import {
  useState,
  useEffect,
  Card,
  Tabs,
  Form,
  Input,
  Select,
  Button,
  Space,
  Upload,
  message,
  Progress,
  Table,
  Tag,
  Image,
  Modal,
  Row,
  Col,
  Alert,
  Divider,
  InputNumber,
  Switch,
  Tooltip,
  Badge,
  PictureOutlined,
  VideoCameraOutlined,
  TranslationOutlined,
  SoundOutlined,
  UploadOutlined,
  PlayCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SyncOutlined,
  DownloadOutlined,
  EyeOutlined,
  DeleteOutlined,
  InfoCircleOutlined,
  Option,
  TextArea,
  FC,
} from '@/imports';
import {
  materialProcessingDataSource,
  MaterialProcessJob,
  ImageToImageParams,
  ImageToVideoParams,
  VideoTranslationParams,
  VideoDubbingParams,
  TRANSLATION_LANGUAGES,
  STYLE_OPTIONS,
  MOTION_OPTIONS,
  TranslationLanguage,
} from '@/services/materialProcessingDataSource';

const JOB_TYPE_NAMES: Record<string, string> = {
  image_to_image: '图生图',
  image_to_video: '图生视频',
  video_translation: '视频翻译',
  video_dubbing: '视频配音',
};

const STATUS_CONFIG: Record<string, { color: string; icon: React.ReactNode }> = {
  pending: { color: 'default', icon: <SyncOutlined spin /> },
  processing: { color: 'processing', icon: <SyncOutlined spin /> },
  completed: { color: 'success', icon: <CheckCircleOutlined /> },
  failed: { color: 'error', icon: <CloseCircleOutlined /> },
};

const MaterialProcessing: FC = () => {
  const [activeTab, setActiveTab] = useState('image-to-image');
  const [jobs, setJobs] = useState<MaterialProcessJob[]>([]);
  const [loading, setLoading] = useState(false);
  const [inputUrl, setInputUrl] = useState('');
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewJob, setPreviewJob] = useState<MaterialProcessJob | null>(null);
  
  const [imageToImageForm] = Form.useForm();
  const [imageToVideoForm] = Form.useForm();
  const [videoTranslationForm] = Form.useForm();
  const [videoDubbingForm] = Form.useForm();

  useEffect(() => {
    fetchJobs();
    const interval = setInterval(fetchJobs, 3000);
    return () => clearInterval(interval);
  }, []);

  const fetchJobs = async () => {
    try {
      const data = await materialProcessingDataSource.getJobs();
      setJobs(data);
    } catch (error) {
      console.error('Failed to fetch jobs:', error);
    }
  };

  const handleImageToImage = async (values: ImageToImageParams) => {
    if (!inputUrl) {
      message.warning('请先上传图片或输入图片URL');
      return;
    }
    
    setLoading(true);
    try {
      const job = await materialProcessingDataSource.imageToImage(inputUrl, values);
      message.success(`任务已创建: ${job.id}`);
      imageToImageForm.resetFields();
      fetchJobs();
    } catch (error) {
      message.error('创建任务失败');
    } finally {
      setLoading(false);
    }
  };

  const handleImageToVideo = async (values: ImageToVideoParams) => {
    if (!inputUrl) {
      message.warning('请先上传图片或输入图片URL');
      return;
    }
    
    setLoading(true);
    try {
      const job = await materialProcessingDataSource.imageToVideo(inputUrl, values);
      message.success(`任务已创建: ${job.id}`);
      imageToVideoForm.resetFields();
      fetchJobs();
    } catch (error) {
      message.error('创建任务失败');
    } finally {
      setLoading(false);
    }
  };

  const handleVideoTranslation = async (values: VideoTranslationParams) => {
    if (!inputUrl) {
      message.warning('请先上传视频或输入视频URL');
      return;
    }
    
    setLoading(true);
    try {
      const job = await materialProcessingDataSource.translateVideo(inputUrl, values);
      message.success(`任务已创建: ${job.id}`);
      videoTranslationForm.resetFields();
      fetchJobs();
    } catch (error) {
      message.error('创建任务失败');
    } finally {
      setLoading(false);
    }
  };

  const handleVideoDubbing = async (values: VideoDubbingParams) => {
    if (!inputUrl) {
      message.warning('请先上传视频或输入视频URL');
      return;
    }
    
    setLoading(true);
    try {
      const job = await materialProcessingDataSource.dubVideo(inputUrl, values);
      message.success(`任务已创建: ${job.id}`);
      videoDubbingForm.resetFields();
      fetchJobs();
    } catch (error) {
      message.error('创建任务失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCancelJob = async (jobId: string) => {
    try {
      await materialProcessingDataSource.cancelJob(jobId);
      message.success('任务已取消');
      fetchJobs();
    } catch (error) {
      message.error('取消任务失败');
    }
  };

  const handlePreview = (job: MaterialProcessJob) => {
    setPreviewJob(job);
    setPreviewVisible(true);
  };

  const handleDownload = (job: MaterialProcessJob) => {
    if (job.outputUrl) {
      window.open(job.outputUrl, '_blank');
    }
  };

  const jobColumns = [
    {
      title: '任务ID',
      dataIndex: 'id',
      key: 'id',
      width: 180,
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (type: string) => <Tag color="blue">{JOB_TYPE_NAMES[type]}</Tag>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 150,
      render: (status: string, record: MaterialProcessJob) => (
        <Space direction="vertical" size={0} style={{ width: '100%' }}>
          <Tag color={STATUS_CONFIG[status].color} icon={STATUS_CONFIG[status].icon}>
            {status.toUpperCase()}
          </Tag>
          {status === 'processing' && (
            <Progress percent={record.progress} size="small" />
          )}
        </Space>
      ),
    },
    {
      title: '输入',
      dataIndex: 'inputUrl',
      key: 'inputUrl',
      ellipsis: true,
      render: (url: string) => (
        <Tooltip title={url}>
          <a href={url} target="_blank" rel="noopener noreferrer">
            {url.substring(0, 50)}...
          </a>
        </Tooltip>
      ),
    },
    {
      title: '输出',
      dataIndex: 'outputUrl',
      key: 'outputUrl',
      ellipsis: true,
      render: (url: string) => url ? (
        <Tooltip title={url}>
          <a href={url} target="_blank" rel="noopener noreferrer">
            {url.substring(0, 50)}...
          </a>
        </Tooltip>
      ) : '-',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
    },
    {
      title: '操作',
      key: 'actions',
      width: 150,
      render: (_: any, record: MaterialProcessJob) => (
        <Space>
          {record.status === 'completed' && (
            <>
              <Tooltip title="预览">
                <Button 
                  type="text" 
                  icon={<EyeOutlined />} 
                  onClick={() => handlePreview(record)}
                />
              </Tooltip>
              <Tooltip title="下载">
                <Button 
                  type="text" 
                  icon={<DownloadOutlined />} 
                  onClick={() => handleDownload(record)}
                />
              </Tooltip>
            </>
          )}
          {record.status === 'processing' && (
            <Tooltip title="取消">
              <Button 
                type="text" 
                danger 
                icon={<CloseCircleOutlined />} 
                onClick={() => handleCancelJob(record.id)}
              />
            </Tooltip>
          )}
        </Space>
      ),
    },
  ];

  const renderImageToImage = () => (
    <Card title="图生图" extra={<Tag color="blue">AI图像生成</Tag>}>
      <Alert
        message="功能说明"
        description="基于输入图片，使用AI生成新的图片。支持多种风格转换，如写实、艺术、动漫等。"
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
      />
      
      <Form form={imageToImageForm} layout="vertical" onFinish={handleImageToImage}>
        <Form.Item label="输入图片">
          <Space.Compact style={{ width: '100%' }}>
            <Input 
              placeholder="输入图片URL" 
              value={inputUrl} 
              onChange={e => setInputUrl(e.target.value)}
            />
            <Upload
              accept="image/*"
              showUploadList={false}
              beforeUpload={(file) => {
                const url = URL.createObjectURL(file);
                setInputUrl(url);
                return false;
              }}
            >
              <Button icon={<UploadOutlined />}>上传</Button>
            </Upload>
          </Space.Compact>
        </Form.Item>

        {inputUrl && (
          <Form.Item label="预览">
            <Image src={inputUrl} width={200} style={{ borderRadius: 8 }} />
          </Form.Item>
        )}

        <Form.Item name="prompt" label="提示词">
          <TextArea 
            rows={3} 
            placeholder="描述你想要生成的图片效果，例如：将产品图片转换为白色背景..."
          />
        </Form.Item>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item name="style" label="风格" initialValue="realistic">
              <Select>
                {STYLE_OPTIONS.map(opt => (
                  <Option key={opt.value} value={opt.value}>{opt.label}</Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item 
              name="strength" 
              label="转换强度" 
              initialValue={0.7}
              tooltip="值越大，生成的图片与原图差异越大"
            >
              <InputNumber min={0} max={1} step={0.1} style={{ width: '100%' }} />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item>
          <Button type="primary" htmlType="submit" loading={loading} icon={<PictureOutlined />}>
            开始生成
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );

  const renderImageToVideo = () => (
    <Card title="图生视频" extra={<Tag color="purple">AI视频生成</Tag>}>
      <Alert
        message="功能说明"
        description="将静态图片转换为动态视频。支持多种运动效果，如缩放、平移、旋转等。"
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
      />
      
      <Form form={imageToVideoForm} layout="vertical" onFinish={handleImageToVideo}>
        <Form.Item label="输入图片">
          <Space.Compact style={{ width: '100%' }}>
            <Input 
              placeholder="输入图片URL" 
              value={inputUrl} 
              onChange={e => setInputUrl(e.target.value)}
            />
            <Upload
              accept="image/*"
              showUploadList={false}
              beforeUpload={(file) => {
                const url = URL.createObjectURL(file);
                setInputUrl(url);
                return false;
              }}
            >
              <Button icon={<UploadOutlined />}>上传</Button>
            </Upload>
          </Space.Compact>
        </Form.Item>

        {inputUrl && (
          <Form.Item label="预览">
            <Image src={inputUrl} width={200} style={{ borderRadius: 8 }} />
          </Form.Item>
        )}

        <Form.Item name="prompt" label="提示词">
          <TextArea 
            rows={2} 
            placeholder="描述视频的运动效果，例如：缓慢放大产品特写..."
          />
        </Form.Item>

        <Row gutter={16}>
          <Col span={8}>
            <Form.Item name="motion" label="运动类型" initialValue="zoom">
              <Select>
                {MOTION_OPTIONS.map(opt => (
                  <Option key={opt.value} value={opt.value}>{opt.label}</Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item name="duration" label="时长(秒)" initialValue={5}>
              <InputNumber min={1} max={30} style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item name="fps" label="帧率" initialValue={30}>
              <Select>
                <Option value={24}>24 FPS</Option>
                <Option value={30}>30 FPS</Option>
                <Option value={60}>60 FPS</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Form.Item>
          <Button type="primary" htmlType="submit" loading={loading} icon={<VideoCameraOutlined />}>
            开始生成
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );

  const renderVideoTranslation = () => (
    <Card title="视频翻译" extra={<Tag color="green">AI翻译配音</Tag>}>
      <Alert
        message="功能说明"
        description="自动识别视频中的语音，翻译为目标语言，并合成新的配音。支持保留背景音效。"
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
      />
      
      <Form form={videoTranslationForm} layout="vertical" onFinish={handleVideoTranslation}>
        <Form.Item label="输入视频">
          <Space.Compact style={{ width: '100%' }}>
            <Input 
              placeholder="输入视频URL" 
              value={inputUrl} 
              onChange={e => setInputUrl(e.target.value)}
            />
            <Upload
              accept="video/*"
              showUploadList={false}
              beforeUpload={(file) => {
                const url = URL.createObjectURL(file);
                setInputUrl(url);
                return false;
              }}
            >
              <Button icon={<UploadOutlined />}>上传</Button>
            </Upload>
          </Space.Compact>
        </Form.Item>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item 
              name="sourceLanguage" 
              label="源语言" 
              initialValue="auto"
              tooltip="选择'自动检测'将自动识别视频中的语言"
            >
              <Select>
                <Option value="auto">自动检测</Option>
                {Object.entries(TRANSLATION_LANGUAGES).map(([code, name]) => (
                  <Option key={code} value={code}>{name}</Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item 
              name="targetLanguage" 
              label="目标语言" 
              initialValue="en"
              rules={[{ required: true, message: '请选择目标语言' }]}
            >
              <Select>
                {Object.entries(TRANSLATION_LANGUAGES).map(([code, name]) => (
                  <Option key={code} value={code}>{name}</Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item name="voiceType" label="配音声音" initialValue="neutral">
              <Select>
                <Option value="male">男声</Option>
                <Option value="female">女声</Option>
                <Option value="neutral">中性</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item 
              name="preserveBackgroundAudio" 
              label="保留背景音" 
              valuePropName="checked" 
              initialValue={true}
            >
              <Switch />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item>
          <Button type="primary" htmlType="submit" loading={loading} icon={<TranslationOutlined />}>
            开始翻译
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );

  const renderVideoDubbing = () => (
    <Card title="视频配音" extra={<Tag color="orange">AI配音合成</Tag>}>
      <Alert
        message="功能说明"
        description="为视频添加指定语言的配音。支持口型同步功能，使配音更自然。"
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
      />
      
      <Form form={videoDubbingForm} layout="vertical" onFinish={handleVideoDubbing}>
        <Form.Item label="输入视频">
          <Space.Compact style={{ width: '100%' }}>
            <Input 
              placeholder="输入视频URL" 
              value={inputUrl} 
              onChange={e => setInputUrl(e.target.value)}
            />
            <Upload
              accept="video/*"
              showUploadList={false}
              beforeUpload={(file) => {
                const url = URL.createObjectURL(file);
                setInputUrl(url);
                return false;
              }}
            >
              <Button icon={<UploadOutlined />}>上传</Button>
            </Upload>
          </Space.Compact>
        </Form.Item>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item 
              name="targetLanguage" 
              label="配音语言" 
              initialValue="en"
              rules={[{ required: true, message: '请选择配音语言' }]}
            >
              <Select>
                {Object.entries(TRANSLATION_LANGUAGES).map(([code, name]) => (
                  <Option key={code} value={code}>{name}</Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item name="voiceType" label="配音声音" initialValue="neutral">
              <Select>
                <Option value="male">男声</Option>
                <Option value="female">女声</Option>
                <Option value="neutral">中性</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Form.Item 
          name="syncLips" 
          label="口型同步" 
          valuePropName="checked" 
          initialValue={true}
          tooltip="启用后，AI将自动调整口型以匹配配音"
        >
          <Switch />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" loading={loading} icon={<SoundOutlined />}>
            开始配音
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );

  return (
    <div className="material-processing-page">
      <Row gutter={16}>
        <Col span={14}>
          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            items={[
              {
                key: 'image-to-image',
                label: (
                  <span>
                    <PictureOutlined />
                    图生图
                  </span>
                ),
                children: renderImageToImage(),
              },
              {
                key: 'image-to-video',
                label: (
                  <span>
                    <VideoCameraOutlined />
                    图生视频
                  </span>
                ),
                children: renderImageToVideo(),
              },
              {
                key: 'video-translation',
                label: (
                  <span>
                    <TranslationOutlined />
                    视频翻译
                  </span>
                ),
                children: renderVideoTranslation(),
              },
              {
                key: 'video-dubbing',
                label: (
                  <span>
                    <SoundOutlined />
                    视频配音
                  </span>
                ),
                children: renderVideoDubbing(),
              },
            ]}
          />
        </Col>
        
        <Col span={10}>
          <Card 
            title={
              <Space>
                <span>处理队列</span>
                <Badge count={jobs.filter(j => j.status === 'processing').length} />
              </Space>
            }
            extra={
              <Button icon={<SyncOutlined />} onClick={fetchJobs}>刷新</Button>
            }
          >
            <Table
              columns={jobColumns}
              dataSource={jobs}
              rowKey="id"
              pagination={{ pageSize: 5 }}
              size="small"
            />
          </Card>
        </Col>
      </Row>

      <Modal
        title="预览结果"
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={null}
        width={800}
      >
        {previewJob && (
          <div style={{ textAlign: 'center' }}>
            {previewJob.type === 'image_to_image' ? (
              <Image src={previewJob.outputUrl} style={{ maxWidth: '100%' }} />
            ) : (
              <video 
                src={previewJob.outputUrl} 
                controls 
                style={{ maxWidth: '100%', maxHeight: 500 }}
              />
            )}
            <Divider />
            <Space>
              <Button icon={<DownloadOutlined />} onClick={() => handleDownload(previewJob)}>
                下载结果
              </Button>
            </Space>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default MaterialProcessing;
