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 { StateDialog, StateRowToggle } from "./add-state-dialog";
import type { Country, State } from "@/lib/types";

type StateRow = State & { country: { name: string } | null };

export default async function StatePage() {
  const supabase = await createClient();
  const [{ data: statesData }, { data: countriesData }] = await Promise.all([
    supabase
      .from("states")
      .select("*, country:countries(name)")
      .order("name"),
    supabase.from("countries").select("*").order("name"),
  ]);

  const states = (statesData as StateRow[]) ?? [];
  const countries = (countriesData as Country[]) ?? [];
  const canManage = await canDo("master", "update");

  return (
    <div>
      <PageHeader
        title="State"
        breadcrumb="Master / Course / State"
        action={canManage ? <StateDialog countries={countries} /> : undefined}
      />
      <Card className="p-0">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-16">No</TableHead>
              <TableHead>State</TableHead>
              <TableHead>Country</TableHead>
              <TableHead>Status</TableHead>
              {canManage && <TableHead className="text-right">Actions</TableHead>}
            </TableRow>
          </TableHeader>
          <TableBody>
            {states.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={canManage ? 5 : 4}
                  className="py-10 text-center text-muted-foreground"
                >
                  No states yet.
                </TableCell>
              </TableRow>
            ) : (
              states.map((s, i) => (
                <TableRow key={s.id}>
                  <TableCell className="text-muted-foreground">{i + 1}</TableCell>
                  <TableCell className="font-medium">{s.name}</TableCell>
                  <TableCell>{s.country?.name ?? "—"}</TableCell>
                  <TableCell>
                    <Badge variant={s.is_active ? "default" : "secondary"}>
                      {s.is_active ? "Active" : "Inactive"}
                    </Badge>
                  </TableCell>
                  {canManage && (
                    <TableCell>
                      <div className="flex items-center justify-end gap-2">
                        <StateRowToggle id={s.id} isActive={s.is_active} />
                        <StateDialog countries={countries} state={s} />
                      </div>
                    </TableCell>
                  )}
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>
    </div>
  );
}
