import { Drawer, Calendar, Badge, List, Tag, Button, Space, message, Empty, Alert, Skeleton, Grid } from 'antd';
import type { CalendarProps } from 'antd';
import { CalendarOutlined, ClockCircleOutlined, DeleteOutlined, ReloadOutlined } from '@ant-design/icons';
import { useState, useEffect } from 'react';
import dayjs, { Dayjs } from 'dayjs';
import { mediaApi } from '@/lib/media-api';
import { getErrorMessage } from '@/utils/getErrorMessage';

interface ScheduleEvent {
  jobId: string;
  videoId: number;
  videoTitle: string | null;
  action: 'publish' | 'unpublish';
  scheduledFor: string;
  status: string;
}

interface ScheduleCalendarDrawerProps {
  open: boolean;
  onClose: () => void;
  onRefresh?: () => void;
}

export default function ScheduleCalendarDrawer({
  open,
  onClose,
  onRefresh,
}: ScheduleCalendarDrawerProps) {
  const [schedules, setSchedules] = useState<ScheduleEvent[]>([]);
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedDate, setSelectedDate] = useState<Dayjs>(dayjs());
  const [selectedDateEvents, setSelectedDateEvents] = useState<ScheduleEvent[]>([]);

  useEffect(() => {
    if (open) {
      fetchSchedules();
    }
  }, [open]);

  useEffect(() => {
    // Filter events for selected date
    const dayEvents = schedules.filter((event) =>
      dayjs(event.scheduledFor).isSame(selectedDate, 'day')
    );
    setSelectedDateEvents(dayEvents);
  }, [selectedDate, schedules]);

  const fetchSchedules = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await mediaApi.get('/videos/schedules/upcoming', {
        params: { limit: 100 },
      });
      setSchedules(response.data.schedules || []);
    } catch (error: unknown) {
      console.error('Failed to fetch schedules:', error);
      setError(getErrorMessage(error, 'Failed to load schedules. Please try again.'));
    } finally {
      setLoading(false);
    }
  };

  const handleCancelSchedule = async (videoId: number, action: 'publish' | 'unpublish') => {
    try {
      await mediaApi.delete(`/videos/${videoId}/schedule/${action}`);
      message.success(`${action} schedule cancelled`);
      fetchSchedules();
      onRefresh?.();
    } catch (error: unknown) {
      message.error(getErrorMessage(error, `Failed to cancel ${action} schedule`));
    }
  };

  // Get events for a specific date
  const getListData = (value: Dayjs) => {
    const dayEvents = schedules.filter((event) =>
      dayjs(event.scheduledFor).isSame(value, 'day')
    );

    return dayEvents.map((event) => ({
      type: event.action === 'publish' ? 'success' : 'warning',
      content: `${event.videoTitle || `Video ${event.videoId}`} - ${event.action}`,
      time: dayjs(event.scheduledFor).format('HH:mm'),
    }));
  };

  // Render cell with badge count (new API)
  const cellRender: CalendarProps<Dayjs>['cellRender'] = (current, info) => {
    if (info.type !== 'date') return info.originNode;

    const listData = getListData(current);
    return (
      <div style={{ minHeight: 40 }}>
        {listData.length > 0 && (
          <div style={{ textAlign: 'center' }}>
            <Badge
              count={listData.length}
              style={{
                backgroundColor: listData.some((item) => item.type === 'success') ? '#52c41a' : '#faad14',
              }}
            />
          </div>
        )}
      </div>
    );
  };

  return (
    <Drawer
      title={
        <Space>
          <CalendarOutlined />
          Scheduled Publishing Calendar
        </Space>
      }
      open={open}
      onClose={onClose}
      placement="right"
      width={isMobile ? '100%' : 700}
      mask={false}
      destroyOnClose={false}
      styles={{
        body: {
          padding: 24,
          overflowY: 'auto'
        }
      }}
      aria-label="Scheduled publishing calendar"
    >
      <div>
        {error ? (
          <div style={{ paddingBottom: 24 }}>
            <Alert
              type="error"
              message="Failed to Load Schedules"
              description={error}
              showIcon
              action={
                <Button
                  size="small"
                  type="primary"
                  onClick={fetchSchedules}
                  icon={<ReloadOutlined />}
                >
                  Retry
                </Button>
              }
            />
          </div>
        ) : loading ? (
          <div>
            <Skeleton active paragraph={{ rows: 2 }} />
            <Skeleton.Button active block style={{ height: 400, marginTop: 16 }} />
            <Skeleton active paragraph={{ rows: 3 }} style={{ marginTop: 16 }} />
          </div>
        ) : (
          <>
            {/* Stats */}
            <div style={{ marginBottom: 16, padding: 12, background: '#f5f5f5', borderRadius: 4 }}>
              <Space size="large">
                <span>
                  <strong>Total Scheduled:</strong> {schedules.length}
                </span>
                <span>
                  <strong>Publish:</strong>{' '}
                  {schedules.filter((s) => s.action === 'publish').length}
                </span>
                <span>
                  <strong>Unpublish:</strong>{' '}
                  {schedules.filter((s) => s.action === 'unpublish').length}
                </span>
              </Space>
            </div>

            {/* Calendar */}
            <Calendar
              cellRender={cellRender}
              onSelect={setSelectedDate}
              value={selectedDate}
            />

            {/* Events for selected date */}
            <div style={{ marginTop: 16 }}>
              <h4>
                Events on {selectedDate.format('YYYY-MM-DD')} ({selectedDateEvents.length})
              </h4>
              {selectedDateEvents.length > 0 ? (
                <List
                  size="small"
                  dataSource={selectedDateEvents}
                  renderItem={(event) => (
                    <List.Item
                      actions={[
                        <Button
                          key="cancel"
                          type="text"
                          danger
                          size="small"
                          icon={<DeleteOutlined />}
                          onClick={() => handleCancelSchedule(event.videoId, event.action)}
                          aria-label={`Cancel ${event.action} schedule for ${event.videoTitle || `Video ${event.videoId}`}`}
                        >
                          Cancel
                        </Button>,
                      ]}
                    >
                      <List.Item.Meta
                        avatar={<ClockCircleOutlined style={{ fontSize: 20 }} />}
                        title={
                          <Space>
                            <span>{event.videoTitle || `Video ${event.videoId}`}</span>
                            <Tag color={event.action === 'publish' ? 'success' : 'warning'}>
                              {event.action}
                            </Tag>
                          </Space>
                        }
                        description={`Scheduled for ${dayjs(event.scheduledFor).format('HH:mm:ss')} (${event.status})`}
                      />
                    </List.Item>
                  )}
                />
              ) : (
                <Empty description="No events on this date" image={Empty.PRESENTED_IMAGE_SIMPLE} />
              )}
            </div>

            {/* Refresh button */}
            <div style={{ marginTop: 16, textAlign: 'right' }}>
              <Button
                onClick={fetchSchedules}
                loading={loading}
                icon={<ReloadOutlined />}
                aria-label="Refresh calendar"
              >
                Refresh
              </Button>
            </div>
          </>
        )}
      </div>
    </Drawer>
  );
}
