import { useMemo } from 'react';
import { Calendar, Spin, Empty, theme } from 'antd';
import { BellOutlined, EnvironmentOutlined } from '@ant-design/icons';
import type { Dayjs } from 'dayjs';
import type { PersonalCalendarItem, CalendarLayer } from '@/types/api';
import { hexToRgba, formatTimeShort } from './calendarUtils';

const { useToken } = theme;

interface PersonalCalendarViewProps {
  items: PersonalCalendarItem[];
  layers?: CalendarLayer[];
  loading?: boolean;
  currentMonth: Dayjs;
  selectedDate: string | null;
  onDateSelect: (date: string) => void;
  onItemClick: (item: PersonalCalendarItem) => void;
  onMonthChange: (month: Dayjs) => void;
}

const MAX_CELL_ITEMS = 3;

export default function PersonalCalendarView({
  items,
  loading,
  currentMonth,
  onDateSelect,
  onItemClick,
  onMonthChange,
}: PersonalCalendarViewProps) {
  useToken();

  // Group items by date
  const itemsByDate = useMemo(() => {
    const map: Record<string, PersonalCalendarItem[]> = {};
    for (const item of items) {
      const arr = map[item.date];
      if (arr) {
        arr.push(item);
      } else {
        map[item.date] = [item];
      }
    }
    for (const key of Object.keys(map)) {
      map[key]!.sort((a, b) => a.startTime.localeCompare(b.startTime));
    }
    return map;
  }, [items]);

  const handleSelect = (date: Dayjs) => {
    onDateSelect(date.format('YYYY-MM-DD'));
  };

  const handlePanelChange = (date: Dayjs) => {
    onMonthChange(date);
  };

  const cellRender = (date: Dayjs) => {
    const dateKey = date.format('YYYY-MM-DD');
    const dayItems = itemsByDate[dateKey];
    if (!dayItems || dayItems.length === 0) return null;

    const visible = dayItems.slice(0, MAX_CELL_ITEMS);
    const overflow = dayItems.length - MAX_CELL_ITEMS;

    return (
      <div
        style={{
          display: 'flex',
          flexDirection: 'column',
          gap: 3,
          padding: '0 2px',
        }}
      >
        {visible.map((item) => {
          const isTimeBlock = item.itemType === 'TIME_BLOCK';
          const isReminder = item.itemType === 'REMINDER';
          const color = item.color || '#1890ff';
          const bgAlpha = isTimeBlock ? 0.1 : 0.2;
          const borderAlpha = isTimeBlock ? 0.3 : 0.5;
          const isSystemType = item.type !== 'personal';

          return (
            <div
              key={item.id}
              onClick={(e) => {
                e.stopPropagation();
                onItemClick(item);
              }}
              style={{
                background: hexToRgba(color, bgAlpha),
                border: isTimeBlock
                  ? `1px dashed ${hexToRgba(color, borderAlpha)}`
                  : `1px solid ${hexToRgba(color, borderAlpha)}`,
                borderLeft: `3px solid ${color}`,
                borderRadius: 4,
                padding: '2px 5px',
                fontSize: 12,
                lineHeight: '16px',
                overflow: 'hidden',
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                color: 'rgba(255,255,255,0.85)',
                cursor: 'pointer',
                opacity: isTimeBlock ? 0.75 : 1,
              }}
            >
              {!item.isAllDay && (
                <span style={{ color: 'rgba(255,255,255,0.5)', marginRight: 3, fontSize: 10 }}>
                  {formatTimeShort(item.startTime)}-{formatTimeShort(item.endTime)}
                </span>
              )}
              {isReminder && (
                <BellOutlined style={{ fontSize: 9, marginRight: 3, color: 'rgba(255,255,255,0.5)' }} />
              )}
              {isSystemType && (
                <span
                  style={{
                    fontSize: 9,
                    color: 'rgba(255,255,255,0.5)',
                    marginRight: 3,
                    textTransform: 'uppercase',
                  }}
                >
                  [{item.type}]
                </span>
              )}
              {item.title}
              {item.location && (
                <span style={{ color: 'rgba(255,255,255,0.4)', marginLeft: 4, fontSize: 10 }}>
                  <EnvironmentOutlined style={{ fontSize: 9, marginRight: 2 }} />
                  {item.location}
                </span>
              )}
            </div>
          );
        })}
        {overflow > 0 && (
          <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.45)', textAlign: 'center' }}>
            +{overflow} more
          </div>
        )}
      </div>
    );
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: 40 }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div style={{ position: 'relative' }}>
      {loading && (
        <div style={{ textAlign: 'center', padding: 12 }}>
          <Spin />
        </div>
      )}
      <Calendar
        fullscreen
        value={currentMonth}
        cellRender={(date) => cellRender(date)}
        onSelect={handleSelect}
        onPanelChange={handlePanelChange}
        headerRender={() => null}
      />
      {items.length === 0 && (
        <div
          style={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            pointerEvents: 'none',
          }}
        >
          <Empty description="No calendar items. Click a date to add one." />
        </div>
      )}
    </div>
  );
}
