import { useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Building2, Loader2, Pencil, Plus, Trash2 } from "lucide-react";

import { lmsService } from "@/services/lms.service";
import type { LmsBranch } from "@/types";
import { useAuth } from "@/contexts/AuthContext";
import { useToast } from "@/hooks/use-toast";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";

type BranchForm = {
  name: string;
  code: string;
  notes: string;
  active: boolean;
};

const EMPTY_FORM: BranchForm = { name: "", code: "", notes: "", active: true };

export default function AdminBranches() {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const { selectedEntity } = useAuth();

  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState<LmsBranch | null>(null);
  const [search, setSearch] = useState("");
  const [form, setForm] = useState<BranchForm>(EMPTY_FORM);

  const branchesQ = useQuery({
    queryKey: ["lms-branches", selectedEntity?.id ?? 0, search],
    queryFn: async () => {
      const res = await lmsService.listBranches({
        size: 200,
        search: search.trim() || undefined,
      });
      return res.items;
    },
  });

  const createMut = useMutation({
    mutationFn: (payload: Partial<LmsBranch>) => lmsService.createBranch(payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["lms-branches"] });
      setOpen(false);
      setEditing(null);
      setForm(EMPTY_FORM);
      toast({ title: "Branch created" });
    },
    onError: () => toast({ title: "Error", description: "Failed to create branch", variant: "destructive" }),
  });

  const updateMut = useMutation({
    mutationFn: ({ id, payload }: { id: number; payload: Partial<LmsBranch> }) =>
      lmsService.updateBranch(id, payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["lms-branches"] });
      setOpen(false);
      setEditing(null);
      setForm(EMPTY_FORM);
      toast({ title: "Branch updated" });
    },
    onError: () => toast({ title: "Error", description: "Failed to update branch", variant: "destructive" }),
  });

  const deleteMut = useMutation({
    mutationFn: (id: number) => lmsService.deleteBranch(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["lms-branches"] });
      toast({ title: "Branch deleted" });
    },
    onError: () => toast({ title: "Error", description: "Failed to delete branch", variant: "destructive" }),
  });

  const isSaving = createMut.isPending || updateMut.isPending;
  const rows = useMemo(() => branchesQ.data ?? [], [branchesQ.data]);

  const openCreate = () => {
    setEditing(null);
    setForm(EMPTY_FORM);
    setOpen(true);
  };

  const openEdit = (row: LmsBranch) => {
    setEditing(row);
    setForm({
      name: row.name || "",
      code: row.code || "",
      notes: row.notes || "",
      active: !!row.active,
    });
    setOpen(true);
  };

  const onSave = () => {
    const payload: Partial<LmsBranch> = {
      name: form.name.trim(),
      code: form.code.trim(),
      notes: form.notes.trim(),
      active: form.active,
    };
    if (!payload.name) return;
    if (editing) {
      updateMut.mutate({ id: editing.id, payload });
      return;
    }
    createMut.mutate(payload);
  };

  const onDelete = (row: LmsBranch) => {
    if (!window.confirm(`Delete branch "${row.name}"?`)) return;
    deleteMut.mutate(row.id);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold">Branches</h1>
          <p className="text-muted-foreground">
            Create branches per entity to organize courses, batches, teachers, and students.
          </p>
        </div>
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger asChild>
            <Button onClick={openCreate}>
              <Plus className="mr-2 h-4 w-4" />
              Add Branch
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{editing ? "Edit Branch" : "Create Branch"}</DialogTitle>
            </DialogHeader>
            <div className="space-y-4 pt-2">
              <div className="space-y-2">
                <Label>Branch name</Label>
                <Input
                  value={form.name}
                  onChange={(e) => setForm((prev) => ({ ...prev, name: e.target.value }))}
                  placeholder="e.g. Riyadh Main Campus"
                />
              </div>
              <div className="space-y-2">
                <Label>Branch code</Label>
                <Input
                  value={form.code}
                  onChange={(e) => setForm((prev) => ({ ...prev, code: e.target.value }))}
                  placeholder="e.g. RUH_MAIN"
                />
              </div>
              <div className="space-y-2">
                <Label>Notes</Label>
                <Textarea
                  value={form.notes}
                  onChange={(e) => setForm((prev) => ({ ...prev, notes: e.target.value }))}
                  placeholder="Optional notes for managers"
                />
              </div>
              <div className="flex items-center justify-between rounded-md border p-3">
                <div>
                  <p className="text-sm font-medium">Active</p>
                  <p className="text-xs text-muted-foreground">Inactive branches stay in history but are hidden from active workflows.</p>
                </div>
                <Switch
                  checked={form.active}
                  onCheckedChange={(checked) => setForm((prev) => ({ ...prev, active: checked }))}
                />
              </div>
              <Button className="w-full" onClick={onSave} disabled={isSaving || !form.name.trim()}>
                {isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                {editing ? "Update Branch" : "Create Branch"}
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <Card>
        <CardContent className="pt-6 space-y-4">
          <div className="flex items-center gap-2">
            <Input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search branches by name or code"
            />
          </div>

          {branchesQ.isLoading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Name</TableHead>
                  <TableHead>Code</TableHead>
                  <TableHead>Entity</TableHead>
                  <TableHead>Shared LMS</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {rows.map((row) => (
                  <TableRow key={row.id}>
                    <TableCell className="font-medium">{row.name}</TableCell>
                    <TableCell>{row.code || "—"}</TableCell>
                    <TableCell>{row.entity_name || "—"}</TableCell>
                    <TableCell>
                      <div className="text-xs text-muted-foreground">
                        C:{row.course_count} B:{row.batch_count} S:{row.student_count} T:{row.teacher_count}
                      </div>
                    </TableCell>
                    <TableCell>
                      {row.active ? (
                        <span className="inline-flex items-center rounded bg-emerald-100 px-2 py-0.5 text-xs text-emerald-700">Active</span>
                      ) : (
                        <span className="inline-flex items-center rounded bg-slate-100 px-2 py-0.5 text-xs text-slate-600">Inactive</span>
                      )}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex items-center justify-end gap-1">
                        <Button variant="ghost" size="icon" onClick={() => openEdit(row)}>
                          <Pencil className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="icon" onClick={() => onDelete(row)} disabled={deleteMut.isPending}>
                          <Trash2 className="h-4 w-4 text-destructive" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
                {rows.length === 0 && (
                  <TableRow>
                    <TableCell colSpan={6} className="py-12 text-center text-muted-foreground">
                      <div className="flex flex-col items-center gap-2">
                        <Building2 className="h-5 w-5" />
                        <span>No branches found for this entity.</span>
                      </div>
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}

