import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { CalendarOff, Plus, 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 { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";

export default function BlockedDatesPage() {
  const { toast } = useToast();
  const [dates, setDates] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [form, setForm] = useState({ title: "", start_date: "", end_date: "", reason: "" });

  const fetchData = async () => { setLoading(true); const { data } = await supabase.from("blocked_dates").select("*").order("start_date", { ascending: false }); setDates(data || []); setLoading(false); };
  useEffect(() => { fetchData(); }, []);

  const handleCreate = async () => {
    const { data: a } = await supabase.from("associations").select("id").eq("status", "active").limit(1);
    if (!a?.length) return;
    await supabase.from("blocked_dates").insert({ ...form, association_id: a[0].id });
    toast({ title: "Blocked date added" }); setDialogOpen(false); fetchData();
  };
  const handleDelete = async (id: string) => { await supabase.from("blocked_dates").delete().eq("id", id); toast({ title: "Deleted" }); fetchData(); };

  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"><CalendarOff className="h-6 w-6 text-primary" /> Blocked Dates</h1><p className="text-sm text-muted-foreground mt-1">Manage unavailable dates and blackout periods.</p></div>
        <div className="flex gap-2">
          <RecordImportButton
            title="Import Blocked Dates"
            description="Upload a CSV or Excel file with blocked date records."
            expectedColumns={[
              { key: "title", label: "Title", required: true },
              { key: "start_date", label: "Start Date", required: true },
              { key: "end_date", label: "End Date", required: true },
              { key: "reason", label: "Reason" },
            ]}
            onImport={async (rows) => {
              const { data: a } = await supabase.from("associations").select("id").eq("status", "active").limit(1);
              if (!a?.length) throw new Error("Create an association first");
              const payload = rows.map(r => ({
                title: r.title || "Blocked",
                start_date: r.start_date,
                end_date: r.end_date,
                reason: r.reason || null,
                association_id: a[0].id,
              }));
              const { error } = await supabase.from("blocked_dates").insert(payload);
              if (error) throw error;
              toast({ title: `Imported ${rows.length} blocked dates` });
              fetchData();
            }}
            templateFileName="blocked_dates_template.xlsx"
          />
          <Button className="gap-2" onClick={() => { setForm({ title: "", start_date: "", end_date: "", reason: "" }); setDialogOpen(true); }}><Plus className="h-4 w-4" /> Add Blocked Date</Button>
        </div>
      </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> : dates.length === 0 ? <Card><CardContent className="py-12 text-center text-muted-foreground">No blocked dates found.</CardContent></Card> : (
        <Card><Table><TableHeader><TableRow><TableHead>Title</TableHead><TableHead>Start</TableHead><TableHead>End</TableHead><TableHead>Reason</TableHead><TableHead className="w-12" /></TableRow></TableHeader><TableBody>
          {dates.map((d) => (<TableRow key={d.id}><TableCell className="font-medium">{d.title}</TableCell><TableCell>{d.start_date}</TableCell><TableCell>{d.end_date}</TableCell><TableCell>{d.reason || "—"}</TableCell><TableCell><Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={() => handleDelete(d.id)}><Trash2 className="h-4 w-4" /></Button></TableCell></TableRow>))}</TableBody></Table></Card>
      )}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}><DialogContent><DialogHeader><DialogTitle>Add Blocked Date</DialogTitle></DialogHeader>
        <div className="space-y-4">
          <div><Label>Title</Label><Input value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} /></div>
          <div className="grid grid-cols-2 gap-4"><div><Label>Start Date</Label><Input type="date" value={form.start_date} onChange={(e) => setForm({ ...form, start_date: e.target.value })} /></div><div><Label>End Date</Label><Input type="date" value={form.end_date} onChange={(e) => setForm({ ...form, end_date: e.target.value })} /></div></div>
          <div><Label>Reason</Label><Textarea value={form.reason} onChange={(e) => setForm({ ...form, reason: e.target.value })} /></div>
        </div><DialogFooter><Button onClick={handleCreate}>Add</Button></DialogFooter></DialogContent></Dialog>
    </div>
  );
}
