import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";
import { useToast } from "@/hooks/use-toast";
import { Users, Plus, Search } from "lucide-react";
import RecordImportButton from "@/components/RecordImportButton";
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, DialogTrigger, DialogFooter } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { format } from "date-fns";
import VotingAndComments from "@/components/shared/VotingAndComments";
import BoardVotePdfExport from "@/components/BoardVotePdfExport";
import { FileUploadDropzone } from "@/components/FileUploadDropzone";
import { FileText, Download, Trash2, Mail } from "lucide-react";
import BoardVoteOptionsEditor from "@/components/BoardVoteOptionsEditor";
import BoardVoteOptionsVoting from "@/components/BoardVoteOptionsVoting";

export default function BoardVotesPage({ boardAssociationIds }: { boardAssociationIds?: string[] } = {}) {
  const { user } = useAuth();
  const { toast } = useToast();
  const [items, setItems] = useState<any[]>([]);
  const [associations, setAssociations] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [dialogOpen, setDialogOpen] = useState(false);
  const [selectedItem, setSelectedItem] = useState<any>(null);
  const [createAttachments, setCreateAttachments] = useState<any[]>([]);
  const [editAttachments, setEditAttachments] = useState<any[]>([]);
  const [savingAttachments, setSavingAttachments] = useState(false);
  const [createVoteOptions, setCreateVoteOptions] = useState<string[]>(["Yes", "No"]);

  const isBoardView = !!boardAssociationIds?.length;

  const fetchData = async () => {
    setLoading(true);
    let itemsQuery = supabase.from("board_votes").select("*, associations(name)").order("created_at", { ascending: false });
    let assocQuery = supabase.from("associations").select("id, name").eq("status", "active").order("name");
    if (isBoardView) {
      itemsQuery = itemsQuery.in("association_id", boardAssociationIds!);
      assocQuery = assocQuery.in("id", boardAssociationIds!);
    }
    const [itemsRes, assocRes] = await Promise.all([itemsQuery, assocQuery]);
    if (itemsRes.data) setItems(itemsRes.data);
    if (assocRes.data) setAssociations(assocRes.data);
    setLoading(false);
  };

  useEffect(() => { fetchData(); }, []);

  const handleCreate = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    const filteredOptions = createVoteOptions.filter(o => o.trim());
    if (filteredOptions.length < 2) {
      toast({ title: "Error", description: "At least 2 vote options are required.", variant: "destructive" });
      return;
    }
    const { error } = await supabase.from("board_votes").insert({
      association_id: fd.get("association_id") as string,
      title: fd.get("title") as string,
      description: (fd.get("description") as string) || null,
      created_by: user?.id,
      attachments: createAttachments,
      vote_options: filteredOptions,
    });
    if (error) {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    } else {
      toast({ title: "Vote item created" });
      setDialogOpen(false);
      setCreateAttachments([]);
      setCreateVoteOptions(["Yes", "No"]);
      fetchData();
    }
  };

  const handleSaveAttachments = async () => {
    if (!selectedItem) return;
    setSavingAttachments(true);
    const { error } = await supabase.from("board_votes").update({ attachments: editAttachments }).eq("id", selectedItem.id);
    setSavingAttachments(false);
    if (error) {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    } else {
      toast({ title: "Attachments updated" });
      setSelectedItem({ ...selectedItem, attachments: editAttachments });
      fetchData();
    }
  };

  const removeEditAttachment = (index: number) => {
    setEditAttachments(prev => prev.filter((_, i) => i !== index));
  };

  const handleClose = async (id: string) => {
    await supabase.from("board_votes").update({ status: "closed" }).eq("id", id);
    toast({ title: "Vote closed" });
    fetchData();
    if (selectedItem?.id === id) setSelectedItem({ ...selectedItem, status: "closed" });
  };

  const handleDelete = async (id: string) => {
    if (!confirm("Are you sure you want to delete this board vote? This cannot be undone.")) return;
    const { error } = await supabase.from("board_votes").delete().eq("id", id);
    if (error) {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    } else {
      toast({ title: "Vote deleted" });
      setSelectedItem(null);
      fetchData();
    }
  };

  const [sendingInvites, setSendingInvites] = useState(false);
  const handleEmailBoard = async (id: string) => {
    if (!confirm("Email all board members with a secure voting link for this item?")) return;
    setSendingInvites(true);
    const { data, error } = await supabase.functions.invoke("send-board-vote-invites", {
      body: { board_vote_id: id, base_url: window.location.origin },
    });
    setSendingInvites(false);
    if (error || data?.error) {
      toast({ title: "Error", description: data?.error || error?.message || "Failed to send", variant: "destructive" });
    } else {
      toast({ title: "Invitations sent", description: `Sent ${data?.sent ?? 0}, failed ${data?.failed ?? 0}` });
    }
  };

  const filtered = items.filter((i) => i.title.toLowerCase().includes(search.toLowerCase()));

  const statusVariant = (s: string) => s === "open" ? "default" as const : "secondary" as const;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold flex items-center gap-2"><Users className="h-6 w-6 text-primary" /> Board Votes</h1>
          <p className="text-sm text-muted-foreground">Create and manage board voting items and track results.</p>
        </div>
        {!isBoardView && (
          <div className="flex gap-2">
            <RecordImportButton
              title="Import Board Votes"
              description="Upload a CSV or Excel file with board vote items."
              expectedColumns={[
                { key: "title", label: "Title", required: true },
                { key: "description", label: "Description" },
              ]}
              onImport={async (rows) => {
                const assocId = associations[0]?.id;
                if (!assocId) throw new Error("Create an association first");
                const payload = rows.map(r => ({
                  title: r.title || "Untitled",
                  description: r.description || null,
                  association_id: assocId,
                  created_by: user?.id,
                }));
                const { error } = await supabase.from("board_votes").insert(payload);
                if (error) throw error;
                toast({ title: `Imported ${rows.length} vote items` });
                fetchData();
              }}
              templateFileName="board_votes_template.xlsx"
            />
            <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
              <DialogTrigger asChild><Button className="gap-2"><Plus className="h-4 w-4" /> New Vote</Button></DialogTrigger>
            <DialogContent>
              <DialogHeader><DialogTitle>Create Board Vote</DialogTitle></DialogHeader>
              <form onSubmit={handleCreate} className="space-y-4">
                <div className="space-y-2">
                  <Label>Association *</Label>
                  <Select name="association_id" required>
                    <SelectTrigger><SelectValue placeholder="Select association" /></SelectTrigger>
                    <SelectContent>{associations.map((a) => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}</SelectContent>
                  </Select>
                </div>
                <div className="space-y-2"><Label>Title *</Label><Input name="title" required /></div>
                <div className="space-y-2"><Label>Description</Label><Textarea name="description" /></div>
                <BoardVoteOptionsEditor options={createVoteOptions} onChange={setCreateVoteOptions} />
                <div className="space-y-2">
                  <Label>Attachments</Label>
                  <FileUploadDropzone
                    bucketName="files"
                    onFilesUploaded={(files) => setCreateAttachments(files.map(f => ({ file_name: f.file_name, file_url: f.file_url, file_size: f.file_size })))}
                    maxFiles={10}
                  />
                </div>
                <DialogFooter><Button type="submit">Create</Button></DialogFooter>
              </form>
            </DialogContent>
          </Dialog>
          </div>
        )}
      </div>

      <div className="relative max-w-sm">
        <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
        <Input placeholder="Search votes..." value={search} onChange={(e) => setSearch(e.target.value)} className="pl-10" />
      </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">
          <Users className="mx-auto h-12 w-12 mb-4 opacity-50" />
          <p>{search ? "No votes match your search." : "No board votes yet."}</p>
        </CardContent></Card>
      ) : (
        <div className="rounded-lg border bg-card">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Title</TableHead>
                <TableHead>Association</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Created</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filtered.map((item) => (
                <TableRow key={item.id} className="cursor-pointer hover:bg-muted/50" onClick={() => { setSelectedItem(item); setEditAttachments(item.attachments || []); }}>
                  <TableCell className="font-medium">{item.title}</TableCell>
                  <TableCell>{item.associations?.name || "—"}</TableCell>
                  <TableCell><Badge variant={statusVariant(item.status)}>{item.status}</Badge></TableCell>
                  <TableCell className="text-muted-foreground">{format(new Date(item.created_at), "MMM d, yyyy")}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}

      <Dialog open={!!selectedItem} onOpenChange={(open) => { if (!open) setSelectedItem(null); else if (selectedItem) setEditAttachments(selectedItem.attachments || []); }}>
        <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
          <DialogHeader><DialogTitle className="flex items-center gap-2"><Users className="w-5 h-5" /> Board Vote</DialogTitle></DialogHeader>
          {selectedItem && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div><p className="text-sm text-muted-foreground">Title</p><p className="font-medium">{selectedItem.title}</p></div>
                <div><p className="text-sm text-muted-foreground">Status</p><Badge variant={statusVariant(selectedItem.status)}>{selectedItem.status}</Badge></div>
                <div><p className="text-sm text-muted-foreground">Association</p><p className="font-medium">{selectedItem.associations?.name || "—"}</p></div>
                <div><p className="text-sm text-muted-foreground">Created</p><p className="font-medium">{format(new Date(selectedItem.created_at), "MMMM d, yyyy")}</p></div>
              </div>
              {selectedItem.description && (
                <div><p className="text-sm text-muted-foreground">Description</p><p className="bg-muted p-3 rounded-md mt-1 border whitespace-pre-wrap">{selectedItem.description}</p></div>
              )}

              {/* Attachments section */}
              <div className="space-y-2">
                <p className="text-sm font-medium text-muted-foreground">Attachments</p>
                {editAttachments.length > 0 && (
                  <div className="space-y-2">
                    {editAttachments.map((file: any, idx: number) => (
                      <div key={idx} className="flex items-center gap-2 p-2 rounded-md border bg-muted/30">
                        <FileText className="h-4 w-4 text-primary shrink-0" />
                        <a href={file.file_url} target="_blank" rel="noopener noreferrer" className="text-sm truncate flex-1 text-primary hover:underline">{file.file_name}</a>
                        <a href={file.file_url} target="_blank" rel="noopener noreferrer"><Download className="h-4 w-4 text-muted-foreground hover:text-foreground" /></a>
                        {!isBoardView && (
                          <Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => removeEditAttachment(idx)}>
                            <Trash2 className="h-3 w-3 text-destructive" />
                          </Button>
                        )}
                      </div>
                    ))}
                  </div>
                )}
                {!isBoardView && (
                  <>
                    <FileUploadDropzone
                      bucketName="files"
                      onFilesUploaded={(files) => {
                        const newFiles = files.map(f => ({ file_name: f.file_name, file_url: f.file_url, file_size: f.file_size }));
                        setEditAttachments(prev => [...prev, ...newFiles]);
                      }}
                      maxFiles={10}
                    />
                    <Button size="sm" onClick={handleSaveAttachments} disabled={savingAttachments}>
                      {savingAttachments ? "Saving..." : "Save Attachments"}
                    </Button>
                  </>
                )}
                {editAttachments.length === 0 && isBoardView && (
                  <p className="text-sm text-muted-foreground italic">No attachments</p>
                )}
              </div>

              <div className="flex justify-end gap-2 flex-wrap">
                <BoardVotePdfExport vote={selectedItem} />
                {selectedItem.status === "open" && !isBoardView && (
                  <Button variant="default" size="sm" onClick={() => handleEmailBoard(selectedItem.id)} disabled={sendingInvites}>
                    <Mail className="h-4 w-4 mr-1" /> {sendingInvites ? "Sending…" : "Email Board to Vote"}
                  </Button>
                )}
                {!isBoardView && (
                  <Button variant="destructive" size="sm" onClick={() => handleDelete(selectedItem.id)}>
                    <Trash2 className="h-4 w-4 mr-1" /> Delete
                  </Button>
                )}
                {selectedItem.status === "open" && !isBoardView && (
                  <Button variant="outline" size="sm" onClick={() => handleClose(selectedItem.id)}>Close Voting</Button>
                )}
              </div>
              {selectedItem.vote_options?.length > 0 && (
                <BoardVoteOptionsVoting
                  voteId={selectedItem.id}
                  voteOptions={selectedItem.vote_options}
                  status={selectedItem.status}
                />
              )}
              <VotingAndComments entityType="board_vote" entityId={selectedItem.id} />
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
