import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Scale, Plus, Search, MoreHorizontal, Edit, Trash2 } 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, 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 { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import VotingAndComments from "@/components/shared/VotingAndComments";

const statusColors: Record<string, string> = { pending: "bg-amber-100 text-amber-700", accepted: "bg-emerald-100 text-emerald-700", rejected: "bg-red-100 text-red-700", expired: "bg-muted text-muted-foreground" };

export default function BidsQuotesPage({ boardAssociationIds, boardCanManage = false }: { boardAssociationIds?: string[]; boardCanManage?: boolean } = {}) {
  const { toast } = useToast();
  const [bids, setBids] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [selectedBid, setSelectedBid] = useState<any>(null);
  const [form, setForm] = useState({ vendor_name: "", amount: "", description: "", status: "pending", received_date: "", expiry_date: "" });

  const isBoardView = !!boardAssociationIds?.length;
  // Staff always manage; board members only when granted the upload permission.
  const canManage = !isBoardView || boardCanManage;
  const fetchData = async () => { setLoading(true); let query = supabase.from("bids_quotes").select("*, associations(name)").order("created_at", { ascending: false }); if (isBoardView) query = query.in("association_id", boardAssociationIds!); const { data } = await query; setBids(data || []); setLoading(false); };
  useEffect(() => { fetchData(); }, []);
  const openNew = () => { setEditing(null); setForm({ vendor_name: "", amount: "", description: "", status: "pending", received_date: "", expiry_date: "" }); setDialogOpen(true); };
  const openEdit = (b: any) => { setEditing(b); setForm({ vendor_name: b.vendor_name, amount: b.amount?.toString() || "", description: b.description || "", status: b.status, received_date: b.received_date || "", expiry_date: b.expiry_date || "" }); setDialogOpen(true); };
  const handleSave = async () => {
    const payload = { ...form, amount: parseFloat(form.amount) || 0, received_date: form.received_date || null, expiry_date: form.expiry_date || null };
    if (editing) { await supabase.from("bids_quotes").update(payload).eq("id", editing.id); toast({ title: "Updated" }); }
    else {
      let targetAssoc = boardAssociationIds?.[0];
      if (!targetAssoc) { const { data: a } = await supabase.from("associations").select("id").eq("status", "active").limit(1); targetAssoc = a?.[0]?.id; }
      if (!targetAssoc) return;
      const { error } = await supabase.from("bids_quotes").insert({ ...payload, association_id: targetAssoc });
      if (error) { toast({ variant: "destructive", title: "Error", description: error.message }); return; }
      toast({ title: "Bid created" });
    }
    setDialogOpen(false); fetchData();
  };
  const handleDelete = async (id: string) => { await supabase.from("bids_quotes").delete().eq("id", id); toast({ title: "Deleted" }); fetchData(); };
  const filtered = bids.filter((b) => b.vendor_name.toLowerCase().includes(search.toLowerCase()));

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div><h1 className="text-2xl font-bold text-foreground flex items-center gap-2"><Scale className="h-6 w-6 text-primary" /> Bids & Quotes</h1><p className="text-sm text-muted-foreground mt-1">Manage vendor bids and quotes.</p></div>
        {canManage && <div className="flex gap-2">
          <RecordImportButton
            title="Import Bids & Quotes"
            description="Upload a CSV or Excel file with bid/quote records."
            expectedColumns={[
              { key: "vendor_name", label: "Vendor Name", required: true },
              { key: "amount", label: "Amount", required: true },
              { key: "description", label: "Description" },
              { key: "status", label: "Status" },
              { key: "received_date", label: "Received Date" },
              { key: "expiry_date", label: "Expiry Date" },
            ]}
            onImport={async (rows) => {
              let targetAssoc = boardAssociationIds?.[0];
              if (!targetAssoc) { const { data: a } = await supabase.from("associations").select("id").eq("status", "active").limit(1); targetAssoc = a?.[0]?.id; }
              if (!targetAssoc) throw new Error("Create an association first");
              const payload = rows.map(r => ({
                vendor_name: r.vendor_name || "Unknown",
                amount: parseFloat(r.amount) || 0,
                description: r.description || null,
                status: r.status || "pending",
                received_date: r.received_date || null,
                expiry_date: r.expiry_date || null,
                association_id: targetAssoc,
              }));
              const { error } = await supabase.from("bids_quotes").insert(payload);
              if (error) throw error;
              toast({ title: `Imported ${rows.length} bids` });
              fetchData();
            }}
            templateFileName="bids_quotes_template.xlsx"
          />
          <Button className="gap-2" onClick={openNew}><Plus className="h-4 w-4" /> New Bid</Button>
        </div>}
      </div>
      <div className="relative max-w-md"><Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" /><Input placeholder="Search..." 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 bids found.</CardContent></Card> : (
        <Card><Table><TableHeader><TableRow><TableHead>Vendor</TableHead><TableHead>Amount</TableHead><TableHead>Status</TableHead><TableHead>Received</TableHead><TableHead>Expires</TableHead><TableHead className="w-12" /></TableRow></TableHeader><TableBody>
          {filtered.map((b) => (<TableRow key={b.id} className="cursor-pointer" onClick={() => setSelectedBid(b)}><TableCell className="font-medium">{b.vendor_name}</TableCell><TableCell>${Number(b.amount).toLocaleString()}</TableCell><TableCell><Badge className={statusColors[b.status] || "bg-muted text-muted-foreground"}>{b.status}</Badge></TableCell><TableCell>{b.received_date || "—"}</TableCell><TableCell>{b.expiry_date || "—"}</TableCell>{canManage && <TableCell>
            <DropdownMenu><DropdownMenuTrigger asChild><Button variant="ghost" size="icon" className="h-8 w-8" onClick={(e) => e.stopPropagation()}><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger><DropdownMenuContent align="end"><DropdownMenuItem onClick={(e) => { e.stopPropagation(); openEdit(b); }}><Edit className="h-4 w-4 mr-2" /> Edit</DropdownMenuItem><DropdownMenuItem className="text-destructive" onClick={(e) => { e.stopPropagation(); handleDelete(b.id); }}><Trash2 className="h-4 w-4 mr-2" /> Delete</DropdownMenuItem></DropdownMenuContent></DropdownMenu></TableCell>}</TableRow>))}</TableBody></Table></Card>
      )}

      {/* Create/Edit Dialog */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}><DialogContent><DialogHeader><DialogTitle>{editing ? "Edit" : "New"} Bid/Quote</DialogTitle></DialogHeader>
        <div className="space-y-4">
          <div><Label>Vendor</Label><Input value={form.vendor_name} onChange={(e) => setForm({ ...form, vendor_name: e.target.value })} /></div>
          <div className="grid grid-cols-2 gap-4"><div><Label>Amount</Label><Input type="number" value={form.amount} onChange={(e) => setForm({ ...form, amount: e.target.value })} /></div>
            <div><Label>Status</Label><Select value={form.status} onValueChange={(v) => setForm({ ...form, status: v })}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent><SelectItem value="pending">Pending</SelectItem><SelectItem value="accepted">Accepted</SelectItem><SelectItem value="rejected">Rejected</SelectItem><SelectItem value="expired">Expired</SelectItem></SelectContent></Select></div></div>
          <div className="grid grid-cols-2 gap-4"><div><Label>Received</Label><Input type="date" value={form.received_date} onChange={(e) => setForm({ ...form, received_date: e.target.value })} /></div><div><Label>Expires</Label><Input type="date" value={form.expiry_date} onChange={(e) => setForm({ ...form, expiry_date: e.target.value })} /></div></div>
          <div><Label>Description</Label><Textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} /></div>
        </div><DialogFooter><Button onClick={handleSave}>{editing ? "Update" : "Create"}</Button></DialogFooter></DialogContent></Dialog>

      {/* Detail/Vote Dialog */}
      <Dialog open={!!selectedBid} onOpenChange={(open) => !open && setSelectedBid(null)}>
        <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
          <DialogHeader><DialogTitle className="flex items-center gap-2"><Scale className="w-5 h-5" /> Bid/Quote Review</DialogTitle></DialogHeader>
          {selectedBid && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div><p className="text-sm text-muted-foreground">Vendor</p><p className="font-medium">{selectedBid.vendor_name}</p></div>
                <div><p className="text-sm text-muted-foreground">Amount</p><p className="font-medium">${Number(selectedBid.amount).toLocaleString()}</p></div>
                <div><p className="text-sm text-muted-foreground">Status</p><Badge className={statusColors[selectedBid.status] || ""}>{selectedBid.status}</Badge></div>
                <div><p className="text-sm text-muted-foreground">Association</p><p className="font-medium">{selectedBid.associations?.name || "—"}</p></div>
              </div>
              {selectedBid.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">{selectedBid.description}</p></div>
              )}
              <VotingAndComments entityType="bid_quote" entityId={selectedBid.id} />
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
