"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Plus, RefreshCw } from "lucide-react";
import { toast } from "react-hot-toast";
import { Panel, EmptyState } from "@/components/shared/panel";
import { StatusBadge } from "@/components/shared/status-badge";
import { Button } from "@/components/ui/button";
import { CreateSiteManagerDialog } from "./create-site-manager-dialog";
import { SiteManagerDetailsDialog } from "./site-manager-details-dialog";
import type { Location } from "./types";
import type { LocationSiteManagerAccount } from "./related-api-contract";

export function LocationAccounts({ location, accounts, error, source, canManageSiteManagers = true }: {
  location: Pick<Location, "id" | "name">;
  accounts?: LocationSiteManagerAccount[];
  error?: string;
  source: "api" | "preview";
  canManageSiteManagers?: boolean;
}) {
  const [creating, setCreating] = useState(false);
  const [refreshing, startRefresh] = useTransition();
  const router = useRouter();
  return <Panel title="Accounts" description={`Site Managers assigned to ${location.name}`} actions={<div className="flex flex-wrap gap-2">
    {source === "api" && <Button variant="outline" size="sm" disabled={refreshing} onClick={() => startRefresh(() => router.refresh())}><RefreshCw aria-hidden="true" className={refreshing ? "animate-spin motion-reduce:animate-none" : ""} />{refreshing ? "Refreshing…" : "Refresh"}</Button>}
    {canManageSiteManagers && <Button size="sm" disabled={source !== "api"} onClick={() => setCreating(true)}><Plus aria-hidden="true" />Add Site Manager</Button>}
  </div>}>
    {error ? <div role="alert" className="rounded-lg border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive"><p className="font-medium">Site Manager list unavailable</p><p className="mt-1">{error}</p></div>
      : accounts === undefined ? <EmptyState title="Site Manager data unavailable" description="Connect the CSMS API to manage accounts assigned to this location." />
      : !accounts.length ? <EmptyState title="No Site Managers assigned" description={canManageSiteManagers ? "Add a Site Manager to give them access to this location." : "No Site Managers are assigned to this location."} />
      : <div className="overflow-x-auto rounded-lg border border-border"><table className="data-table min-w-[760px]"><caption className="sr-only">Site Managers assigned to {location.name}</caption>
        <thead><tr><th scope="col">Account</th><th scope="col">Email</th><th scope="col">Phone</th><th scope="col">Status</th>{source === "api" && <th scope="col">Actions</th>}</tr></thead>
        <tbody>{accounts.map(account => <tr key={account.id}><td className="font-medium">{account.name}</td><td>{account.email || "—"}</td><td className="whitespace-nowrap">{account.phone || "—"}</td><td><StatusBadge tone={account.active ? "success" : "neutral"}>{account.active ? "Active" : "Inactive"}</StatusBadge></td>{source === "api" && <td><SiteManagerDetailsDialog location={location} account={account} onChanged={() => router.refresh()} readOnly={!canManageSiteManagers} /></td>}</tr>)}</tbody>
      </table></div>}
    {canManageSiteManagers && source === "api" && creating && <CreateSiteManagerDialog location={location} onOpenChange={setCreating} onCreated={() => {
      setCreating(false); toast.success("Site Manager created and assigned to this location."); router.refresh();
    }} />}
  </Panel>;
}
