import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { router } from "@inertiajs/react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { toast } from "sonner";
import { Pencil, Trash2 } from "lucide-react";
import BulkDelegateImport from "@/components/company-portal/BulkDelegateImport";

const csrfToken = () =>
  (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? "";

interface Delegate {
  id: string;
  company_id: string;
  first_name: string;
  last_name: string;
  email: string | null;
  phone: string | null;
  status: string;
}

const emptyDelegate = { first_name: "", last_name: "", email: "", phone: "", status: "active" };

export const CompanyMembersTab = ({ companyId }: { companyId: string }) => {
  const queryClient = useQueryClient();
  const [createForm, setCreateForm] = useState(emptyDelegate);
  const [editForm, setEditForm] = useState(emptyDelegate);
  const [editingDelegate, setEditingDelegate] = useState<Delegate | null>(null);
  const [editOpen, setEditOpen] = useState(false);

  const { data: delegates, isLoading } = useQuery({
    queryKey: ["delegates", companyId],
    queryFn: async (): Promise<Delegate[]> => {
      const res = await fetch(`/api/admin/companies/${companyId}/delegates`);
      if (!res.ok) return [];
      return res.json();
    },
  });

  const createMutation = useMutation({
    mutationFn: async (values: typeof createForm) => {
      const res = await fetch(`/api/admin/companies/${companyId}/delegates`, {
        method: "POST",
        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken() },
        body: JSON.stringify({
          company_id: companyId,
          first_name: values.first_name.trim(),
          last_name: values.last_name.trim(),
          email: values.email.trim() || null,
          phone: values.phone.trim() || null,
          status: values.status,
        }),
      });
      if (!res.ok) throw new Error("Failed to create delegate");
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["delegates", companyId] });
      toast.success("Delegate added");
      setCreateForm(emptyDelegate);
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const updateMutation = useMutation({
    mutationFn: async ({ delegateId, values }: { delegateId: string; values: typeof editForm }) => {
      const res = await fetch(`/api/admin/delegates/${delegateId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken() },
        body: JSON.stringify({
          first_name: values.first_name.trim(),
          last_name: values.last_name.trim(),
          email: values.email.trim() || null,
          phone: values.phone.trim() || null,
          status: values.status,
        }),
      });
      if (!res.ok) throw new Error("Failed to update delegate");
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["delegates", companyId] });
      toast.success("Delegate updated");
      setEditOpen(false);
      setEditingDelegate(null);
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const deleteMutation = useMutation({
    mutationFn: async (delegateId: string) => {
      const res = await fetch(`/api/admin/delegates/${delegateId}`, {
        method: "DELETE",
        headers: { "X-CSRF-TOKEN": csrfToken() },
      });
      if (!res.ok) throw new Error("Failed to delete delegate");
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["delegates", companyId] });
      toast.success("Delegate deleted");
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const openEditDialog = (d: Delegate) => {
    setEditingDelegate(d);
    setEditForm({
      first_name: d.first_name,
      last_name: d.last_name,
      email: d.email || "",
      phone: d.phone || "",
      status: d.status,
    });
    setEditOpen(true);
  };

  return (
    <div className="space-y-6">
      {/* Delegates Table */}
      <div className="bg-card border border-border rounded-xl overflow-hidden">
        <div className="px-4 py-3 border-b border-border">
          <h2 className="text-lg font-semibold text-primary">Assigned Delegates</h2>
        </div>
        {isLoading ? (
          <p className="text-muted-foreground p-4">Loading delegates...</p>
        ) : (
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Name</TableHead>
                <TableHead>Email</TableHead>
                <TableHead>Phone</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="w-[120px]">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {delegates?.map((d) => (
                <TableRow key={d.id}>
                  <TableCell className="font-medium">
                    <button
                      className="text-left hover:underline text-primary cursor-pointer"
                      onClick={() => router.visit(`/admin/delegates/${d.id}`)}
                    >
                      {d.first_name} {d.last_name}
                    </button>
                  </TableCell>
                  <TableCell>{d.email || "—"}</TableCell>
                  <TableCell>{d.phone || "—"}</TableCell>
                  <TableCell>
                    <Badge variant={d.status === "active" ? "default" : "destructive"} className="capitalize">{d.status}</Badge>
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      <Button variant="outline" size="sm" onClick={() => openEditDialog(d)}>
                        <Pencil className="h-3 w-3 mr-1" /> Edit
                      </Button>
                      <Button variant="destructive" size="sm" onClick={() => deleteMutation.mutate(d.id)}>
                        <Trash2 className="h-3 w-3 mr-1" /> Delete
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
              {delegates?.length === 0 && (
                <TableRow>
                  <TableCell colSpan={5} className="text-center text-muted-foreground py-8">No delegates assigned yet.</TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        )}
      </div>

      {/* Add New Delegate */}
      <div className="bg-card border border-border rounded-xl p-6">
        <h2 className="text-lg font-semibold text-foreground mb-4">Add New Delegate</h2>
        <form onSubmit={(e) => { e.preventDefault(); createMutation.mutate(createForm); }} className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>First Name</Label>
              <Input value={createForm.first_name} onChange={(e) => setCreateForm((f) => ({ ...f, first_name: e.target.value }))} required maxLength={100} />
            </div>
            <div className="space-y-2">
              <Label>Last Name</Label>
              <Input value={createForm.last_name} onChange={(e) => setCreateForm((f) => ({ ...f, last_name: e.target.value }))} required maxLength={100} />
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Email</Label>
              <Input type="email" value={createForm.email} onChange={(e) => setCreateForm((f) => ({ ...f, email: e.target.value }))} maxLength={255} />
            </div>
            <div className="space-y-2">
              <Label>Phone</Label>
              <Input value={createForm.phone} onChange={(e) => setCreateForm((f) => ({ ...f, phone: e.target.value }))} maxLength={30} />
            </div>
          </div>
          <div className="w-1/2">
            <div className="space-y-2">
              <Label>Status</Label>
              <Select value={createForm.status} onValueChange={(v) => setCreateForm((f) => ({ ...f, status: v }))}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="active">Active</SelectItem>
                  <SelectItem value="inactive">Inactive</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <Button type="submit" variant="hero" disabled={createMutation.isPending}>
            {createMutation.isPending ? "Creating..." : "Create Delegate"}
          </Button>
        </form>
      </div>

      {/* Bulk CSV Import */}
      <BulkDelegateImport companyId={companyId} />
      <Dialog open={editOpen} onOpenChange={(v) => { if (!v) setEditingDelegate(null); setEditOpen(v); }}>
        <DialogContent>
          <DialogHeader><DialogTitle>Edit Delegate</DialogTitle></DialogHeader>
          <form onSubmit={(e) => { e.preventDefault(); if (editingDelegate) updateMutation.mutate({ delegateId: editingDelegate.id, values: editForm }); }} className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>First Name</Label>
                <Input value={editForm.first_name} onChange={(e) => setEditForm((f) => ({ ...f, first_name: e.target.value }))} required maxLength={100} />
              </div>
              <div className="space-y-2">
                <Label>Last Name</Label>
                <Input value={editForm.last_name} onChange={(e) => setEditForm((f) => ({ ...f, last_name: e.target.value }))} required maxLength={100} />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Email</Label>
                <Input type="email" value={editForm.email} onChange={(e) => setEditForm((f) => ({ ...f, email: e.target.value }))} maxLength={255} />
              </div>
              <div className="space-y-2">
                <Label>Phone</Label>
                <Input value={editForm.phone} onChange={(e) => setEditForm((f) => ({ ...f, phone: e.target.value }))} maxLength={30} />
              </div>
            </div>
            <div className="space-y-2">
              <Label>Status</Label>
              <Select value={editForm.status} onValueChange={(v) => setEditForm((f) => ({ ...f, status: v }))}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="active">Active</SelectItem>
                  <SelectItem value="inactive">Inactive</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <Button type="submit" variant="hero" className="w-full" disabled={updateMutation.isPending}>
              {updateMutation.isPending ? "Saving..." : "Save Changes"}
            </Button>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
};
