import React, { useState } from 'react';
import { Modal, Form, Input, Button, Alert, Grid } from 'antd';
import { VideoPickerModal } from '../media/VideoPickerModal';
import type { Video } from '../media/VideoPickerModal';

interface VideoVariableEditorProps {
  open: boolean;
  onClose: () => void;
  onSave: (variable: {
    key: string;
    label: string;
    description: string;
    videoId: number;
    type: 'VIDEO';
  }) => void;
  existingKeys: string[];
}

export const VideoVariableEditor: React.FC<VideoVariableEditorProps> = ({
  open,
  onClose,
  onSave,
  existingKeys,
}) => {
  const [form] = Form.useForm();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [selectedVideo, setSelectedVideo] = useState<Video | null>(null);
  const [showVideoPicker, setShowVideoPicker] = useState(false);

  const handleSave = async () => {
    try {
      const values = await form.validateFields();

      if (!selectedVideo) {
        Modal.error({ content: 'Please select a video' });
        return;
      }

      onSave({
        key: values.key.toUpperCase().replace(/\s+/g, '_'),
        label: values.label,
        description: values.description || '',
        videoId: selectedVideo.id,
        type: 'VIDEO',
      });

      form.resetFields();
      setSelectedVideo(null);
      onClose();
    } catch (err) {
      console.error('Validation failed:', err);
    }
  };

  const handleVideoSelect = (video: Video) => {
    setSelectedVideo(video);

    // Auto-fill label if empty
    const currentLabel = form.getFieldValue('label');
    if (!currentLabel) {
      form.setFieldsValue({ label: video.title });
    }

    // Auto-generate key if empty
    const currentKey = form.getFieldValue('key');
    if (!currentKey) {
      const generatedKey = video.title
        .toUpperCase()
        .replace(/[^A-Z0-9]+/g, '_')
        .replace(/^_+|_+$/g, '');
      form.setFieldsValue({ key: generatedKey });
    }
  };

  return (
    <>
      <Modal
        open={open}
        onCancel={onClose}
        title="Add Video Variable"
        width={isMobile ? '95vw' : 600}
        footer={[
          <Button key="cancel" onClick={onClose}>
            Cancel
          </Button>,
          <Button key="save" type="primary" onClick={handleSave}>
            Add Variable
          </Button>,
        ]}
      >
        <Alert
          message="Video Variables in Emails"
          description="Videos will be displayed as thumbnail images with play buttons that link to the video player. Most email clients don't support embedded video playback."
          type="info"
          style={{ marginBottom: 16 }}
        />

        <Form form={form} layout="vertical">
          {/* Video Selection */}
          <Form.Item label="Select Video">
            {selectedVideo ? (
              <div
                style={{
                  padding: 12,
                  border: '1px solid #d9d9d9',
                  borderRadius: 8,
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                }}
              >
                <span>
                  <strong>{selectedVideo.title}</strong>
                  <br />
                  <small style={{ color: '#999' }}>
                    ID: {selectedVideo.id} • {selectedVideo.orientation === 'H' ? 'Horizontal' : 'Vertical'}
                  </small>
                </span>
                <Button onClick={() => setShowVideoPicker(true)}>Change</Button>
              </div>
            ) : (
              <Button block onClick={() => setShowVideoPicker(true)}>
                Choose Video from Library
              </Button>
            )}
          </Form.Item>

          {/* Variable Key */}
          <Form.Item
            name="key"
            label="Variable Key"
            rules={[
              { required: true, message: 'Please enter a variable key' },
              {
                pattern: /^[A-Z_]+$/,
                message: 'Key must be uppercase letters and underscores only',
              },
              {
                validator: (_, value) => {
                  if (value && existingKeys.includes(value.toUpperCase())) {
                    return Promise.reject('This key already exists');
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <Input placeholder="VIDEO_INTRO" />
          </Form.Item>

          {/* Variable Label */}
          <Form.Item
            name="label"
            label="Display Label"
            rules={[{ required: true, message: 'Please enter a label' }]}
          >
            <Input placeholder="Introduction Video" />
          </Form.Item>

          {/* Description */}
          <Form.Item name="description" label="Description (Optional)">
            <Input.TextArea
              rows={2}
              placeholder="Video explaining the campaign goals..."
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* Video Picker Modal */}
      <VideoPickerModal
        open={showVideoPicker}
        onClose={() => setShowVideoPicker(false)}
        onSelect={handleVideoSelect}
        mode="single"
      />
    </>
  );
};
