import React, { useCallback, useState } from 'react';
import { Button, Input, Modal, Space, Spin, message } from 'antd';
import { CloudDownloadOutlined, CheckOutlined } from '@ant-design/icons';
import ReactDiffViewer, { DiffMethod } from 'react-diff-viewer-continued';
import { customRequest } from 'helpers/http';

interface ImportModalProps {
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

type Phase = 'input' | 'preview' | 'confirming';

export function ImportModal({ open, onClose, onSuccess }: ImportModalProps) {
  const [sourceUrl, setSourceUrl] = useState('');
  const [phase, setPhase] = useState<Phase>('input');
  const [loading, setLoading] = useState(false);
  const [currentJson, setCurrentJson] = useState('');
  const [incomingJson, setIncomingJson] = useState('');
  const [payload, setPayload] = useState<any>(null);

  const reset = useCallback(() => {
    setSourceUrl('');
    setPhase('input');
    setLoading(false);
    setCurrentJson('');
    setIncomingJson('');
    setPayload(null);
  }, []);

  const handleClose = useCallback(() => {
    reset();
    onClose();
  }, [reset, onClose]);

  const handleFetchPreview = useCallback(async () => {
    if (!sourceUrl.trim()) {
      message.warning('Please paste the export URL');
      return;
    }

    setLoading(true);
    try {
      // Step 1: Fetch from source URL (cross-origin)
      const response = await fetch(sourceUrl.trim());
      if (!response.ok) {
        const errorData = await response.json().catch(() => null);
        throw new Error(
          errorData?.message || `Failed to fetch: ${response.status}`,
        );
      }
      const exportData = await response.json();

      // Step 2: Send to our import-preview endpoint
      const preview = await customRequest<{
        current: any;
        incoming: any;
      }>('workflow/import-preview', 'POST', { payload: exportData });

      // Step 3: Format for diff viewer
      setCurrentJson(
        preview.current ? JSON.stringify(preview.current, null, 2) : '',
      );
      setIncomingJson(JSON.stringify(preview.incoming, null, 2));
      setPayload(exportData);
      setPhase('preview');
    } catch (e: any) {
      if (e.message?.includes('expired') || e.message?.includes('invalid')) {
        message.error(
          'Export link has expired or is invalid. Please generate a new one from the source environment.',
        );
      } else {
        message.error(
          e?.message ||
            'Cannot reach the source environment. Please check the URL and try again.',
        );
      }
    } finally {
      setLoading(false);
    }
  }, [sourceUrl]);

  const handleConfirm = useCallback(async () => {
    if (!payload) return;
    setPhase('confirming');
    try {
      const result = await customRequest<{
        success: boolean;
        workflowId: string;
        workflowName: string;
      }>('workflow/import-confirm', 'POST', { payload });

      message.success(
        `Workflow "${result.workflowName}" imported successfully!`,
      );
      reset();
      onClose();
      onSuccess();
    } catch (e: any) {
      message.error(e?.message ?? 'Import failed');
      setPhase('preview');
    }
  }, [payload, reset, onClose, onSuccess]);

  return (
    <Modal
      title="Import Workflow"
      open={open}
      onCancel={handleClose}
      width={phase === 'preview' ? '90vw' : 520}
      footer={
        phase === 'input' ? (
          <Space>
            <Button onClick={handleClose}>Cancel</Button>
            <Button
              type="primary"
              icon={<CloudDownloadOutlined />}
              onClick={handleFetchPreview}
              loading={loading}
            >
              Fetch &amp; Preview
            </Button>
          </Space>
        ) : (
          <Space>
            <Button onClick={handleClose}>Cancel</Button>
            <Button
              type="primary"
              icon={<CheckOutlined />}
              onClick={handleConfirm}
              loading={phase === 'confirming'}
            >
              Confirm Import
            </Button>
          </Space>
        )
      }
    >
      {phase === 'input' && (
        <>
          <p style={{ marginBottom: 8 }}>
            Paste the export URL from the source environment:
          </p>
          <Input.TextArea
            value={sourceUrl}
            onChange={(e) => setSourceUrl(e.target.value)}
            placeholder="https://dev.example.com/api/workflow/export/abc123?token=..."
            autoSize={{ minRows: 3, maxRows: 5 }}
          />
        </>
      )}

      {phase === 'preview' && (
        <div style={{ maxHeight: '70vh', overflow: 'auto' }}>
          <ReactDiffViewer
            oldValue={currentJson}
            newValue={incomingJson}
            splitView
            compareMethod={DiffMethod.LINES}
            leftTitle="Current (this environment)"
            rightTitle="Incoming (source environment)"
          />
        </div>
      )}

      {phase === 'confirming' && (
        <div style={{ textAlign: 'center', padding: 40 }}>
          <Spin size="large" />
          <p style={{ marginTop: 16 }}>Importing workflow...</p>
        </div>
      )}
    </Modal>
  );
}
