import { Calendar, Badge, Tag, Spin } from 'antd';
import type { CalendarProps } from 'antd';
import type { Dayjs } from 'dayjs';
import type { Shift } from '@/types/api';

interface Props {
  loading: boolean;
  calendarData: Record<string, { count: number; shifts: Shift[] }>;
  onSelectDate: (date: Dayjs) => void;
  onSelectShift: (shift: Shift) => void;
}

export default function ShiftsCalendar({
  loading,
  calendarData,
  onSelectDate,
  onSelectShift,
}: Props) {
  const cellRender: CalendarProps<Dayjs>['cellRender'] = (current, info) => {
    if (info.type !== 'date') return info.originNode;

    const dateKey = current.format('YYYY-MM-DD');
    const dayData = calendarData[dateKey];

    if (!dayData) return null;

    return (
      <div>
        <Badge count={dayData.count} style={{ backgroundColor: '#1890ff' }} />
        <div style={{ marginTop: 8 }}>
          {dayData.shifts.slice(0, 3).map((shift) => (
            <Tag
              key={shift.id}
              color={shift.status === 'OPEN' ? 'blue' : shift.status === 'FULL' ? 'green' : 'red'}
              style={{
                marginBottom: 4,
                cursor: 'pointer',
                display: 'block',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
              }}
              onClick={(e) => {
                e.stopPropagation();
                onSelectShift(shift);
              }}
            >
              {shift.startTime} {shift.title}
            </Tag>
          ))}
          {dayData.count > 3 && (
            <Tag style={{ display: 'block' }}>+{dayData.count - 3} more</Tag>
          )}
        </div>
      </div>
    );
  };

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

  return (
    <Calendar
      cellRender={cellRender}
      onSelect={onSelectDate}
    />
  );
}
