import { useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { useLibraryMedia, useCreateMedia, useDeleteMedia, useLibraryMovements, useCreateMovement, useReturnMovement, useLibraryCards, useCreateCard, useStudents } from "@/hooks/queries";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Search, Plus, Book, ArrowUpDown, Trash2, RotateCcw } from "lucide-react";
import { useToast } from "@/hooks/use-toast";

type Tab = "media" | "movements" | "cards";

export default function AdminLibrary() {
  const [search, setSearch] = useState("");
  const [tab, setTab] = useState<Tab>("media");
  const [mediaOpen, setMediaOpen] = useState(false);
  const [moveOpen, setMoveOpen] = useState(false);
  const [mediaForm, setMediaForm] = useState({ name: "", isbn: "", author: "", edition: "" });
  const [moveForm, setMoveForm] = useState({ media_id: "", student_id: "" });
  const [cardOpen, setCardOpen] = useState(false);
  const [cardStudentId, setCardStudentId] = useState("");
  const { toast } = useToast();

  const mediaQ = useLibraryMedia();
  const movQ = useLibraryMovements();
  const cardsQ = useLibraryCards();
  const createMediaMut = useCreateMedia();
  const deleteMediaMut = useDeleteMedia();
  const createMoveMut = useCreateMovement();
  const returnMoveMut = useReturnMovement();
  const createCardMut = useCreateCard();
  const studentsQ = useStudents({ size: 500 });
  const students = studentsQ.data?.items ?? [];

  const loading =
    tab === "media" ? mediaQ.isLoading : tab === "movements" ? movQ.isLoading : cardsQ.isLoading;
  const media = mediaQ.data?.data ?? mediaQ.data?.items ?? [];
  const movements = movQ.data?.data ?? movQ.data?.items ?? [];
  const cards = cardsQ.data?.data ?? cardsQ.data?.items ?? [];

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
      </div>
    );
  }

  const q = search.toLowerCase();
  const filteredMedia = media.filter(
    (m) =>
      m.name?.toLowerCase().includes(q) ||
      m.isbn?.toLowerCase().includes(q) ||
      m.author?.toLowerCase().includes(q),
  );
  const filteredMov = movements.filter(
    (m) =>
      m.media_name?.toLowerCase().includes(q) ||
      m.student_name?.toLowerCase().includes(q) ||
      m.faculty_name?.toLowerCase().includes(q),
  );
  const filteredCards = cards.filter(
    (c) => c.number?.toLowerCase().includes(q) || c.student_name?.toLowerCase().includes(q),
  );

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold">Library</h1>
          <p className="text-muted-foreground">Media, circulation, and library cards.</p>
        </div>
        <div className="flex gap-2">
          {tab === "media" && (
            <Button onClick={() => setMediaOpen(true)}>
              <Plus className="mr-2 h-4 w-4" />
              Add media
            </Button>
          )}
          {tab === "movements" && (
            <Button onClick={() => setMoveOpen(true)}>
              <Plus className="mr-2 h-4 w-4" />
              Issue
            </Button>
          )}
          {tab === "cards" && (
            <Button onClick={() => setCardOpen(true)}>
              <Plus className="mr-2 h-4 w-4" />
              New card
            </Button>
          )}
        </div>
      </div>
      <div className="flex flex-wrap gap-2">
        <Button variant={tab === "media" ? "default" : "outline"} onClick={() => setTab("media")}>
          <Book className="mr-2 h-4 w-4" />
          Media catalog
        </Button>
        <Button variant={tab === "movements" ? "default" : "outline"} onClick={() => setTab("movements")}>
          <ArrowUpDown className="mr-2 h-4 w-4" />
          Movements
        </Button>
        <Button variant={tab === "cards" ? "default" : "outline"} onClick={() => setTab("cards")}>
          Library cards
        </Button>
      </div>
      <div className="relative 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..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="pl-9"
        />
      </div>
      {tab === "media" && (
        <Card>
          <CardContent className="pt-6">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>#</TableHead>
                  <TableHead>Name</TableHead>
                  <TableHead>ISBN</TableHead>
                  <TableHead>Author</TableHead>
                  <TableHead>Edition</TableHead>
                  <TableHead>Type</TableHead>
                  <TableHead>Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredMedia.map((m, i) => (
                  <TableRow key={m.id}>
                    <TableCell>{i + 1}</TableCell>
                    <TableCell className="font-medium">{m.name}</TableCell>
                    <TableCell>{m.isbn}</TableCell>
                    <TableCell>{m.author}</TableCell>
                    <TableCell>{m.edition}</TableCell>
                    <TableCell>{m.media_type}</TableCell>
                    <TableCell>
                      <Button size="sm" variant="ghost" className="text-destructive" onClick={() => { if (!window.confirm("Delete this media?")) return; deleteMediaMut.mutate(m.id, { onSuccess: () => toast({ title: "Deleted" }), onError: (err: Error) => toast({ title: "Error", description: err.message, variant: "destructive" }) }); }}>
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}
      {tab === "movements" && (
        <Card>
          <CardContent className="pt-6">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>#</TableHead>
                  <TableHead>Media</TableHead>
                  <TableHead>Student</TableHead>
                  <TableHead>Faculty</TableHead>
                  <TableHead>Issued Date</TableHead>
                  <TableHead>Return Date</TableHead>
                  <TableHead>State</TableHead>
                  <TableHead>Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredMov.map((m, i) => (
                  <TableRow key={m.id}>
                    <TableCell>{i + 1}</TableCell>
                    <TableCell className="font-medium">{m.media_name}</TableCell>
                    <TableCell>{m.student_name}</TableCell>
                    <TableCell>{m.faculty_name}</TableCell>
                    <TableCell>{m.issued_date}</TableCell>
                    <TableCell>{m.return_date}</TableCell>
                    <TableCell>
                      <Badge variant="outline">{m.state}</Badge>
                    </TableCell>
                    <TableCell>
                      {m.state === "issue" && (
                        <Button size="sm" variant="ghost" onClick={() => returnMoveMut.mutate(m.id, { onSuccess: () => toast({ title: "Returned" }), onError: (err: Error) => toast({ title: "Error", description: err.message, variant: "destructive" }) })}>
                          <RotateCcw className="h-4 w-4 mr-1" /> Return
                        </Button>
                      )}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}
      {tab === "cards" && (
        <Card>
          <CardContent className="pt-6">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>#</TableHead>
                  <TableHead>Number</TableHead>
                  <TableHead>Student</TableHead>
                  <TableHead>Faculty</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredCards.map((c, i) => (
                  <TableRow key={c.id}>
                    <TableCell>{i + 1}</TableCell>
                    <TableCell className="font-medium">{c.number}</TableCell>
                    <TableCell>{c.student_name}</TableCell>
                    <TableCell>{c.faculty_name}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      <Dialog open={mediaOpen} onOpenChange={setMediaOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Add media</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Name</Label>
              <Input
                value={mediaForm.name}
                onChange={(e) => setMediaForm((f) => ({ ...f, name: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label>ISBN</Label>
              <Input
                value={mediaForm.isbn}
                onChange={(e) => setMediaForm((f) => ({ ...f, isbn: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label>Author</Label>
              <Input
                value={mediaForm.author}
                onChange={(e) => setMediaForm((f) => ({ ...f, author: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label>Edition</Label>
              <Input
                value={mediaForm.edition}
                onChange={(e) => setMediaForm((f) => ({ ...f, edition: e.target.value }))}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setMediaOpen(false)}>
              Cancel
            </Button>
            <Button
              disabled={createMediaMut.isPending || !mediaForm.name.trim()}
              onClick={() =>
                createMediaMut.mutate(
                  {
                    name: mediaForm.name.trim(),
                    isbn: mediaForm.isbn || undefined,
                    author: mediaForm.author || undefined,
                    edition: mediaForm.edition || undefined,
                  },
                  {
                    onSuccess: () => {
                      setMediaOpen(false);
                      setMediaForm({ name: "", isbn: "", author: "", edition: "" });
                      toast({ title: "Created successfully" });
                    },
                    onError: (err: Error) =>
                      toast({ title: "Error", description: err.message, variant: "destructive" }),
                  },
                )
              }
            >
              Save
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={moveOpen} onOpenChange={setMoveOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Issue movement</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Media</Label>
              <Select value={moveForm.media_id || "__none__"} onValueChange={(v) => setMoveForm((f) => ({ ...f, media_id: v === "__none__" ? "" : v }))}>
                <SelectTrigger><SelectValue placeholder="Select media" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="__none__">— Select —</SelectItem>
                  {media.map((m) => (<SelectItem key={m.id} value={String(m.id)}>{m.name}</SelectItem>))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Student</Label>
              <Select value={moveForm.student_id || "__none__"} onValueChange={(v) => setMoveForm((f) => ({ ...f, student_id: v === "__none__" ? "" : v }))}>
                <SelectTrigger><SelectValue placeholder="Select student" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="__none__">— Select —</SelectItem>
                  {students.map((s) => (<SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>))}
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setMoveOpen(false)}>Cancel</Button>
            <Button
              disabled={createMoveMut.isPending || !moveForm.media_id || !moveForm.student_id}
              onClick={() => createMoveMut.mutate(
                { media_id: Number(moveForm.media_id), student_id: Number(moveForm.student_id) },
                {
                  onSuccess: () => { setMoveOpen(false); setMoveForm({ media_id: "", student_id: "" }); toast({ title: "Issued" }); },
                  onError: (err: Error) => toast({ title: "Error", description: err.message, variant: "destructive" }),
                },
              )}
            >
              Issue
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={cardOpen} onOpenChange={setCardOpen}>
        <DialogContent>
          <DialogHeader><DialogTitle>Create library card</DialogTitle></DialogHeader>
          <div className="space-y-2">
            <Label>Student</Label>
            <Select value={cardStudentId || "__none__"} onValueChange={(v) => setCardStudentId(v === "__none__" ? "" : v)}>
              <SelectTrigger><SelectValue placeholder="Select student" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="__none__">— Select —</SelectItem>
                {students.map((s) => (<SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>))}
              </SelectContent>
            </Select>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setCardOpen(false)}>Cancel</Button>
            <Button disabled={createCardMut.isPending || !cardStudentId} onClick={() => createCardMut.mutate({ student_id: Number(cardStudentId) }, { onSuccess: () => { setCardOpen(false); setCardStudentId(""); toast({ title: "Card created" }); }, onError: (err: Error) => toast({ title: "Error", description: err.message, variant: "destructive" }) })}>
              Create
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
