import { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/hooks/use-toast";
import { Trash2, Plus, Loader2 } from "lucide-react";

interface Props {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  amenity: { id: string; name: string; association_id: string } | null;
}

export default function ManageAmenityBookingsDialog({ open, onOpenChange, amenity }: Props) {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [bookings, setBookings] = useState<any[]>([]);
  const [newDate, setNewDate] = useState("");
  const [newLabel, setNewLabel] = useState("");
  const [saving, setSaving] = useState(false);

  const load = async () => {
    if (!amenity) return;
    setLoading(true);
    const { data } = await (supabase as any)
      .from("amenity_bookings")
      .select("id, booking_date, start_time, end_time, status, title, guest_name")
      .eq("amenity_id", amenity.id)
      .gte("booking_date", new Date(Date.now() - 30 * 86400000).toISOString().slice(0, 10))
      .order("booking_date", { ascending: true });
    setBookings(data || []);
    setLoading(false);
  };

  useEffect(() => {
    if (open && amenity) load();
  }, [open, amenity?.id]);

  const addBlock = async () => {
    if (!amenity || !newDate) return;
    setSaving(true);
    const { error } = await (supabase as any).from("amenity_bookings").insert({
      amenity_id: amenity.id,
      association_id: amenity.association_id,
      booking_date: newDate,
      booking_type: "block",
      title: newLabel || "Booked",
      guest_name: newLabel || "Manually Blocked",
      guest_email: "blocked@internal",
      status: "blocked",
    });
    setSaving(false);
    if (error) {
      toast({ variant: "destructive", title: "Error", description: error.message });
    } else {
      setNewDate("");
      setNewLabel("");
      load();
    }
  };

  const remove = async (id: string) => {
    const { error } = await (supabase as any).from("amenity_bookings").delete().eq("id", id);
    if (error) {
      toast({ variant: "destructive", title: "Error", description: error.message });
    } else {
      setBookings((prev) => prev.filter((b) => b.id !== id));
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[560px] max-h-[85vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Manage Bookings — {amenity?.name}</DialogTitle>
          <DialogDescription>
            Add manual booked dates that will display as unavailable on the public calendar.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div className="rounded-md border p-3 space-y-3 bg-muted/30">
            <p className="text-sm font-medium">Add booked date</p>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label className="text-xs">Date</Label>
                <Input type="date" value={newDate} onChange={(e) => setNewDate(e.target.value)} />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs">Label (optional)</Label>
                <Input value={newLabel} onChange={(e) => setNewLabel(e.target.value)} placeholder="e.g. Private event" />
              </div>
            </div>
            <Button size="sm" onClick={addBlock} disabled={!newDate || saving} className="gap-1.5">
              {saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Plus className="h-3.5 w-3.5" />}
              Add Booked Date
            </Button>
          </div>

          <div>
            <p className="text-sm font-medium mb-2">Upcoming bookings</p>
            {loading ? (
              <div className="flex justify-center py-6"><Loader2 className="h-5 w-5 animate-spin text-muted-foreground" /></div>
            ) : bookings.length === 0 ? (
              <p className="text-sm text-muted-foreground py-4 text-center">No bookings yet.</p>
            ) : (
              <div className="space-y-2">
                {bookings.map((b) => (
                  <div key={b.id} className="flex items-center justify-between rounded-md border bg-card px-3 py-2">
                    <div className="min-w-0">
                      <p className="text-sm font-medium">{b.booking_date}</p>
                      <p className="text-xs text-muted-foreground truncate">
                        {b.title || b.guest_name || "—"}
                      </p>
                    </div>
                    <div className="flex items-center gap-2">
                      <Badge variant={b.status === "confirmed" || b.status === "blocked" ? "default" : "secondary"} className="text-[10px] capitalize">
                        {(b.status || "").replace(/_/g, " ")}
                      </Badge>
                      <Button variant="ghost" size="icon" className="h-7 w-7 text-destructive" onClick={() => remove(b.id)}>
                        <Trash2 className="h-3.5 w-3.5" />
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>Close</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
