import { useState, FormEvent } from 'react';
import type { CalendarEvent } from '../../types/calendar';
import { createEvent, updateEvent } from '../../api/calendar';
import { toast } from 'sonner';

const COLOR_SWATCHES = [
  { label: 'Blue', value: 'blue', cls: 'bg-blue-500' },
  { label: 'Green', value: 'green', cls: 'bg-green-500' },
  { label: 'Red', value: 'red', cls: 'bg-red-500' },
  { label: 'Purple', value: 'purple', cls: 'bg-purple-500' },
  { label: 'Orange', value: 'orange', cls: 'bg-orange-500' },
  { label: 'Pink', value: 'pink', cls: 'bg-pink-500' },
];

interface Props {
  date: string;
  existing?: CalendarEvent;
  defaultType?: CalendarEvent['event_type'];
  onSuccess: () => void;
  onCancel: () => void;
}

export default function CalendarEventForm({ date, existing, defaultType = 'general', onSuccess, onCancel }: Props) {
  const [title, setTitle] = useState(existing?.title ?? '');
  const [description, setDescription] = useState(existing?.description ?? '');
  const [eventType, setEventType] = useState<CalendarEvent['event_type']>(existing?.event_type ?? defaultType);
  const [color, setColor] = useState(existing?.color ?? '');
  const [startTime, setStartTime] = useState(existing?.start_time ?? '');
  const [isCompleted, setIsCompleted] = useState(existing?.is_completed ?? false);
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    if (!title.trim()) {
      toast.error('Title is required');
      return;
    }
    setSubmitting(true);
    try {
      if (existing?.id) {
        await updateEvent(existing.id, {
          title: title.trim(),
          description: description.trim() || undefined,
          event_type: eventType,
          color: color || undefined,
          start_time: startTime || undefined,
          is_completed: isCompleted,
        });
        toast.success('Event updated');
      } else {
        await createEvent({
          date,
          title: title.trim(),
          description: description.trim() || undefined,
          event_type: eventType,
          color: color || undefined,
          start_time: startTime || undefined,
          is_completed: isCompleted,
        });
        toast.success('Event created');
      }
      onSuccess();
    } catch {
      toast.error('Failed to save event');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1">
          Title <span className="text-red-500">*</span>
        </label>
        <input
          type="text"
          value={title}
          onChange={e => setTitle(e.target.value)}
          className="w-full rounded-md border border-zinc-300 dark:border-zinc-600 bg-white dark:bg-zinc-800 px-3 py-2 text-sm text-zinc-900 dark:text-zinc-100 focus:outline-none focus:ring-2 focus:ring-primary"
          placeholder="Event title"
          required
        />
      </div>

      <div>
        <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1">
          Description
        </label>
        <textarea
          value={description}
          onChange={e => setDescription(e.target.value)}
          rows={2}
          className="w-full rounded-md border border-zinc-300 dark:border-zinc-600 bg-white dark:bg-zinc-800 px-3 py-2 text-sm text-zinc-900 dark:text-zinc-100 focus:outline-none focus:ring-2 focus:ring-primary resize-none"
          placeholder="Optional description"
        />
      </div>

      <div className="grid grid-cols-2 gap-3">
        <div>
          <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1">Type</label>
          <select
            value={eventType}
            onChange={e => setEventType(e.target.value as CalendarEvent['event_type'])}
            className="w-full rounded-md border border-zinc-300 dark:border-zinc-600 bg-white dark:bg-zinc-800 px-3 py-2 text-sm text-zinc-900 dark:text-zinc-100 focus:outline-none focus:ring-2 focus:ring-primary"
          >
            <option value="general">General</option>
            <option value="workout">Workout</option>
            <option value="supplement">Supplement</option>
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1">Start Time</label>
          <input
            type="time"
            value={startTime}
            onChange={e => setStartTime(e.target.value)}
            className="w-full rounded-md border border-zinc-300 dark:border-zinc-600 bg-white dark:bg-zinc-800 px-3 py-2 text-sm text-zinc-900 dark:text-zinc-100 focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </div>
      </div>

      <div>
        <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">Color</label>
        <div className="flex gap-2">
          <button
            type="button"
            onClick={() => setColor('')}
            className={`w-7 h-7 rounded-full border-2 bg-zinc-200 dark:bg-zinc-600 ${!color ? 'border-primary' : 'border-transparent'}`}
            title="None"
          />
          {COLOR_SWATCHES.map(s => (
            <button
              key={s.value}
              type="button"
              onClick={() => setColor(s.value)}
              className={`w-7 h-7 rounded-full border-2 ${s.cls} ${color === s.value ? 'border-primary' : 'border-transparent'}`}
              title={s.label}
            />
          ))}
        </div>
      </div>

      <div className="flex items-center gap-2">
        <input
          id="is-completed"
          type="checkbox"
          checked={isCompleted}
          onChange={e => setIsCompleted(e.target.checked)}
          className="rounded border-zinc-300 dark:border-zinc-600 text-primary focus:ring-primary"
        />
        <label htmlFor="is-completed" className="text-sm text-zinc-700 dark:text-zinc-300">Mark as completed</label>
      </div>

      <div className="flex gap-2 pt-2">
        <button
          type="submit"
          disabled={submitting}
          className="flex-1 rounded-md bg-primary px-4 py-2 text-sm font-medium text-white hover:bg-primary/90 disabled:opacity-50 transition-colors"
        >
          {submitting ? 'Saving...' : existing ? 'Update' : 'Create'}
        </button>
        <button
          type="button"
          onClick={onCancel}
          className="flex-1 rounded-md border border-zinc-300 dark:border-zinc-600 px-4 py-2 text-sm font-medium text-zinc-700 dark:text-zinc-300 hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
        >
          Cancel
        </button>
      </div>
    </form>
  );
}
