import { useState, useEffect, useCallback } from 'react';
import { Card, Typography, Spin, Tag, Flex, Tooltip, Button } from 'antd';
import {
  CalendarOutlined,
  ClockCircleOutlined,
  EnvironmentOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import type { TodayEventsResult, TodayEvent } from '@/types/api';

const { Text } = Typography;

function formatTime(iso: string): string {
  return dayjs(iso).format('h:mm A');
}

function EventRow({ event }: { event: TodayEvent }) {
  const start = formatTime(event.startTime);
  const end = event.endTime ? formatTime(event.endTime) : null;
  const timeStr = end ? `${start}-${end}` : start;

  return (
    <Flex
      align="center"
      gap={8}
      style={{
        padding: '5px 0',
        borderBottom: '1px solid rgba(255,255,255,0.04)',
        lineHeight: 1.4,
      }}
    >
      <Text type="secondary" style={{ fontSize: 12, flexShrink: 0, width: 90, whiteSpace: 'nowrap' }}>
        <ClockCircleOutlined style={{ marginRight: 4, fontSize: 11 }} />
        {timeStr}
      </Text>
      <Text strong style={{ fontSize: 13, flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
        {event.title}
      </Text>
      {event.placeName && (
        <Tooltip title={event.placeName}>
          <Text type="secondary" style={{ fontSize: 12, flexShrink: 0, maxWidth: 120, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            <EnvironmentOutlined style={{ marginRight: 3, fontSize: 11 }} />
            {event.placeName}
          </Text>
        </Tooltip>
      )}
      {event.tags.length > 0 && (
        <Tag style={{ fontSize: 11, margin: 0, padding: '0 4px', lineHeight: '18px', flexShrink: 0 }}>
          {event.tags[0]}
        </Tag>
      )}
    </Flex>
  );
}

export default function TodayEventsCard() {
  const [result, setResult] = useState<TodayEventsResult | null>(null);
  const [loading, setLoading] = useState(true);

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

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

  if (result && !result.enabled) return null;

  return (
    <Card
      title={<span style={{ fontSize: 14 }}><CalendarOutlined style={{ marginRight: 6, fontSize: 15 }} />Today's Events</span>}
      size="small"
      extra={
        <Flex align="center" gap={6}>
          {result && <Text type="secondary" style={{ fontSize: 12 }}>{result.total} event{result.total !== 1 ? 's' : ''}</Text>}
          <Button type="text" size="small" icon={<ReloadOutlined spin={loading} style={{ fontSize: 13 }} />} onClick={fetchEvents} />
        </Flex>
      }
      styles={{ body: { padding: '6px 14px 8px' } }}
    >
      {loading && !result ? (
        <div style={{ textAlign: 'center', padding: 12 }}><Spin size="small" /></div>
      ) : result && result.events.length > 0 ? (
        <>
          {result.events.map(event => (
            <EventRow key={event.id} event={event} />
          ))}
        </>
      ) : (
        <Text type="secondary" style={{ fontSize: 13, display: 'block', padding: '8px 0' }}>No events scheduled today</Text>
      )}
    </Card>
  );
}
