import { useState, useEffect } from "react";
import { format } from "date-fns";
import type { CalendarEvent, Calendar } from "../types";
import { api } from "../api";
import Modal from "./Modal";

interface EventModalProps {
  open: boolean;
  onClose: () => void;
  onSaved: () => void;
  event?: CalendarEvent | null;
  calendars: Calendar[];
  defaultDate?: Date;
  defaultCalendarId?: string;
}

export default function EventModal({
  open,
  onClose,
  onSaved,
  event,
  calendars,
  defaultDate,
  defaultCalendarId,
}: EventModalProps) {
  const isEdit = !!event;
  const writableCalendars = calendars.filter((c) => c.role !== "viewer");

  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [location, setLocation] = useState("");
  const [calendarId, setCalendarId] = useState("");
  const [startDate, setStartDate] = useState("");
  const [startTime, setStartTime] = useState("09:00");
  const [endDate, setEndDate] = useState("");
  const [endTime, setEndTime] = useState("10:00");
  const [allDay, setAllDay] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [showDelete, setShowDelete] = useState(false);

  useEffect(() => {
    if (!open) return;
    setError("");
    setShowDelete(false);
    if (event) {
      setTitle(event.title);
      setDescription(event.description || "");
      setLocation(event.location || "");
      setCalendarId(event.calendar_id);
      setAllDay(event.all_day);
      const st = new Date(event.start_time);
      const et = new Date(event.end_time);
      setStartDate(format(st, "yyyy-MM-dd"));
      setStartTime(format(st, "HH:mm"));
      setEndDate(format(et, "yyyy-MM-dd"));
      setEndTime(format(et, "HH:mm"));
    } else {
      setTitle("");
      setDescription("");
      setLocation("");
      setCalendarId(defaultCalendarId || writableCalendars[0]?.id || "");
      setAllDay(false);
      const d = defaultDate || new Date();
      const dateStr = format(d, "yyyy-MM-dd");
      setStartDate(dateStr);
      setEndDate(dateStr);
      setStartTime("09:00");
      setEndTime("10:00");
    }
  }, [open, event, defaultDate, defaultCalendarId]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!title.trim() || !calendarId) return;
    setSaving(true);
    setError("");
    try {
      const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
      const startISO = allDay
        ? `${startDate}T00:00:00`
        : `${startDate}T${startTime}:00`;
      const endISO = allDay
        ? `${endDate}T23:59:59`
        : `${endDate}T${endTime}:00`;

      const payload = {
        title: title.trim(),
        description: description.trim() || undefined,
        location: location.trim() || undefined,
        start_time: new Date(startISO).toISOString(),
        end_time: new Date(endISO).toISOString(),
        timezone: tz,
        all_day: allDay,
      };

      if (isEdit) {
        await api.updateEvent(event!.id, payload);
      } else {
        await api.createEvent({ ...payload, calendar_id: calendarId });
      }
      onSaved();
      onClose();
    } catch (err: any) {
      setError(err.error || "Failed to save event");
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!event) return;
    setSaving(true);
    try {
      await api.deleteEvent(event.id);
      onSaved();
      onClose();
    } catch (err: any) {
      setError(err.error || "Failed to delete event");
    } finally {
      setSaving(false);
    }
  };

  const calColor =
    calendars.find((c) => c.id === calendarId)?.color || "#3B82F6";

  return (
    <Modal open={open} onClose={onClose} title={isEdit ? "Edit Event" : "New Event"}>
      <form onSubmit={handleSubmit} className="space-y-4">
        {error && (
          <div className="text-sm text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-900/20 px-3 py-2 rounded-lg">
            {error}
          </div>
        )}

        <div>
          <input
            type="text"
            placeholder="Event title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            className="w-full text-lg font-medium bg-transparent border-0 border-b-2 border-gray-200 dark:border-gray-600 focus:border-blue-500 dark:focus:border-blue-400 focus:ring-0 px-0 py-2 text-gray-900 dark:text-white placeholder-gray-400 outline-none transition-colors"
            autoFocus
            required
          />
        </div>

        {!isEdit && (
          <div>
            <label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
              Calendar
            </label>
            <div className="relative">
              <div
                className="absolute left-3 top-1/2 -translate-y-1/2 w-3 h-3 rounded-full"
                style={{ backgroundColor: calColor }}
              />
              <select
                value={calendarId}
                onChange={(e) => setCalendarId(e.target.value)}
                className="w-full pl-8 pr-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-sm text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
              >
                {writableCalendars.map((c) => (
                  <option key={c.id} value={c.id}>
                    {c.name}
                  </option>
                ))}
              </select>
            </div>
          </div>
        )}

        <div className="flex items-center gap-3">
          <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
            <input
              type="checkbox"
              checked={allDay}
              onChange={(e) => setAllDay(e.target.checked)}
              className="rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500"
            />
            All day
          </label>
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
              Start
            </label>
            <input
              type="date"
              value={startDate}
              onChange={(e) => {
                setStartDate(e.target.value);
                if (e.target.value > endDate) setEndDate(e.target.value);
              }}
              className="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-sm text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
              required
            />
            {!allDay && (
              <input
                type="time"
                value={startTime}
                onChange={(e) => setStartTime(e.target.value)}
                className="w-full mt-2 px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-sm text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
                required
              />
            )}
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
              End
            </label>
            <input
              type="date"
              value={endDate}
              onChange={(e) => setEndDate(e.target.value)}
              min={startDate}
              className="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-sm text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
              required
            />
            {!allDay && (
              <input
                type="time"
                value={endTime}
                onChange={(e) => setEndTime(e.target.value)}
                className="w-full mt-2 px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-sm text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
                required
              />
            )}
          </div>
        </div>

        <div>
          <label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
            Location
          </label>
          <input
            type="text"
            placeholder="Add location"
            value={location}
            onChange={(e) => setLocation(e.target.value)}
            className="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-sm text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none placeholder-gray-400"
          />
        </div>

        <div>
          <label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
            Description
          </label>
          <textarea
            placeholder="Add description"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            rows={3}
            className="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-sm text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none resize-none placeholder-gray-400"
          />
        </div>

        <div className="flex items-center justify-between pt-2">
          <div>
            {isEdit && !showDelete && (
              <button
                type="button"
                onClick={() => setShowDelete(true)}
                className="text-sm text-red-500 hover:text-red-700 dark:hover:text-red-400 transition-colors"
              >
                Delete event
              </button>
            )}
            {isEdit && showDelete && (
              <div className="flex items-center gap-2">
                <span className="text-sm text-red-500">Delete?</span>
                <button
                  type="button"
                  onClick={handleDelete}
                  className="text-sm text-white bg-red-500 hover:bg-red-600 px-3 py-1 rounded-lg transition-colors"
                  disabled={saving}
                >
                  Yes
                </button>
                <button
                  type="button"
                  onClick={() => setShowDelete(false)}
                  className="text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 transition-colors"
                >
                  No
                </button>
              </div>
            )}
          </div>
          <div className="flex gap-2">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={saving || !title.trim()}
              className="px-4 py-2 text-sm text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-50 rounded-lg transition-colors font-medium"
            >
              {saving ? "Saving..." : isEdit ? "Update" : "Create"}
            </button>
          </div>
        </div>
      </form>
    </Modal>
  );
}
