import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";
import { useToast } from "@/hooks/use-toast";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Plus, FileEdit, Lock, Search, Trash2 } from "lucide-react";
import { format } from "date-fns";
import CollaborativeDocumentEditor from "./CollaborativeDocumentEditor";

interface Props {
  boardAssociationIds?: string[];
}

export default function CollaborativeDocumentsPage({ boardAssociationIds }: Props) {
  const { user } = useAuth();
  const { toast } = useToast();
  const [documents, setDocuments] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [showCreate, setShowCreate] = useState(false);
  const [newTitle, setNewTitle] = useState("");
  const [newAssocId, setNewAssocId] = useState("");
  const [associations, setAssociations] = useState<any[]>([]);
  const [selectedDoc, setSelectedDoc] = useState<any>(null);

  useEffect(() => {
    fetchDocuments();
    fetchAssociations();
  }, [user]);

  const fetchAssociations = async () => {
    let query = supabase.from("associations").select("id, name").order("name");
    if (boardAssociationIds?.length) {
      query = query.in("id", boardAssociationIds);
    }
    const { data } = await query;
    setAssociations(data || []);
  };

  const fetchDocuments = async () => {
    setLoading(true);
    let query = supabase
      .from("collaborative_documents")
      .select("*")
      .order("updated_at", { ascending: false });
    if (boardAssociationIds?.length) {
      query = query.in("association_id", boardAssociationIds);
    }
    const { data, error } = await query;
    if (error) toast({ title: "Error", description: error.message, variant: "destructive" });
    else setDocuments(data || []);
    setLoading(false);
  };

  const handleCreate = async () => {
    if (!newTitle.trim() || !newAssocId) return;
    const { error } = await supabase.from("collaborative_documents").insert({
      title: newTitle.trim(),
      association_id: newAssocId,
      created_by: user?.id,
    });
    if (error) {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    } else {
      toast({ title: "Document created" });
      setShowCreate(false);
      setNewTitle("");
      setNewAssocId("");
      fetchDocuments();
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm("Delete this document and all its history?")) return;
    const { error } = await supabase.from("collaborative_documents").delete().eq("id", id);
    if (error) toast({ title: "Error", description: error.message, variant: "destructive" });
    else fetchDocuments();
  };

  const filtered = documents.filter(
    (d) => !search || d.title?.toLowerCase().includes(search.toLowerCase())
  );

  if (selectedDoc) {
    return (
      <CollaborativeDocumentEditor
        document={selectedDoc}
        onBack={() => { setSelectedDoc(null); fetchDocuments(); }}
        associations={associations}
      />
    );
  }

  const getAssocName = (id: string) => associations.find((a) => a.id === id)?.name || "—";

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <FileEdit className="h-6 w-6 text-primary" /> Collaborative Documents
          </h1>
          <p className="text-muted-foreground mt-1">Create and edit documents together with board members.</p>
        </div>
        <Button onClick={() => setShowCreate(true)} className="gap-2">
          <Plus className="h-4 w-4" /> New Document
        </Button>
      </div>

      <div className="relative w-full 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 documents..." className="pl-10" value={search} onChange={(e) => setSearch(e.target.value)} />
      </div>

      {loading ? (
        <div className="flex justify-center py-12"><div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" /></div>
      ) : filtered.length === 0 ? (
        <Card><CardContent className="py-12 text-center text-muted-foreground">No collaborative documents yet.</CardContent></Card>
      ) : (
        <div className="grid gap-3">
          {filtered.map((doc) => (
            <Card key={doc.id} className="hover:bg-muted/30 transition-colors cursor-pointer" onClick={() => setSelectedDoc(doc)}>
              <CardContent className="flex items-center justify-between p-4">
                <div className="flex items-center gap-3 min-w-0">
                  <FileEdit className="h-5 w-5 text-primary shrink-0" />
                  <div className="min-w-0">
                    <p className="font-medium truncate">{doc.title}</p>
                    <p className="text-xs text-muted-foreground">{getAssocName(doc.association_id)} · Updated {format(new Date(doc.updated_at), "MMM d, yyyy h:mm a")}</p>
                  </div>
                </div>
                <div className="flex items-center gap-2 shrink-0">
                  {doc.locked_by && (
                    <Badge variant="secondary" className="gap-1 text-xs">
                      <Lock className="h-3 w-3" /> Editing
                    </Badge>
                  )}
                  <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={(e) => { e.stopPropagation(); handleDelete(doc.id); }}>
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      <Dialog open={showCreate} onOpenChange={setShowCreate}>
        <DialogContent>
          <DialogHeader><DialogTitle>New Collaborative Document</DialogTitle></DialogHeader>
          <div className="space-y-4">
            <div>
              <label className="text-sm font-medium">Title</label>
              <Input value={newTitle} onChange={(e) => setNewTitle(e.target.value)} placeholder="Document title" />
            </div>
            <div>
              <label className="text-sm font-medium">Association</label>
              <Select value={newAssocId} onValueChange={setNewAssocId}>
                <SelectTrigger><SelectValue placeholder="Select association" /></SelectTrigger>
                <SelectContent>
                  {associations.map((a) => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowCreate(false)}>Cancel</Button>
            <Button onClick={handleCreate} disabled={!newTitle.trim() || !newAssocId}>Create</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
