import React, { useCallback, useEffect, useState } from 'react';
import { Button, Input, Modal, Space, message } from 'antd';
import { CopyOutlined, LoadingOutlined } from '@ant-design/icons';
import { customRequest } from 'helpers/http';

interface ExportModalProps {
  open: boolean;
  workflowId: string | null;
  onClose: () => void;
}

export function ExportModal({ open, workflowId, onClose }: ExportModalProps) {
  const [url, setUrl] = useState<string>('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (open && workflowId) {
      setUrl('');
      setLoading(true);
      customRequest<{ url: string }>(
        `workflow/${workflowId}/export-token`,
        'POST',
      )
        .then((res) => setUrl(res.url))
        .catch((e: any) =>
          message.error(e?.message ?? 'Failed to generate export URL'),
        )
        .finally(() => setLoading(false));
    }
  }, [open, workflowId]);

  const handleCopy = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(url);
      message.success('URL copied to clipboard');
    } catch {
      // Fallback for older browsers
      const textarea = document.getElementById(
        'export-url-input',
      ) as HTMLTextAreaElement;
      textarea?.select();
      document.execCommand('copy');
      message.success('URL copied to clipboard');
    }
  }, [url]);

  return (
    <Modal
      title="Export Workflow"
      open={open}
      onCancel={onClose}
      footer={
        <Space>
          <Button onClick={onClose}>Close</Button>
          <Button
            type="primary"
            icon={<CopyOutlined />}
            onClick={handleCopy}
            disabled={!url}
          >
            Copy URL
          </Button>
        </Space>
      }
    >
      {loading ? (
        <div style={{ textAlign: 'center', padding: 24 }}>
          <LoadingOutlined style={{ fontSize: 24 }} />
          <p>Generating export URL...</p>
        </div>
      ) : (
        <>
          <p style={{ marginBottom: 8, color: '#666' }}>
            Export URL (valid for 30 minutes):
          </p>
          <Input.TextArea
            id="export-url-input"
            value={url}
            readOnly
            autoSize={{ minRows: 3, maxRows: 5 }}
            onFocus={(e) => e.target.select()}
          />
        </>
      )}
    </Modal>
  );
}
