import React, { useState, useEffect } from 'react';
import { format, startOfWeek, addDays, isSameDay, parseISO, isBefore } from 'date-fns';
import { cs } from 'date-fns/locale';
import { Event } from '../../types/event';
import { getEvents } from '../../services/eventService';
import { getMatches } from '../../services/public';

interface CalendarProps {
  onEventClick?: (event: Event) => void;
}

const Calendar: React.FC<CalendarProps> = ({ onEventClick }) => {
  const [currentDate, setCurrentDate] = useState(new Date());
  const [events, setEvents] = useState<Event[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [latestResults, setLatestResults] = useState<any[]>([]);

  useEffect(() => {
    const fetchEvents = async () => {
      try {
        const data = await getEvents();
        setEvents(data);
      } catch (err) {
        setError('Nepodařilo se načíst události');
        console.error('Error fetching events:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchEvents();
  }, []);

  // Fetch latest results (small sidebar)
  useEffect(() => {
    let active = true;
    (async () => {
      try {
        const matches = await getMatches();
        // Expecting items with date or date_time and score/result
        const now = new Date();
        const normalized = (Array.isArray(matches) ? matches : []).map((m: any) => {
          const dt = parseISO(m.date_time || m.date || m.match_date || m.datetime || '');
          return { ...m, __dt: isNaN(dt as any) ? null : dt };
        }).filter((m: any) => m.__dt && isBefore(m.__dt, now));
        normalized.sort((a: any, b: any) => (b.__dt as any) - (a.__dt as any));
        const recent = normalized.slice(0, 6);
        if (active) setLatestResults(recent);
      } catch (e) {
        // silent fail for sidebar
      }
    })();
    return () => { active = false };
  }, []);

  const startDate = startOfWeek(currentDate, { weekStartsOn: 1 }); // Start on Monday
  const days = [];
  
  for (let i = 0; i < 7; i++) {
    const day = addDays(startDate, i);
    days.push(day);
  }

  const getEventsForDay = (day: Date) => {
    return events.filter(event => {
      const eventDate = parseISO(event.start_time);
      return isSameDay(eventDate, day);
    });
  };

  const getEventTypeColor = (type: string) => {
    switch (type) {
      case 'match':
        return 'bg-red-100 text-red-800 border-red-200';
      case 'training':
        return 'bg-blue-100 text-blue-800 border-blue-200';
      case 'meeting':
        return 'bg-green-100 text-green-800 border-green-200';
      default:
        return 'bg-gray-100 text-gray-800 border-gray-200';
    }
  };

  if (loading) return <div>Načítám kalendář...</div>;
  if (error) return <div className="text-red-500">{error}</div>;

  return (
    <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
      {/* Main Calendar (more prominent) */}
      <div className="lg:col-span-3">
        <div className="bg-white rounded-lg shadow overflow-hidden">
          {/* Week header */}
          <div className="grid grid-cols-7 gap-px bg-gray-200">
            {days.map((day, i) => {
              const isToday = isSameDay(day, new Date());
              return (
                <div key={i} className={`bg-white p-3 text-center ${isToday ? 'ring-2 ring-blue-500 ring-offset-2 ring-offset-white' : ''}`}>
                  <div className="font-semibold text-gray-900 uppercase tracking-wide text-xs">
                    {format(day, 'EEEE', { locale: cs })}
                  </div>
                  <div className={`mt-1 text-xl font-bold ${isToday ? 'text-blue-600' : 'text-gray-900'}`}>
                    {format(day, 'd')}
                  </div>
                </div>
              );
            })}
          </div>

          {/* Grouped events by day */}
          <div className="p-4">
            {days.map((day, i) => {
              const dayEvents = getEventsForDay(day);
              const isToday = isSameDay(day, new Date());
              return (
                <div key={i} className="mb-5">
                  <div className={`sticky top-0 z-10 px-3 py-2 ${isToday ? 'bg-blue-50 border-l-4 border-blue-500' : 'bg-gray-50 border-l-4 border-gray-300'}`}>
                    <h3 className={`text-sm md:text-base font-semibold tracking-wide ${isToday ? 'text-blue-700' : 'text-gray-800'}`}>
                      {format(day, 'EEEE d. M. yyyy', { locale: cs })}
                      {isToday && <span className="ml-2 text-[10px] md:text-xs font-bold text-blue-700 uppercase bg-blue-100 px-2 py-0.5 rounded-full">Dnes</span>}
                    </h3>
                  </div>
                  {dayEvents.length > 0 ? (
                    <div className="mt-2 space-y-2">
                      {dayEvents.map((event) => (
                        <div
                          key={event.id}
                          onClick={() => onEventClick?.(event)}
                          className={`p-3 rounded-md border cursor-pointer transition-colors ${getEventTypeColor(event.type)} hover:opacity-95`}
                          style={{ borderColor: 'rgba(0,0,0,0.08)' }}
                        >
                          <div className="flex items-center justify-between">
                            <div className="font-medium truncate pr-2">{event.title}</div>
                            <div className="text-[10px] md:text-xs px-2 py-0.5 rounded-full bg-white/70 border border-black/10 text-gray-700">
                              {event.type}
                            </div>
                          </div>
                          <div className="text-sm text-gray-700">
                            {format(parseISO(event.start_time), 'H:mm', { locale: cs })}
                            {event.location && ` • ${event.location}`}
                          </div>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <p className="mt-2 text-gray-500 text-sm">Žádné události</p>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Sidebar: Latest Results (compact, space-saving) */}
      <aside className="lg:col-span-1">
        <div className="bg-white rounded-lg shadow p-2 lg:sticky lg:top-2">
          <h3 className="text-xs font-semibold text-gray-800 mb-2 tracking-wide uppercase">Nejnovější výsledky</h3>
          {latestResults.length === 0 ? (
            <p className="text-gray-500 text-xs">Zatím žádné výsledky</p>
          ) : (
            <ul className="space-y-1">
              {latestResults.slice(0,6).map((m: any, idx: number) => {
                const nameHome = (m.home || m.home_team) || 'Domácí';
                const nameAway = (m.away || m.away_team) || 'Hosté';
                const score = m.score || (typeof m.result_home === 'number' && typeof m.result_away === 'number' ? `${m.result_home}:${m.result_away}` : '-');
                const dtRaw = (m.date_time || m.date || m.match_date || m.datetime || '') as string;
                let shortDate = '';
                try {
                  const parsed = parseISO(dtRaw);
                  if (!isNaN((parsed as any))) {
                    shortDate = format(parsed as any, 'd.M.', { locale: cs });
                  }
                } catch {}
                return (
                  <li key={idx} className="flex items-center justify-between gap-2 p-1.5 rounded border border-gray-200/70 hover:bg-gray-50">
                    <div className="flex-1 min-w-0 text-[11px] font-medium text-gray-900 truncate">
                      <span className="truncate inline-block max-w-[46%] align-bottom">{nameHome}</span>
                      <span className="mx-1 text-gray-500">vs</span>
                      <span className="truncate inline-block max-w-[46%] align-bottom">{nameAway}</span>
                    </div>
                    <div className="flex items-center gap-1 flex-shrink-0">
                      {shortDate && (
                        <span className="hidden sm:inline-block text-[10px] text-gray-600 bg-gray-100 border border-gray-200 rounded px-1 py-0.5">{shortDate}</span>
                      )}
                      <span className="text-[10px] font-extrabold bg-gray-800 text-white rounded px-1.5 py-0.5">{score}</span>
                    </div>
                  </li>
                );
              })}
            </ul>
          )}
        </div>
      </aside>
    </div>
  );
};

export default Calendar;
