import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
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 { Search, Plus, Building2, Trash2, Pencil, Users, Shield } from "lucide-react";
import { entitiesService } from "@/services/entities.service";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useToast } from "@/hooks/use-toast";

const ENTITY_TYPES = [
  { value: "corporate", label: "Corporate" },
  { value: "university", label: "University" },
  { value: "school", label: "School" },
  { value: "government", label: "Government" },
  { value: "freelance", label: "Freelance" },
];

export default function EntitiesPage() {
  const [search, setSearch] = useState("");
  const [createOpen, setCreateOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  const [editEntity, setEditEntity] = useState<{ id: number; name: string; code: string; type: string } | null>(null);
  const [form, setForm] = useState({ name: "", code: "", type: "" });
  const { toast } = useToast();
  const qc = useQueryClient();

  const entitiesQ = useQuery({
    queryKey: ["entities"],
    queryFn: () => entitiesService.list({ size: 200 }),
  });

  const createMut = useMutation({
    mutationFn: (data: { name: string; code?: string; type?: string }) =>
      entitiesService.create(data as Partial<import("@/types").Entity>),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["entities"] });
      setCreateOpen(false);
      setForm({ name: "", code: "", type: "" });
      toast({ title: "Entity created" });
    },
    onError: (err: Error) => toast({ title: "Error", description: err.message, variant: "destructive" }),
  });

  const updateMut = useMutation({
    mutationFn: ({ id, data }: { id: number; data: Record<string, unknown> }) =>
      entitiesService.update(id, data as Partial<import("@/types").Entity>),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["entities"] });
      setEditOpen(false);
      toast({ title: "Entity updated" });
    },
    onError: (err: Error) => toast({ title: "Error", description: err.message, variant: "destructive" }),
  });

  const deleteMut = useMutation({
    mutationFn: (id: number) => entitiesService.delete(id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["entities"] });
      toast({ title: "Deleted" });
    },
    onError: (err: Error) => toast({ title: "Error", description: err.message, variant: "destructive" }),
  });

  const raw = entitiesQ.data as unknown;
  const entities: { id: number; name: string; code: string; type: string; user_count: number; role_count: number; active: boolean }[] = (() => {
    if (!raw) return [];
    if (Array.isArray(raw)) return raw as never[];
    const r = raw as { items?: unknown; data?: unknown };
    const arr = (r.items ?? r.data ?? []) as never[];
    return Array.isArray(arr) ? arr : [];
  })();

  const filtered = entities.filter(
    (e) =>
      e.name?.toLowerCase().includes(search.toLowerCase()) ||
      e.code?.toLowerCase().includes(search.toLowerCase()),
  );
  const loading = entitiesQ.isLoading;

  function openEdit(e: typeof entities[0]) {
    setEditEntity({ id: e.id, name: e.name, code: e.code, type: e.type });
    setEditOpen(true);
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Entities</h1>
          <p className="text-muted-foreground">Manage organizations and entities on the platform.</p>
        </div>
        <Button size="sm" onClick={() => setCreateOpen(true)}>
          <Plus className="h-4 w-4 mr-1" /> Create Entity
        </Button>
      </div>

      <div className="flex gap-4 items-center">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input placeholder="Search entities..." className="pl-9" value={search} onChange={(e) => setSearch(e.target.value)} />
        </div>
        <Badge variant="secondary">{entities.length} total</Badge>
      </div>

      {loading ? (
        <div className="flex items-center justify-center min-h-[300px]">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
        </div>
      ) : (
        <Card className="border-0 shadow-sm">
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Name</TableHead>
                  <TableHead>Code</TableHead>
                  <TableHead>Type</TableHead>
                  <TableHead>Users</TableHead>
                  <TableHead>Roles</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="w-24" />
                </TableRow>
              </TableHeader>
              <TableBody>
                {filtered.length === 0 && (
                  <TableRow>
                    <TableCell colSpan={7} className="text-center text-muted-foreground py-8">
                      No entities found.
                    </TableCell>
                  </TableRow>
                )}
                {filtered.map((e) => (
                  <TableRow key={e.id}>
                    <TableCell className="font-medium">
                      <div className="flex items-center gap-2">
                        <Building2 className="h-4 w-4 text-primary" />
                        {e.name}
                      </div>
                    </TableCell>
                    <TableCell><code className="text-xs bg-muted px-1.5 py-0.5 rounded">{e.code}</code></TableCell>
                    <TableCell>
                      <Badge variant="outline" className="capitalize">{e.type || "—"}</Badge>
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary"><Users className="h-3 w-3 mr-1" />{e.user_count ?? 0}</Badge>
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary"><Shield className="h-3 w-3 mr-1" />{e.role_count ?? 0}</Badge>
                    </TableCell>
                    <TableCell>
                      <Badge variant={e.active !== false ? "default" : "secondary"}>
                        {e.active !== false ? "Active" : "Inactive"}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div className="flex gap-1">
                        <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => openEdit(e)}>
                          <Pencil className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 text-destructive"
                          onClick={() => {
                            if (window.confirm(`Delete entity "${e.name}"?`))
                              deleteMut.mutate(e.id);
                          }}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* Create Dialog */}
      <Dialog open={createOpen} onOpenChange={setCreateOpen}>
        <DialogContent>
          <DialogHeader><DialogTitle>Create Entity</DialogTitle></DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Name</Label>
              <Input value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))} placeholder="Organization name" />
            </div>
            <div className="space-y-2">
              <Label>Code</Label>
              <Input value={form.code} onChange={(e) => setForm((f) => ({ ...f, code: e.target.value }))} placeholder="ORG_CODE (auto-generated if empty)" />
            </div>
            <div className="space-y-2">
              <Label>Type</Label>
              <Select value={form.type} onValueChange={(v) => setForm((f) => ({ ...f, type: v }))}>
                <SelectTrigger><SelectValue placeholder="Select type" /></SelectTrigger>
                <SelectContent>
                  {ENTITY_TYPES.map((t) => (
                    <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setCreateOpen(false)}>Cancel</Button>
            <Button
              disabled={createMut.isPending || !form.name.trim()}
              onClick={() =>
                createMut.mutate({
                  name: form.name.trim(),
                  code: form.code.trim() || undefined,
                  type: form.type || undefined,
                })
              }
            >
              {createMut.isPending ? "Creating..." : "Create"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Edit Dialog */}
      <Dialog open={editOpen} onOpenChange={setEditOpen}>
        <DialogContent>
          <DialogHeader><DialogTitle>Edit Entity</DialogTitle></DialogHeader>
          {editEntity && (
            <div className="space-y-4">
              <div className="space-y-2">
                <Label>Name</Label>
                <Input
                  value={editEntity.name}
                  onChange={(e) => setEditEntity((prev) => prev ? { ...prev, name: e.target.value } : prev)}
                />
              </div>
              <div className="space-y-2">
                <Label>Code</Label>
                <Input
                  value={editEntity.code}
                  onChange={(e) => setEditEntity((prev) => prev ? { ...prev, code: e.target.value } : prev)}
                />
              </div>
              <div className="space-y-2">
                <Label>Type</Label>
                <Select
                  value={editEntity.type}
                  onValueChange={(v) => setEditEntity((prev) => prev ? { ...prev, type: v } : prev)}
                >
                  <SelectTrigger><SelectValue placeholder="Select type" /></SelectTrigger>
                  <SelectContent>
                    {ENTITY_TYPES.map((t) => (
                      <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setEditOpen(false)}>Cancel</Button>
            <Button
              disabled={updateMut.isPending || !editEntity?.name.trim()}
              onClick={() => {
                if (!editEntity) return;
                updateMut.mutate({
                  id: editEntity.id,
                  data: { name: editEntity.name, code: editEntity.code, type: editEntity.type },
                });
              }}
            >
              {updateMut.isPending ? "Saving..." : "Save"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
