import { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { Typography, Button, Card, Result, Spin, Space, Grid, theme } from 'antd';
import { VideoCameraOutlined, ClockCircleOutlined } from '@ant-design/icons';
import axios from 'axios';
import dayjs from 'dayjs';
import { useSettingsStore } from '@/stores/settings.store';
import { useDocumentTitle } from '@/hooks/useDocumentTitle';

const { Title, Text, Paragraph } = Typography;
const apiBase = '/api';

interface MeetingJoinInfo {
  title: string;
  description: string | null;
  jitsiRoom: string;
  domain: string;
  startTime: string | null;
  endTime: string | null;
}

export default function MeetingJoinPage() {
  const { slug } = useParams<{ slug: string }>();
  const { token: themeToken } = theme.useToken();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const { settings } = useSettingsStore();

  const [meeting, setMeeting] = useState<MeetingJoinInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useDocumentTitle(
    meeting
      ? `${meeting.title} | ${settings?.organizationName || 'Changemaker'}`
      : `Meeting | ${settings?.organizationName || 'Changemaker'}`,
  );

  useEffect(() => {
    if (!slug) return;
    (async () => {
      try {
        const res = await axios.get<MeetingJoinInfo>(`${apiBase}/jitsi/meetings/${slug}/join`);
        setMeeting(res.data);
      } catch (err: unknown) {
        if (axios.isAxiosError(err) && err.response?.status === 410) {
          setError('This meeting has ended.');
        } else if (axios.isAxiosError(err) && err.response?.status === 404) {
          setError('Meeting not found.');
        } else {
          setError('Failed to load meeting information.');
        }
      } finally {
        setLoading(false);
      }
    })();
  }, [slug]);

  const handleJoin = () => {
    if (!meeting) return;
    const url = `https://${meeting.domain}/${meeting.jitsiRoom}`;
    window.open(url, '_blank', 'noopener,noreferrer');
  };

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

  if (error || !meeting) {
    return (
      <Result
        status={error?.includes('ended') ? 'info' : '404'}
        title={error?.includes('ended') ? 'Meeting Ended' : 'Meeting Not Found'}
        subTitle={error || 'This meeting does not exist.'}
        icon={<VideoCameraOutlined style={{ fontSize: 48, color: themeToken.colorTextSecondary }} />}
      />
    );
  }

  return (
    <div style={{ maxWidth: 560, margin: '40px auto', padding: isMobile ? '0 16px' : 0 }}>
      <Card
        style={{
          background: themeToken.colorBgContainer,
          borderColor: themeToken.colorBorder,
        }}
      >
        <Space direction="vertical" size="large" style={{ width: '100%', textAlign: 'center' }}>
          <VideoCameraOutlined style={{ fontSize: 48, color: themeToken.colorPrimary }} />

          <Title level={3} style={{ margin: 0 }}>
            {meeting.title}
          </Title>

          {meeting.description && (
            <Paragraph type="secondary" style={{ fontSize: 14, margin: 0 }}>
              {meeting.description}
            </Paragraph>
          )}

          {meeting.startTime && (
            <Space>
              <ClockCircleOutlined style={{ color: themeToken.colorTextSecondary }} />
              <Text type="secondary">
                {dayjs(meeting.startTime).format('MMM D, YYYY h:mm A')}
                {meeting.endTime && ` — ${dayjs(meeting.endTime).format('h:mm A')}`}
              </Text>
            </Space>
          )}

          <Button
            type="primary"
            size="large"
            icon={<VideoCameraOutlined />}
            onClick={handleJoin}
            block
          >
            Join Meeting
          </Button>

          <Text type="secondary" style={{ fontSize: 12 }}>
            You'll join as a guest. The meeting host must be present for the call to start.
          </Text>
        </Space>
      </Card>
    </div>
  );
}
