import { useEffect, useMemo, useState } from "react";
import { format, isSameDay, startOfMonth, endOfMonth, startOfWeek, endOfWeek, eachDayOfInterval, parseISO } from "date-fns";
import { CalendarDays, Lock, Send, CalendarIcon } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";
import { useHomeowner } from "@/contexts/HomeownerContext";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Calendar } from "@/components/ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { cn } from "@/lib/utils";

type CalendarMode = "rentals" | "meetings";

export default function HomeownerAmenityCalendarPage() {
  const { user, isAssociationManagement } = useAuth();
  const { association, currentOwner, loading: contextLoading } = useHomeowner();
  const [mode, setMode] = useState<CalendarMode>(isAssociationManagement ? "meetings" : "rentals");
  const [bookings, setBookings] = useState<any[]>([]);
  const [meetingAmenities, setMeetingAmenities] = useState<any[]>([]);
  const [rentalAmenities, setRentalAmenities] = useState<any[]>([]);
  const [meetingForm, setMeetingForm] = useState({ guest_name: "", booking_date: "", start_time: "", notes: "" });
  const [meetingDates, setMeetingDates] = useState<Date[]>([]);
  const [submittingMeeting, setSubmittingMeeting] = useState(false);
  const [loading, setLoading] = useState(true);
  const currentMonth = new Date();

  useEffect(() => {
    if (!association?.id) return;
    setLoading(true);
    Promise.all([
    (supabase as any)
      .from("amenity_bookings")
      .select("*, amenities(name)")
      .eq("association_id", association.id)
      .in("booking_type", ["rental", "meeting"])
      .order("booking_date"),
    (supabase as any)
      .from("amenities")
      .select("id, name")
      .eq("association_id", association.id)
      .eq("amenity_type", "meeting_calendar")
      .eq("is_active", true)
      .eq("show_on_homeowner_portal", true)
      .order("name"),
    (supabase as any)
      .from("amenities")
      .select("id, name")
      .eq("association_id", association.id)
      .eq("amenity_type", "rental_calendar")
      .eq("is_active", true)
      .eq("show_on_homeowner_portal", true)
      .order("name"),
    ]).then(([bookingRes, meetingAmenityRes, rentalAmenityRes]: any[]) => {
      setBookings(bookingRes.data || []);
      setMeetingAmenities(meetingAmenityRes.data || []);
      setRentalAmenities(rentalAmenityRes.data || []);
      setLoading(false);
    });
  }, [association?.id]);

  const submitMeetingRequest = async (event: React.FormEvent) => {
    event.preventDefault();
    const amenityId = meetingAmenities[0]?.id;
    if (!association?.id || !amenityId || !meetingForm.guest_name) return;

    const dates = isAssociationManagement
      ? meetingDates.map((d) => format(d, "yyyy-MM-dd"))
      : meetingForm.booking_date
        ? [meetingForm.booking_date]
        : [];
    if (dates.length === 0) return;

    setSubmittingMeeting(true);
    const rows = dates.map((booking_date) => ({
      association_id: association.id,
      amenity_id: amenityId,
      booking_type: "meeting",
      title: "Meeting Request",
      guest_name: meetingForm.guest_name,
      guest_email: user?.email || (currentOwner as any)?.email || null,
      booking_date,
      start_time: meetingForm.start_time || null,
      notes: meetingForm.notes || null,
      status: "pending_approval",
    }));
    const { error } = await (supabase as any).from("amenity_bookings").insert(rows);
    setSubmittingMeeting(false);
    if (!error) {
      setMeetingForm({ guest_name: "", booking_date: "", start_time: "", notes: "" });
      setMeetingDates([]);
    }
  };

  const ownerEmails = useMemo(() => new Set([user?.email, (currentOwner as any)?.email].filter(Boolean).map((email) => String(email).toLowerCase())), [user?.email, currentOwner]);
  const calendarDays = useMemo(() => eachDayOfInterval({ start: startOfWeek(startOfMonth(currentMonth)), end: endOfWeek(endOfMonth(currentMonth)) }), [currentMonth]);
  const visibleAmenityIds = new Set((mode === "meetings" ? meetingAmenities : rentalAmenities).map((amenity) => amenity.id));
  const filtered = bookings.filter((booking) => booking.booking_type === (mode === "meetings" ? "meeting" : "rental") && visibleAmenityIds.has(booking.amenity_id));
  const bookingsForDay = (day: Date) => filtered.filter((booking) => booking.booking_date && isSameDay(parseISO(`${booking.booking_date}T12:00:00`), day));
  const isOwnMeeting = (booking: any) => mode === "meetings" && booking.guest_email && ownerEmails.has(String(booking.guest_email).toLowerCase());

  if (contextLoading || loading) {
    return <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>;
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground">Amenity Calendar</h1>
          <p className="text-muted-foreground mt-1">{mode === "rentals" ? "Rental availability for your association." : "Your meetings are shown with details; other meetings are blocked."}</p>
        </div>
        <Select value={mode} onValueChange={(value) => setMode(value as CalendarMode)}>
          <SelectTrigger className="w-[190px]"><SelectValue /></SelectTrigger>
          <SelectContent>
            {!isAssociationManagement && <SelectItem value="rentals">Rental Calendar</SelectItem>}
            <SelectItem value="meetings">Meeting Calendar</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-base"><CalendarDays className="h-4 w-4" /> {format(currentMonth, "MMMM yyyy")}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-7 rounded-md border overflow-hidden">
            {["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].map((day) => <div key={day} className="bg-muted/50 p-2 text-center text-xs font-semibold text-muted-foreground border-b">{day}</div>)}
            {calendarDays.map((day) => {
              const dayBookings = bookingsForDay(day);
              return (
                <div key={day.toISOString()} className="min-h-[96px] border-r border-b p-2 space-y-1">
                  <div className="text-sm font-medium text-foreground">{format(day, "d")}</div>
                  {dayBookings.map((booking) => {
                    const showDetails = isOwnMeeting(booking);
                    return (
                      <div key={booking.id} className="rounded bg-muted px-2 py-1 text-xs text-muted-foreground">
                        {showDetails ? <span className="font-medium text-foreground">{booking.title || booking.guest_name || "Meeting"}</span> : <span className="inline-flex items-center gap-1"><Lock className="h-3 w-3" /> Blocked</span>}
                        {showDetails && booking.start_time && <div>{booking.start_time.slice(0, 5)}{booking.end_time ? ` – ${booking.end_time.slice(0, 5)}` : ""}</div>}
                      </div>
                    );
                  })}
                </div>
              );
            })}
          </div>
          <div className="mt-4 flex items-center gap-2 text-sm text-muted-foreground"><Badge variant="secondary">Blocked</Badge> Dates with reserved amenity time are unavailable.</div>
        </CardContent>
      </Card>
      {mode === "meetings" && meetingAmenities.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-base"><Send className="h-4 w-4" /> Request Meeting Time</CardTitle>
          </CardHeader>
          <CardContent>
            <form onSubmit={submitMeetingRequest} className="grid gap-4 md:grid-cols-3">
              <div className="space-y-1.5"><Label>Name</Label><Input value={meetingForm.guest_name} onChange={(e) => setMeetingForm({ ...meetingForm, guest_name: e.target.value })} required /></div>
              {isAssociationManagement ? (
                <div className="space-y-1.5">
                  <Label>Dates Requested</Label>
                  <Popover>
                    <PopoverTrigger asChild>
                      <Button
                        type="button"
                        variant="outline"
                        className={cn("w-full justify-start text-left font-normal", meetingDates.length === 0 && "text-muted-foreground")}
                      >
                        <CalendarIcon className="mr-2 h-4 w-4" />
                        {meetingDates.length === 0
                          ? "Select one or more dates"
                          : meetingDates.length === 1
                            ? format(meetingDates[0], "PPP")
                            : `${meetingDates.length} dates selected`}
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-auto p-0" align="start">
                      <Calendar
                        mode="multiple"
                        selected={meetingDates}
                        onSelect={(dates) => setMeetingDates(dates || [])}
                        initialFocus
                        className={cn("p-3 pointer-events-auto")}
                      />
                    </PopoverContent>
                  </Popover>
                  {meetingDates.length > 1 && (
                    <p className="text-xs text-muted-foreground">{meetingDates.map((d) => format(d, "MMM d")).join(", ")}</p>
                  )}
                </div>
              ) : (
                <div className="space-y-1.5"><Label>Date Requested</Label><Input type="date" value={meetingForm.booking_date} onChange={(e) => setMeetingForm({ ...meetingForm, booking_date: e.target.value })} required /></div>
              )}
              <div className="space-y-1.5"><Label>Time Requested</Label><Input type="time" value={meetingForm.start_time} onChange={(e) => setMeetingForm({ ...meetingForm, start_time: e.target.value })} /></div>
              <div className="space-y-1.5 md:col-span-3"><Label>Additional Information</Label><Textarea value={meetingForm.notes} onChange={(e) => setMeetingForm({ ...meetingForm, notes: e.target.value })} rows={3} /></div>
              <div className="md:col-span-3"><Button type="submit" disabled={submittingMeeting}>{submittingMeeting ? "Submitting..." : "Submit for Approval"}</Button></div>
            </form>
          </CardContent>
        </Card>
      )}
    </div>
  );
}