"use client";

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/app/shadcn_components/ui/table";
import { Button } from "@/app/shadcn_components/ui/button";
import { Badge } from "@/app/shadcn_components/ui/badge";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  COLLABORATORS_QUERY_KEY,
  fetchCollaborators,
} from "./collaboratorsClient";

type Capability = "approver" | "contractor";

type CapabilityEntry = {
  id: string;
  userId: string;
  capability: Capability;
  name: string | null;
  email: string;
};

type CapabilityMap = Record<string, { name: string | null; email: string; capabilities: Capability[] }>;

async function getCapabilities(portfolioId: string): Promise<CapabilityEntry[]> {
  const res = await fetch(`/api/portfolio/${portfolioId}/capabilities`);
  if (!res.ok) throw new Error("Failed to fetch capabilities");
  return res.json();
}

async function assignCapability(
  portfolioId: string,
  userId: string,
  capability: Capability,
): Promise<void> {
  const res = await fetch(`/api/portfolio/${portfolioId}/capabilities`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ userId, capability }),
  });
  if (!res.ok) throw new Error("Failed to assign capability");
}

async function removeCapability(
  portfolioId: string,
  userId: string,
  capability: Capability,
): Promise<void> {
  const res = await fetch(`/api/portfolio/${portfolioId}/capabilities`, {
    method: "DELETE",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ userId, capability }),
  });
  if (!res.ok) throw new Error("Failed to remove capability");
}

export function CapabilitiesCard({ portfolioId }: { portfolioId: string }) {
  const queryClient = useQueryClient();
  const queryKey = ["portfolioCapabilities", portfolioId];

  const { data: entries = [], isLoading: loadingCaps } = useQuery({
    queryKey,
    queryFn: () => getCapabilities(portfolioId),
    enabled: !!portfolioId,
    refetchOnWindowFocus: false,
  });

  const { data: collaboratorsResponse, isLoading: loadingCollabs } = useQuery({
    queryKey: COLLABORATORS_QUERY_KEY(portfolioId),
    queryFn: () => fetchCollaborators(portfolioId),
    enabled: !!portfolioId,
    refetchOnWindowFocus: false,
  });
  const collaborators = collaboratorsResponse?.users ?? [];

  const isLoading = loadingCaps || loadingCollabs;

  // Build a map: userId -> { capabilities: [] }
  const capMap: CapabilityMap = {};
  for (const c of collaborators) {
    capMap[c.userId] = { name: c.name ?? null, email: c.email, capabilities: [] };
  }
  for (const e of entries) {
    if (capMap[e.userId]) {
      capMap[e.userId].capabilities.push(e.capability);
    }
  }

  const toggleMutation = useMutation({
    mutationFn: ({
      userId,
      capability,
      has,
    }: {
      userId: string;
      capability: Capability;
      has: boolean;
    }) =>
      has
        ? removeCapability(portfolioId, userId, capability)
        : assignCapability(portfolioId, userId, capability),
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey });
    },
  });

  const rows = Object.entries(capMap);

  return (
    <div className="rounded-md border border-gray-700 mt-4">
      <Table>
        <TableBody>
          <TableRow>
            <TableHead className="text-brandblue">
              Project Roles:
              <p className="text-xs text-gray-500">
                Assign approver or contractor capabilities to users
              </p>
            </TableHead>
          </TableRow>
          <TableRow>
            <TableCell colSpan={3}>
              <div className="rounded-md border border-gray-200">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Name</TableHead>
                      <TableHead>Email</TableHead>
                      <TableHead>Approver</TableHead>
                      <TableHead>Contractor</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {isLoading ? (
                      <TableRow>
                        <TableCell colSpan={4} className="text-sm text-gray-500">
                          Loading…
                        </TableCell>
                      </TableRow>
                    ) : rows.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={4} className="text-sm text-gray-500">
                          No collaborators yet. Add users in the section above first.
                        </TableCell>
                      </TableRow>
                    ) : (
                      rows.map(([userId, { name, email, capabilities }]) => (
                        <TableRow key={userId}>
                          <TableCell>{name || "—"}</TableCell>
                          <TableCell className="text-sm text-gray-600">{email}</TableCell>
                          <TableCell>
                            <CapabilityToggle
                              has={capabilities.includes("approver")}
                              capability="approver"
                              isPending={toggleMutation.isPending}
                              onToggle={(has) =>
                                toggleMutation.mutate({ userId, capability: "approver", has })
                              }
                            />
                          </TableCell>
                          <TableCell>
                            <CapabilityToggle
                              has={capabilities.includes("contractor")}
                              capability="contractor"
                              isPending={toggleMutation.isPending}
                              onToggle={(has) =>
                                toggleMutation.mutate({ userId, capability: "contractor", has })
                              }
                            />
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </div>
            </TableCell>
          </TableRow>
        </TableBody>
      </Table>
    </div>
  );
}

function CapabilityToggle({
  has,
  capability,
  isPending,
  onToggle,
}: {
  has: boolean;
  capability: Capability;
  isPending: boolean;
  onToggle: (has: boolean) => void;
}) {
  return (
    <Button
      size="sm"
      variant={has ? "default" : "outline"}
      disabled={isPending}
      onClick={() => onToggle(has)}
      className={has ? "bg-brandblue text-white" : ""}
    >
      {has ? (
        <Badge className="bg-transparent text-white p-0 shadow-none">
          {capability === "approver" ? "Approver" : "Contractor"} ✓
        </Badge>
      ) : (
        <span className="text-gray-500">
          Add {capability === "approver" ? "Approver" : "Contractor"}
        </span>
      )}
    </Button>
  );
}
