import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Plus, Trash2, Pencil, Loader2, HelpCircle, FolderOpen, GripVertical } from "lucide-react";
import { useFaqCategories, useFaqItems, useCreateFaqCategory, useUpdateFaqCategory, useDeleteFaqCategory, useCreateFaqItem, useUpdateFaqItem, useDeleteFaqItem } from "@/hooks/queries";
import { useToast } from "@/hooks/use-toast";
import type { FaqAudience, FaqCategory, FaqItem } from "@/types/faq";

export default function FaqManager() {
  const { toast } = useToast();
  const { data: categories = [], isLoading: lc } = useFaqCategories();
  const [selectedCatId, setSelectedCatId] = useState<number | null>(null);
  const { data: items = [], isLoading: li } = useFaqItems(selectedCatId ? { category_id: selectedCatId } : undefined);
  const createCategory = useCreateFaqCategory();
  const updateCategory = useUpdateFaqCategory();
  const deleteCategory = useDeleteFaqCategory();
  const createItem = useCreateFaqItem();
  const updateItem = useUpdateFaqItem();
  const deleteItem = useDeleteFaqItem();

  const [showAddCat, setShowAddCat] = useState(false);
  const [catName, setCatName] = useState("");
  const [catAudience, setCatAudience] = useState<FaqAudience>("both");

  const [showAddItem, setShowAddItem] = useState(false);
  const [editingItem, setEditingItem] = useState<FaqItem | null>(null);
  const [itemQuestion, setItemQuestion] = useState("");
  const [itemAnswer, setItemAnswer] = useState("");
  const [itemAudience, setItemAudience] = useState<FaqAudience>("both");
  const [itemVideoUrl, setItemVideoUrl] = useState("");

  const [editingCat, setEditingCat] = useState<FaqCategory | null>(null);
  const [editCatName, setEditCatName] = useState("");

  const resetItemForm = () => { setItemQuestion(""); setItemAnswer(""); setItemAudience("both"); setItemVideoUrl(""); setEditingItem(null); };

  const handleCreateCategory = () => {
    createCategory.mutate(
      { name: catName, audience: catAudience },
      {
        onSuccess: () => { toast({ title: "Category Created" }); setShowAddCat(false); setCatName(""); },
        onError: () => toast({ title: "Error", description: "Failed to create category", variant: "destructive" }),
      },
    );
  };

  const handleUpdateCategory = () => {
    if (!editingCat) return;
    updateCategory.mutate(
      { id: editingCat.id, data: { name: editCatName } },
      {
        onSuccess: () => { toast({ title: "Category Updated" }); setEditingCat(null); },
        onError: () => toast({ title: "Error", description: "Failed to update category", variant: "destructive" }),
      },
    );
  };

  const handleDeleteCategory = (id: number) => {
    if (!window.confirm("Delete this FAQ category and all its items?")) return;
    deleteCategory.mutate(id, {
      onSuccess: () => { toast({ title: "Category Deleted" }); if (selectedCatId === id) setSelectedCatId(null); },
      onError: () => toast({ title: "Error", description: "Failed to delete category", variant: "destructive" }),
    });
  };

  const handleSaveItem = () => {
    if (editingItem) {
      updateItem.mutate(
        { id: editingItem.id, data: { question: itemQuestion, answer: itemAnswer, audience: itemAudience, video_url: itemVideoUrl || undefined } },
        {
          onSuccess: () => { toast({ title: "Item Updated" }); setShowAddItem(false); resetItemForm(); },
          onError: () => toast({ title: "Error", description: "Failed to update item", variant: "destructive" }),
        },
      );
    } else if (selectedCatId) {
      createItem.mutate(
        { question: itemQuestion, answer: itemAnswer, category_id: selectedCatId, audience: itemAudience, video_url: itemVideoUrl || undefined },
        {
          onSuccess: () => { toast({ title: "Item Created" }); setShowAddItem(false); resetItemForm(); },
          onError: () => toast({ title: "Error", description: "Failed to create item", variant: "destructive" }),
        },
      );
    }
  };

  const handleDeleteItem = (id: number) => {
    if (!window.confirm("Delete this FAQ item?")) return;
    deleteItem.mutate(id, {
      onSuccess: () => toast({ title: "Item Deleted" }),
      onError: () => toast({ title: "Error", description: "Failed to delete item", variant: "destructive" }),
    });
  };

  const openEditItem = (item: FaqItem) => {
    setEditingItem(item);
    setItemQuestion(item.question);
    setItemAnswer(item.answer);
    setItemAudience(item.audience);
    setItemVideoUrl(item.video_url ?? "");
    setShowAddItem(true);
  };

  if (lc) 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>;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">FAQ Manager</h1>
          <p className="text-muted-foreground">Manage FAQ categories and items.</p>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="space-y-3">
          <div className="flex items-center justify-between">
            <h3 className="text-sm font-medium text-muted-foreground">Categories</h3>
            <Dialog open={showAddCat} onOpenChange={setShowAddCat}>
              <DialogTrigger asChild>
                <Button variant="ghost" size="sm"><Plus className="h-4 w-4" /></Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader><DialogTitle>New Category</DialogTitle></DialogHeader>
                <div className="space-y-4 pt-4">
                  <div className="space-y-2">
                    <Label>Name</Label>
                    <Input placeholder="Category name" value={catName} onChange={e => setCatName(e.target.value)} />
                  </div>
                  <div className="space-y-2">
                    <Label>Audience</Label>
                    <Select value={catAudience} onValueChange={v => setCatAudience(v as FaqAudience)}>
                      <SelectTrigger><SelectValue /></SelectTrigger>
                      <SelectContent>
                        <SelectItem value="both">Both</SelectItem>
                        <SelectItem value="student">Student</SelectItem>
                        <SelectItem value="entity">Entity</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <Button className="w-full" onClick={handleCreateCategory} disabled={createCategory.isPending || !catName}>
                    {createCategory.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                    Create
                  </Button>
                </div>
              </DialogContent>
            </Dialog>
          </div>

          {categories.map(cat => (
            <div key={cat.id} className="group relative">
              <button
                onClick={() => setSelectedCatId(cat.id)}
                className={`w-full text-left p-3 rounded-lg border transition-colors ${selectedCatId === cat.id ? "bg-primary/10 border-primary" : "hover:bg-accent"}`}
              >
                <div className="flex items-center gap-2">
                  <FolderOpen className="h-4 w-4 shrink-0" />
                  <div className="min-w-0 flex-1">
                    <p className="text-sm font-medium truncate">{cat.name}</p>
                    <div className="flex items-center gap-2 text-xs text-muted-foreground">
                      <span>{cat.item_count} items</span>
                      <Badge variant="outline" className="text-xs">{cat.audience}</Badge>
                    </div>
                  </div>
                </div>
              </button>
              <div className="absolute top-2 right-2 hidden group-hover:flex gap-1">
                <Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => { setEditingCat(cat); setEditCatName(cat.name); }}>
                  <Pencil className="h-3 w-3" />
                </Button>
                <Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => handleDeleteCategory(cat.id)}>
                  <Trash2 className="h-3 w-3 text-destructive" />
                </Button>
              </div>
            </div>
          ))}
          {categories.length === 0 && <p className="text-sm text-muted-foreground px-1">No categories yet.</p>}
        </div>

        <div className="md:col-span-2">
          {!selectedCatId ? (
            <Card><CardContent className="py-12 text-center text-muted-foreground">Select a category to manage its FAQ items.</CardContent></Card>
          ) : li ? (
            <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>
          ) : (
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h3 className="font-medium">FAQ Items</h3>
                <Button size="sm" onClick={() => { resetItemForm(); setShowAddItem(true); }}>
                  <Plus className="mr-2 h-4 w-4" /> Add Item
                </Button>
              </div>
              {items
                .sort((a, b) => a.sequence - b.sequence)
                .map(item => (
                  <Card key={item.id}>
                    <CardContent className="py-4">
                      <div className="flex items-start gap-3">
                        <GripVertical className="h-5 w-5 text-muted-foreground mt-0.5 cursor-grab shrink-0" />
                        <div className="flex-1 min-w-0">
                          <p className="font-medium text-sm">{item.question}</p>
                          <p className="text-sm text-muted-foreground mt-1 line-clamp-2">{item.answer}</p>
                          <div className="flex items-center gap-2 mt-2">
                            <Badge variant="outline" className="text-xs">{item.audience}</Badge>
                            {item.video_url && <Badge variant="secondary" className="text-xs">Video</Badge>}
                          </div>
                        </div>
                        <div className="flex gap-1 shrink-0">
                          <Button variant="ghost" size="icon" onClick={() => openEditItem(item)}>
                            <Pencil className="h-4 w-4" />
                          </Button>
                          <Button variant="ghost" size="icon" onClick={() => handleDeleteItem(item.id)}>
                            <Trash2 className="h-4 w-4 text-destructive" />
                          </Button>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              {items.length === 0 && (
                <Card><CardContent className="py-8 text-center text-muted-foreground">No items in this category.</CardContent></Card>
              )}
            </div>
          )}
        </div>
      </div>

      <Dialog open={!!editingCat} onOpenChange={open => { if (!open) setEditingCat(null); }}>
        <DialogContent>
          <DialogHeader><DialogTitle>Edit Category</DialogTitle></DialogHeader>
          <div className="space-y-4 pt-4">
            <div className="space-y-2">
              <Label>Name</Label>
              <Input value={editCatName} onChange={e => setEditCatName(e.target.value)} />
            </div>
            <Button className="w-full" onClick={handleUpdateCategory} disabled={updateCategory.isPending || !editCatName}>
              {updateCategory.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Save
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      <Dialog open={showAddItem} onOpenChange={open => { setShowAddItem(open); if (!open) resetItemForm(); }}>
        <DialogContent>
          <DialogHeader><DialogTitle>{editingItem ? "Edit FAQ Item" : "New FAQ Item"}</DialogTitle></DialogHeader>
          <div className="space-y-4 pt-4">
            <div className="space-y-2">
              <Label>Question</Label>
              <Input placeholder="FAQ question" value={itemQuestion} onChange={e => setItemQuestion(e.target.value)} />
            </div>
            <div className="space-y-2">
              <Label>Answer (Markdown)</Label>
              <Textarea placeholder="Write the answer..." rows={4} value={itemAnswer} onChange={e => setItemAnswer(e.target.value)} />
            </div>
            <div className="space-y-2">
              <Label>Audience</Label>
              <Select value={itemAudience} onValueChange={v => setItemAudience(v as FaqAudience)}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="both">Both</SelectItem>
                  <SelectItem value="student">Student</SelectItem>
                  <SelectItem value="entity">Entity</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Video URL (optional)</Label>
              <Input placeholder="https://..." value={itemVideoUrl} onChange={e => setItemVideoUrl(e.target.value)} />
            </div>
            <Button className="w-full" onClick={handleSaveItem} disabled={(createItem.isPending || updateItem.isPending) || !itemQuestion || !itemAnswer}>
              {(createItem.isPending || updateItem.isPending) && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              {editingItem ? "Save Changes" : "Create Item"}
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
