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 { InstituteDialog, InstituteRowToggle } from "./add-institute-dialog";
import type { Country, Institute, State } from "@/lib/types";

type InstituteRow = Institute & {
  country: { name: string } | null;
  state: { name: string } | null;
};

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

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

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