import { useState, useEffect } from 'react';
import { Modal, Button, Typography, Spin, Result, message, Space } from 'antd';
import { VideoCameraOutlined, CopyOutlined, LoginOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import { getErrorMessage } from '@/utils/getErrorMessage';

const { Text, Paragraph } = Typography;

interface VideoCallModalProps {
  open: boolean;
  onClose: () => void;
  personName: string;
}

interface CreatedMeeting {
  id: string;
  slug: string;
  title: string;
  jitsiRoom: string;
}

export default function VideoCallModal({ open, onClose, personName }: VideoCallModalProps) {
  const [creating, setCreating] = useState(false);
  const [meeting, setMeeting] = useState<CreatedMeeting | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [joining, setJoining] = useState(false);

  useEffect(() => {
    if (!open) return;
    setCreating(true);
    setMeeting(null);
    setError(null);

    api.post<CreatedMeeting>('/jitsi/meetings', {
      title: `Call with ${personName}`,
    })
      .then(({ data }) => setMeeting(data))
      .catch((err) => {
        setError(err.response?.data?.error || 'Failed to create meeting');
      })
      .finally(() => setCreating(false));
  }, [open, personName]);

  const guestLink = meeting ? `${window.location.origin}/meet/${meeting.slug}` : '';

  const handleCopyLink = () => {
    navigator.clipboard.writeText(guestLink).then(
      () => message.success('Guest link copied'),
      () => message.error('Failed to copy'),
    );
  };

  const handleJoinAsHost = async () => {
    if (!meeting) return;
    setJoining(true);
    try {
      const { data } = await api.post<{ token: string; jitsiRoom: string; domain: string }>(
        `/jitsi/meetings/${meeting.slug}/token`,
      );
      window.open(`https://${data.domain}/${data.jitsiRoom}?jwt=${data.token}`, '_blank', 'noopener,noreferrer');
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to get moderator token'));
    } finally {
      setJoining(false);
    }
  };

  return (
    <Modal
      title={<><VideoCameraOutlined style={{ marginRight: 8 }} />Video Call</>}
      open={open}
      onCancel={onClose}
      footer={null}
      width={440}
      destroyOnClose
    >
      {creating ? (
        <div style={{ textAlign: 'center', padding: 32 }}>
          <Spin size="large" />
          <div style={{ marginTop: 12 }}>
            <Text type="secondary">Creating meeting room...</Text>
          </div>
        </div>
      ) : error ? (
        <Result
          status="error"
          title="Could not create meeting"
          subTitle={error}
          extra={<Button onClick={onClose}>Close</Button>}
        />
      ) : meeting ? (
        <div>
          <Text type="secondary" style={{ display: 'block', marginBottom: 16 }}>
            Share the guest link below with <Text strong>{personName}</Text> to invite them to the call.
          </Text>

          <div style={{
            padding: '12px 16px',
            background: 'rgba(255,255,255,0.04)',
            borderRadius: 8,
            border: '1px solid rgba(255,255,255,0.08)',
            marginBottom: 16,
          }}>
            <Text type="secondary" style={{ fontSize: 12, display: 'block', marginBottom: 4 }}>Guest Join Link</Text>
            <Paragraph
              copyable={{ text: guestLink, tooltips: ['Copy', 'Copied'] }}
              style={{ margin: 0, fontSize: 13, wordBreak: 'break-all' }}
            >
              {guestLink}
            </Paragraph>
          </div>

          <Space style={{ width: '100%' }} direction="vertical" size={8}>
            <Button
              type="primary"
              icon={<LoginOutlined />}
              block
              loading={joining}
              onClick={handleJoinAsHost}
            >
              Join as Host
            </Button>
            <Button
              icon={<CopyOutlined />}
              block
              onClick={handleCopyLink}
            >
              Copy Guest Link
            </Button>
          </Space>
        </div>
      ) : null}
    </Modal>
  );
}
