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 { AddFacultyDialog, FacultyRowActions } from "./add-faculty-dialog";
import type { CoachingFaculty } from "@/lib/types";

export default async function FacultyPage() {
  const supabase = await createClient();
  const { data } = await supabase
    .from("coaching_faculty")
    .select("*")
    .order("name");
  const faculty = (data as CoachingFaculty[]) ?? [];
  const canManage = await canDo("master", "update");

  return (
    <div>
      <PageHeader
        title="Faculty"
        breadcrumb="Master / Coaching / Faculty"
        action={canManage ? <AddFacultyDialog /> : undefined}
      />
      <Card className="p-0">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-12">No</TableHead>
              <TableHead>Name</TableHead>
              <TableHead>Subject</TableHead>
              <TableHead>Email</TableHead>
              <TableHead>Phone</TableHead>
              <TableHead>Status</TableHead>
              {canManage && <TableHead className="w-32 text-right">Actions</TableHead>}
            </TableRow>
          </TableHeader>
          <TableBody>
            {faculty.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={canManage ? 7 : 6}
                  className="py-10 text-center text-muted-foreground"
                >
                  No faculty yet. Add your first faculty member to get started.
                </TableCell>
              </TableRow>
            ) : (
              faculty.map((f, i) => (
                <TableRow key={f.id}>
                  <TableCell>{i + 1}</TableCell>
                  <TableCell className="font-medium">{f.name}</TableCell>
                  <TableCell>{f.subject ?? "—"}</TableCell>
                  <TableCell>{f.email ?? "—"}</TableCell>
                  <TableCell>{f.phone ?? "—"}</TableCell>
                  <TableCell>
                    <Badge variant={f.is_active ? "default" : "secondary"}>
                      {f.is_active ? "Active" : "Inactive"}
                    </Badge>
                  </TableCell>
                  {canManage && (
                    <TableCell className="text-right">
                      <FacultyRowActions faculty={f} />
                    </TableCell>
                  )}
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>
    </div>
  );
}
