import { createClient } from "@/lib/supabase/server";
import { canDo } from "@/lib/auth/permissions";
import { PageHeader } from "@/components/layout/page-header";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { CurrencyDialog, CurrencyRowToggle } from "./add-currency-dialog";
import type { CurrencyRate } from "@/lib/types";

export default async function CurrencyRatePage() {
  const supabase = await createClient();
  const { data } = await supabase
    .from("currency_rates")
    .select("*")
    .order("from_currency");

  const rows = (data as CurrencyRate[]) ?? [];
  const canManage = await canDo("master", "update");

  return (
    <div>
      <PageHeader
        title="Currency Rate"
        breadcrumb="Master / Finance / Currency Rate"
        action={canManage ? <CurrencyDialog /> : undefined}
      />
      <Card className="p-0">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-16">No</TableHead>
              <TableHead>From</TableHead>
              <TableHead>To</TableHead>
              <TableHead>Rate</TableHead>
              <TableHead>Effective Date</TableHead>
              <TableHead>Status</TableHead>
              {canManage && <TableHead className="text-right">Actions</TableHead>}
            </TableRow>
          </TableHeader>
          <TableBody>
            {rows.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={canManage ? 7 : 6}
                  className="py-10 text-center text-muted-foreground"
                >
                  No currency rates yet.
                </TableCell>
              </TableRow>
            ) : (
              rows.map((r, i) => (
                <TableRow key={r.id}>
                  <TableCell className="text-muted-foreground">{i + 1}</TableCell>
                  <TableCell className="font-medium">{r.from_currency}</TableCell>
                  <TableCell>{r.to_currency}</TableCell>
                  <TableCell>{r.rate}</TableCell>
                  <TableCell>{r.effective_date ?? "—"}</TableCell>
                  <TableCell>
                    <Badge variant={r.is_active ? "default" : "secondary"}>
                      {r.is_active ? "Active" : "Inactive"}
                    </Badge>
                  </TableCell>
                  {canManage && (
                    <TableCell>
                      <div className="flex items-center justify-end gap-2">
                        <CurrencyRowToggle id={r.id} isActive={r.is_active} />
                        <CurrencyDialog rate={r} />
                      </div>
                    </TableCell>
                  )}
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>
    </div>
  );
}
