import { useEffect, useMemo, useState } from 'react';
import { api } from '../lib/api.ts';

interface CalendarEvent {
  id: string;
  channel_id: string;
  creator_id: string;
  title: string;
  description: string | null;
  start_time: string;
  end_time: string | null;
  recurrence_rule: string | null;
  location: string | null;
  color: string | null;
  going_count: number;
  maybe_count: number;
  no_count: number;
  user_status: string;
}

interface CalendarViewProps {
  channelId: string;
  channelName: string;
}

export function CalendarView({ channelId, channelName }: CalendarViewProps) {
  const [events, setEvents] = useState<CalendarEvent[]>([]);
  const [date, setDate] = useState(() => new Date());
  const [loading, setLoading] = useState(false);
  const [showForm, setShowForm] = useState(false);
  const [title, setTitle] = useState('');
  const [start, setStart] = useState('');
  const [end, setEnd] = useState('');
  const [description, setDescription] = useState('');
  const [selectedEvent, setSelectedEvent] = useState<CalendarEvent | null>(null);

  const monthStart = useMemo(() => new Date(date.getFullYear(), date.getMonth(), 1), [date]);
  const monthEnd = useMemo(() => new Date(date.getFullYear(), date.getMonth() + 1, 0), [date]);
  const days: (number | null)[] = useMemo(() => {
    const startDay = monthStart.getDay();
    const total = monthEnd.getDate();
    const arr: (number | null)[] = Array(startDay).fill(null);
    for (let i = 1; i <= total; i++) arr.push(i);
    return arr;
  }, [monthStart, monthEnd]);

  useEffect(() => {
    const from = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-01T00:00:00Z`;
    const to = `${date.getFullYear()}-${String(date.getMonth() + 2).padStart(2, '0')}-01T00:00:00Z`;
    setLoading(true);
    api.get<CalendarEvent[]>(`/channels/${channelId}/events?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`)
      .then((data) => setEvents(Array.isArray(data) ? data : []))
      .finally(() => setLoading(false));
  }, [channelId, date]);

  const eventsForDay = (day: number) => {
    const d = new Date(date.getFullYear(), date.getMonth(), day);
    return events.filter((e) => {
      const start = new Date(e.start_time);
      return start.getFullYear() === d.getFullYear() && start.getMonth() === d.getMonth() && start.getDate() === d.getDate();
    });
  };

  const handleCreate = async () => {
    if (!title || !start) return;
    const payload = { title, start_time: start, end_time: end || undefined, description: description || undefined };
    const ev = await api.post<CalendarEvent>(`/channels/${channelId}/events`, payload);
    setEvents((prev) => [...prev, ev]);
    setShowForm(false);
    setTitle('');
    setStart('');
    setEnd('');
    setDescription('');
  };

  const handleRSVP = async (eventId: string, status: 'going' | 'maybe' | 'no') => {
    await api.post(`/events/${eventId}/rsvp`, { status });
    setEvents((prev) => prev.map((e) => e.id === eventId ? { ...e, user_status: status } : e));
  };

  const prevMonth = () => setDate((d) => new Date(d.getFullYear(), d.getMonth() - 1, 1));
  const nextMonth = () => setDate((d) => new Date(d.getFullYear(), d.getMonth() + 1, 1));

  return (
    <div className="flex flex-col h-full bg-gb-bg">
      <div className="terminal-border border-t-0 border-x-0 px-3 py-2 text-gb-fg-s flex items-center justify-between">
        <span>○ {channelName}</span>
        <button onClick={() => setShowForm((p) => !p)} className="text-xs text-gb-fg-f hover:text-gb-orange font-mono">[NEW EVENT]</button>
      </div>
      {showForm && (
        <div className="p-3 border-b border-gb-bg-t space-y-2 font-mono text-xs">
          <input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="title" className="terminal-input w-full" />
          <input type="datetime-local" value={start} onChange={(e) => setStart(e.target.value)} className="terminal-input w-full" />
          <input type="datetime-local" value={end} onChange={(e) => setEnd(e.target.value)} className="terminal-input w-full" />
          <textarea value={description} onChange={(e) => setDescription(e.target.value)} placeholder="description" className="terminal-input w-full h-16" />
          <button onClick={handleCreate} disabled={!title || !start} className="px-3 py-1 bg-gb-orange text-gb-bg disabled:opacity-50">[CREATE]</button>
        </div>
      )}
      <div className="p-3 flex items-center justify-between font-mono text-xs">
        <button onClick={prevMonth} className="text-gb-fg-f hover:text-gb-orange">[&lt;]</button>
        <span className="text-gb-fg">{date.toLocaleString('default', { month: 'long', year: 'numeric' })}</span>
        <button onClick={nextMonth} className="text-gb-fg-f hover:text-gb-orange">[&gt;]</button>
      </div>
      {loading && <div className="p-3 text-gb-fg-f text-xs font-mono">[loading...]</div>}
      <div className="flex-1 overflow-y-auto p-3">
        <div className="grid grid-cols-7 gap-1 text-center text-xs font-mono text-gb-fg-s mb-1">
          {['S','M','T','W','T','F','S'].map((d) => <div key={d}>{d}</div>)}
        </div>
        <div className="grid grid-cols-7 gap-1">
          {days.map((day, idx) => (
            <div key={idx} className="min-h-16 border border-gb-bg-t p-1 text-xs">
              {day !== null && (
                <>
                  <div className="text-gb-fg-f font-mono">{day}</div>
                  {eventsForDay(day).map((ev) => (
                    <button
                      key={ev.id}
                      onClick={() => setSelectedEvent(ev)}
                      className="w-full text-left mt-1 px-1 py-0.5 truncate text-gb-bg font-mono"
                      style={{ backgroundColor: ev.color || '#b8bb26' }}
                    >
                      {ev.title}
                    </button>
                  ))}
                </>
              )}
            </div>
          ))}
        </div>
      </div>
      {selectedEvent && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-gb-bg/90 p-4" onClick={() => setSelectedEvent(null)}>
          <div className="bg-gb-bg border border-gb-fg-t w-full max-w-sm p-4" onClick={(e) => e.stopPropagation()}>
            <div className="text-gb-fg font-bold mb-1">{selectedEvent.title}</div>
            <div className="text-gb-fg-s text-xs font-mono mb-2">
              {new Date(selectedEvent.start_time).toLocaleString()}
              {selectedEvent.end_time && ` → ${new Date(selectedEvent.end_time).toLocaleString()}`}
            </div>
            {selectedEvent.description && <div className="text-gb-fg-s text-xs mb-2">{selectedEvent.description}</div>}
            <div className="flex gap-2 text-xs font-mono mb-3">
              <span className="text-gb-green">going:{selectedEvent.going_count}</span>
              <span className="text-gb-orange">maybe:{selectedEvent.maybe_count}</span>
              <span className="text-gb-red">no:{selectedEvent.no_count}</span>
            </div>
            <div className="flex gap-2">
              {(['going','maybe','no'] as const).map((s) => (
                <button
                  key={s}
                  onClick={() => handleRSVP(selectedEvent.id, s)}
                  className={`px-2 py-1 border ${selectedEvent.user_status === s ? 'bg-gb-orange text-gb-bg border-gb-orange' : 'border-gb-bg-t text-gb-fg-s'}`}
                >
                  {s}
                </button>
              ))}
              <button onClick={() => setSelectedEvent(null)} className="ml-auto text-gb-fg-f hover:text-gb-orange">[x]</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
