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 { AddUserDialog } from "./add-user-dialog";
import { UserRowActions } from "./user-row-actions";
import { UserSearch } from "./user-search";
import { PaginationControl } from "@/components/ui/pagination-control";
import type { Branch, Role } from "@/lib/types";

const PAGE_SIZE = 10;

interface UserRow {
  id: string;
  full_name: string;
  email: string;
  phone: string | null;
  status: string;
  role_id: string;
  primary_branch_id: string;
  joining_date: string | null;
  date_of_birth: string | null;
  b2b_country: string | null;
  b2b_state: string | null;
  allowed_ips: string[] | null;
  role: { name: string } | null;
  branch: { name: string } | null;
}

export default async function UserManagementPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string; page?: string }>;
}) {
  const sp = await searchParams;
  const q = sp.q?.trim() ?? "";
  const page = Math.max(1, Number(sp.page) || 1);
  const from = (page - 1) * PAGE_SIZE;

  const supabase = await createClient();

  let query = supabase
    .from("users")
    .select(
      "id, full_name, email, phone, status, role_id, primary_branch_id, joining_date, date_of_birth, b2b_country, b2b_state, allowed_ips, role:roles(name), branch:branches!users_primary_branch_id_fkey(name)",
      { count: "exact" }
    )
    .order("created_at", { ascending: false });

  if (q) {
    query = query.or(`full_name.ilike.%${q}%,email.ilike.%${q}%,phone.ilike.%${q}%`);
  }

  const [{ data: users, count }, { data: roles }, { data: branches }] =
    await Promise.all([
      query.range(from, from + PAGE_SIZE - 1),
      supabase.from("roles").select("*").order("name"),
      supabase.from("branches").select("*").eq("is_active", true).order("name"),
    ]);

  const rows = (users as unknown as UserRow[]) ?? [];
  const canManage = await canDo("users", "update");

  return (
    <div>
      <PageHeader
        title="User Management"
        breadcrumb="Home / User"
        action={
          canManage ? (
            <AddUserDialog
              roles={(roles as Role[]) ?? []}
              branches={(branches as Branch[]) ?? []}
            />
          ) : undefined
        }
      />
      <UserSearch initialQ={q} />
      <Card className="p-0">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Name</TableHead>
              <TableHead>Email</TableHead>
              <TableHead>Phone</TableHead>
              <TableHead>Branch</TableHead>
              <TableHead>Role</TableHead>
              <TableHead>Status</TableHead>
              {canManage && <TableHead className="w-[80px] text-right">Actions</TableHead>}
            </TableRow>
          </TableHeader>
          <TableBody>
            {rows.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="py-10 text-center text-muted-foreground">
                  No users yet.
                </TableCell>
              </TableRow>
            ) : (
              rows.map((u) => (
                <TableRow key={u.id}>
                  <TableCell className="font-medium">{u.full_name}</TableCell>
                  <TableCell>{u.email}</TableCell>
                  <TableCell>{u.phone ?? "—"}</TableCell>
                  <TableCell>{u.branch?.name ?? "—"}</TableCell>
                  <TableCell>{u.role?.name ?? "—"}</TableCell>
                  <TableCell>
                    <Badge variant={u.status === "active" ? "default" : "secondary"}>
                      {u.status}
                    </Badge>
                  </TableCell>
                  {canManage && (
                    <TableCell className="text-right">
                      <UserRowActions
                        user={u}
                        roles={(roles as Role[]) ?? []}
                        branches={(branches as Branch[]) ?? []}
                      />
                    </TableCell>
                  )}
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>
      {(count ?? 0) > PAGE_SIZE && (
        <div className="mt-4">
          <PaginationControl page={page} pageSize={PAGE_SIZE} total={count ?? 0} />
        </div>
      )}
    </div>
  );
}
