"use client";

import { useState } from "react";
import { X } from "lucide-react";
import { format } from "date-fns";
import { useCalendarContext } from "@/components/providers/CalendarProvider";
import type { PersonFilter } from "@/lib/types";
import { PERSON_COLORS } from "@/lib/types";

interface EventModalProps {
  open: boolean;
  onClose: () => void;
  initialDate?: Date;
  editEvent?: {
    id: string;
    title: string;
    description: string | null;
    notes: string | null;
    start_time: string;
    end_time: string;
    all_day: number;
    location: string | null;
    recurrence_rule: string | null;
    calendar_id: string;
    people: { person_name: string; invite_preference: string }[];
  };
}

const PEOPLE: PersonFilter[] = [];

export default function EventModal({ open, onClose, initialDate, editEvent }: EventModalProps) {
  const { calendars, createEvent, updateEvent } = useCalendarContext();

  const familyCal = calendars.find((c) => c.type === "family");

  const [title, setTitle] = useState(editEvent?.title || "");
  const [description, setDescription] = useState(editEvent?.description || "");
  const [notes, setNotes] = useState(editEvent?.notes || "");
  const [calendarId, setCalendarId] = useState(editEvent?.calendar_id || familyCal?.id || "");
  const [allDay, setAllDay] = useState(editEvent ? editEvent.all_day === 1 : false);
  const [startDate, setStartDate] = useState(
    editEvent ? format(new Date(editEvent.start_time), "yyyy-MM-dd") : initialDate ? format(initialDate, "yyyy-MM-dd") : format(new Date(), "yyyy-MM-dd")
  );
  const [startTime, setStartTime] = useState(
    editEvent && editEvent.all_day === 0 ? format(new Date(editEvent.start_time), "HH:mm") : "09:00"
  );
  const [endDate, setEndDate] = useState(
    editEvent ? format(new Date(editEvent.end_time), "yyyy-MM-dd") : initialDate ? format(initialDate, "yyyy-MM-dd") : format(new Date(), "yyyy-MM-dd")
  );
  const [endTime, setEndTime] = useState(
    editEvent && editEvent.all_day === 0 ? format(new Date(editEvent.end_time), "HH:mm") : "10:00"
  );
  const [location, setLocation] = useState(editEvent?.location || "");
  const [selectedPeople, setSelectedPeople] = useState<
    Record<string, { selected: boolean; preference: string }>
  >(
    PEOPLE.reduce(
      (acc, p) => {
        const existing = editEvent?.people.find((ep) => ep.person_name === p);
        acc[p] = {
          selected: !!existing,
          preference: existing?.invite_preference || "reminder_only",
        };
        return acc;
      },
      {} as Record<string, { selected: boolean; preference: string }>
    )
  );
  const [saving, setSaving] = useState(false);

  if (!open) return null;

  const handleSave = async () => {
    if (!title.trim() || !calendarId) return;
    setSaving(true);

    const startISO = allDay
      ? `${startDate}T00:00:00.000Z`
      : new Date(`${startDate}T${startTime}`).toISOString();
    const endISO = allDay
      ? `${endDate}T23:59:59.999Z`
      : new Date(`${endDate}T${endTime}`).toISOString();

    const people = PEOPLE.filter((p) => selectedPeople[p]?.selected).map((p) => ({
      person_name: p,
      invite_preference: selectedPeople[p].preference,
    }));

    if (editEvent) {
      await updateEvent(editEvent.id, {
        title,
        description: description || undefined,
        notes: notes || undefined,
        start_time: startISO,
        end_time: endISO,
        all_day: allDay,
        location: location || undefined,
        people,
      });
    } else {
      await createEvent({
        calendar_id: calendarId,
        title,
        description: description || undefined,
        notes: notes || undefined,
        start_time: startISO,
        end_time: endISO,
        all_day: allDay,
        location: location || undefined,
        created_by: "web",
        people,
      });
    }

    setSaving(false);
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50" onClick={onClose}>
      <div
        className="bg-white dark:bg-zinc-900 rounded-lg shadow-xl w-full max-w-md mx-4 max-h-[90vh] overflow-auto"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between p-4 border-b border-zinc-200 dark:border-zinc-700">
          <h3 className="font-semibold">{editEvent ? "Edit Event" : "New Event"}</h3>
          <button onClick={onClose} className="p-1 rounded hover:bg-zinc-100 dark:hover:bg-zinc-800">
            <X className="w-4 h-4" />
          </button>
        </div>

        <div className="p-4 flex flex-col gap-3">
          <input
            type="text"
            placeholder="Event title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            className="w-full px-3 py-2 rounded-md border border-zinc-300 dark:border-zinc-600 bg-transparent text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            autoFocus
          />

          <select
            value={calendarId}
            onChange={(e) => setCalendarId(e.target.value)}
            className="w-full px-3 py-2 rounded-md border border-zinc-300 dark:border-zinc-600 bg-transparent text-sm"
          >
            {calendars.map((cal) => (
              <option key={cal.id} value={cal.id}>{cal.name}</option>
            ))}
          </select>

          <label className="flex items-center gap-2 text-sm">
            <input type="checkbox" checked={allDay} onChange={(e) => setAllDay(e.target.checked)} className="rounded" />
            All day
          </label>

          <div className="grid grid-cols-2 gap-2">
            <div>
              <label className="text-xs text-zinc-500">Start</label>
              <input type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} className="w-full px-2 py-1.5 rounded border border-zinc-300 dark:border-zinc-600 bg-transparent text-sm" />
            </div>
            {!allDay && (
              <div>
                <label className="text-xs text-zinc-500">&nbsp;</label>
                <input type="time" value={startTime} onChange={(e) => setStartTime(e.target.value)} className="w-full px-2 py-1.5 rounded border border-zinc-300 dark:border-zinc-600 bg-transparent text-sm" />
              </div>
            )}
            <div>
              <label className="text-xs text-zinc-500">End</label>
              <input type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)} className="w-full px-2 py-1.5 rounded border border-zinc-300 dark:border-zinc-600 bg-transparent text-sm" />
            </div>
            {!allDay && (
              <div>
                <label className="text-xs text-zinc-500">&nbsp;</label>
                <input type="time" value={endTime} onChange={(e) => setEndTime(e.target.value)} className="w-full px-2 py-1.5 rounded border border-zinc-300 dark:border-zinc-600 bg-transparent text-sm" />
              </div>
            )}
          </div>

          <input type="text" placeholder="Location (optional)" value={location} onChange={(e) => setLocation(e.target.value)} className="w-full px-3 py-2 rounded-md border border-zinc-300 dark:border-zinc-600 bg-transparent text-sm" />

          <textarea placeholder="Description (optional)" value={description} onChange={(e) => setDescription(e.target.value)} rows={2} className="w-full px-3 py-2 rounded-md border border-zinc-300 dark:border-zinc-600 bg-transparent text-sm resize-none" />

          <textarea placeholder="Notes (optional)" value={notes} onChange={(e) => setNotes(e.target.value)} rows={2} className="w-full px-3 py-2 rounded-md border border-zinc-300 dark:border-zinc-600 bg-transparent text-sm resize-none" />

          <div>
            <label className="text-xs font-medium text-zinc-500 mb-1 block">People</label>
            {PEOPLE.map((person) => (
              <div key={person} className="flex items-center gap-2 py-1">
                <input type="checkbox" checked={selectedPeople[person]?.selected || false} onChange={(e) => setSelectedPeople((prev) => ({ ...prev, [person]: { ...prev[person], selected: e.target.checked } }))} className="rounded" />
                <span className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: PERSON_COLORS[person] }} />
                <span className="text-sm capitalize flex-1">{person}</span>
                {selectedPeople[person]?.selected && (
                  <select value={selectedPeople[person].preference} onChange={(e) => setSelectedPeople((prev) => ({ ...prev, [person]: { ...prev[person], preference: e.target.value } }))} className="text-xs px-2 py-1 rounded border border-zinc-300 dark:border-zinc-600 bg-transparent">
                    <option value="reminder_only">Reminder only</option>
                    <option value="calendar_invite">Calendar invite</option>
                    <option value="both">Both</option>
                    <option value="none">None</option>
                  </select>
                )}
              </div>
            ))}
          </div>
        </div>

        <div className="flex justify-end gap-2 p-4 border-t border-zinc-200 dark:border-zinc-700">
          <button onClick={onClose} className="px-4 py-2 text-sm rounded-md hover:bg-zinc-100 dark:hover:bg-zinc-800">Cancel</button>
          <button onClick={handleSave} disabled={!title.trim() || saving} className="px-4 py-2 text-sm rounded-md bg-blue-500 text-white hover:bg-blue-600 disabled:opacity-50">
            {saving ? "Saving..." : editEvent ? "Update" : "Create"}
          </button>
        </div>
      </div>
    </div>
  );
}
