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

const { Text } = Typography;

interface Meeting {
  id: string;
  slug: string;
  title: string;
  isActive: boolean;
  startTime: string | null;
  endTime: string | null;
  createdAt: string;
}

function getStatusTag(meeting: Meeting) {
  if (!meeting.isActive) {
    return <Tag style={{ margin: 0, fontSize: 10, padding: '0 4px', lineHeight: '18px' }}>Ended</Tag>;
  }
  if (meeting.startTime && dayjs(meeting.startTime).isAfter(dayjs())) {
    return <Tag color="blue" style={{ margin: 0, fontSize: 10, padding: '0 4px', lineHeight: '18px' }}>Scheduled</Tag>;
  }
  return <Tag color="green" style={{ margin: 0, fontSize: 10, padding: '0 4px', lineHeight: '18px' }}>Live</Tag>;
}

function MeetingRow({ meeting }: { meeting: Meeting }) {
  const timeLabel = meeting.startTime
    ? dayjs(meeting.startTime).format('MMM D, h:mm A')
    : dayjs(meeting.createdAt).format('MMM D');

  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: 80, whiteSpace: 'nowrap' }}>
        <ClockCircleOutlined style={{ marginRight: 2, fontSize: 10 }} />
        {timeLabel}
      </Text>
      <Tooltip title={meeting.title}>
        <Text
          strong
          style={{ fontSize: 13, flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
        >
          {meeting.title}
        </Text>
      </Tooltip>
      {getStatusTag(meeting)}
      {meeting.isActive && (
        <Tooltip title="Join meeting">
          <Button
            type="link"
            size="small"
            icon={<LoginOutlined style={{ fontSize: 12 }} />}
            href={`/meet/${meeting.slug}`}
            target="_blank"
            style={{ padding: 0, height: 'auto', lineHeight: 1 }}
          />
        </Tooltip>
      )}
    </Flex>
  );
}

export default function UpcomingMeetingsCard() {
  const navigate = useNavigate();
  const [meetings, setMeetings] = useState<Meeting[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);

  const fetchMeetings = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get<{ meetings: Meeting[] }>('/jitsi/meetings');
      const all = res.data.meetings || [];
      // Show active meetings first (sorted by startTime), then recently ended
      const active = all
        .filter((m) => m.isActive)
        .sort((a, b) => {
          if (a.startTime && b.startTime) return new Date(a.startTime).getTime() - new Date(b.startTime).getTime();
          return 0;
        });
      setTotal(active.length);
      setMeetings(active.slice(0, 5));
    } catch {
      // non-critical widget
    } finally {
      setLoading(false);
    }
  }, []);

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

  return (
    <Card
      title={<span style={{ fontSize: 14 }}><VideoCameraOutlined style={{ marginRight: 6, fontSize: 15 }} />Upcoming Meetings</span>}
      size="small"
      extra={
        <Flex align="center" gap={6}>
          {total > 5 && (
            <Button type="link" size="small" onClick={() => navigate('/app/services/jitsi')} style={{ fontSize: 12, padding: 0 }}>
              +{total - 5} more
            </Button>
          )}
          <Button
            type="text"
            size="small"
            onClick={() => navigate('/app/services/jitsi')}
            style={{ fontSize: 12, padding: '0 4px' }}
          >
            View All
          </Button>
          <Button type="text" size="small" icon={<ReloadOutlined spin={loading} style={{ fontSize: 13 }} />} onClick={fetchMeetings} />
        </Flex>
      }
      styles={{ body: { padding: '6px 14px 8px' } }}
    >
      {loading && meetings.length === 0 ? (
        <div style={{ textAlign: 'center', padding: 12 }}><Spin size="small" /></div>
      ) : meetings.length > 0 ? (
        <div>
          {meetings.map((meeting) => (
            <MeetingRow key={meeting.id} meeting={meeting} />
          ))}
        </div>
      ) : (
        <Text type="secondary" style={{ fontSize: 13, display: 'block', padding: '8px 0' }}>No upcoming meetings</Text>
      )}
    </Card>
  );
}
