import { useState, useEffect, useCallback } from 'react';
import { Card, Typography, Spin, Flex, Button, Tag, Tooltip, Progress } from 'antd';
import {
  ScheduleOutlined,
  ReloadOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import type { DashboardUpcomingShiftsResult, DashboardUpcomingShift } from '@/types/api';

const { Text } = Typography;

function ShiftRow({ shift }: { shift: DashboardUpcomingShift }) {
  const navigate = useNavigate();
  const fillPct = shift.maxVolunteers > 0
    ? Math.round((shift.currentVolunteers / shift.maxVolunteers) * 100) : 0;

  return (
    <Flex
      align="center"
      gap={8}
      onClick={() => navigate('/app/map/shifts')}
      style={{
        padding: '5px 0',
        borderBottom: '1px solid rgba(255,255,255,0.04)',
        lineHeight: 1.4,
        cursor: 'pointer',
      }}
    >
      <Text type="secondary" style={{ fontSize: 12, flexShrink: 0, width: 50, whiteSpace: 'nowrap' }}>
        {dayjs(shift.date).format('MMM D')}
      </Text>
      <Tooltip title={shift.title}>
        <Text
          strong
          style={{ fontSize: 13, flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
        >
          {shift.title}
        </Text>
      </Tooltip>
      <Text type="secondary" style={{ fontSize: 11, flexShrink: 0 }}>
        <ClockCircleOutlined style={{ marginRight: 2, fontSize: 10 }} />
        {shift.startTime}
      </Text>
      <Tooltip title={`${shift.currentVolunteers}/${shift.maxVolunteers} volunteers`}>
        <Progress
          percent={fillPct}
          size="small"
          style={{ width: 50, flexShrink: 0 }}
          strokeColor={fillPct >= 100 ? '#52c41a' : fillPct >= 50 ? '#faad14' : '#1890ff'}
          showInfo={false}
        />
      </Tooltip>
      {shift.cutName && (
        <Tag style={{ fontSize: 10, margin: 0, padding: '0 4px', lineHeight: '18px', flexShrink: 0, maxWidth: 70, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {shift.cutName}
        </Tag>
      )}
    </Flex>
  );
}

export default function UpcomingShiftsCard() {
  const navigate = useNavigate();
  const [result, setResult] = useState<DashboardUpcomingShiftsResult | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchShifts = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get<DashboardUpcomingShiftsResult>('/dashboard/upcoming-shifts');
      setResult(res.data);
    } catch {
      // non-critical widget
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchShifts();
    const interval = setInterval(fetchShifts, 5 * 60_000);
    return () => clearInterval(interval);
  }, [fetchShifts]);

  return (
    <Card
      title={<span style={{ fontSize: 14 }}><ScheduleOutlined style={{ marginRight: 6, fontSize: 15 }} />Upcoming Shifts</span>}
      size="small"
      extra={
        <Flex align="center" gap={6}>
          {result && result.total > 5 && (
            <Button type="link" size="small" onClick={() => navigate('/app/map/shifts')} style={{ fontSize: 12, padding: 0 }}>
              +{result.total - 5} more
            </Button>
          )}
          <Button type="text" size="small" icon={<ReloadOutlined spin={loading} style={{ fontSize: 13 }} />} onClick={fetchShifts} />
        </Flex>
      }
      styles={{ body: { padding: '6px 14px 8px' } }}
    >
      {loading && !result ? (
        <div style={{ textAlign: 'center', padding: 12 }}><Spin size="small" /></div>
      ) : result && result.shifts.length > 0 ? (
        <div>
          {result.shifts.map(shift => (
            <ShiftRow key={shift.id} shift={shift} />
          ))}
        </div>
      ) : (
        <Text type="secondary" style={{ fontSize: 13, display: 'block', padding: '8px 0' }}>No upcoming shifts</Text>
      )}
    </Card>
  );
}
