import {
  useState,
  Card,
  Form,
  Input,
  Select,
  InputNumber,
  Button,
  Space,
  Row,
  Col,
  Divider,
  Upload,
  message,
  Tabs,
  Table,
  Tag,
  Modal,
  Switch,
  Tooltip,
  Alert,
  Image,
  Badge,
  Progress,
  PlusOutlined,
  DeleteOutlined,
  SaveOutlined,
  SendOutlined,
  InfoCircleOutlined,
  ShopOutlined,
  DollarOutlined,
  BoxPlotOutlined,
  PictureOutlined,
  VideoCameraOutlined,
  TranslationOutlined,
  ThunderboltOutlined,
  EyeOutlined,
  Option,
  TextArea,
  FC,
} from '@/imports';
import type { UploadFile } from 'antd/es/upload/interface';
import {
  materialProcessingDataSource,
  ImageToImageParams,
  ImageToVideoParams,
  STYLE_OPTIONS,
  TRANSLATION_LANGUAGES,
} from '@/services/materialProcessingDataSource';
import { useLocale } from '@/contexts/LocaleContext';

interface ProductVariant {
  id: string;
  sku: string;
  name: string;
  price: number;
  stock: number;
  attributes: Record<string, string>;
}

interface PublishFormValues {
  name: string;
  platform: string[];
  category: string;
  brand: string;
  description: string;
  price: number;
  costPrice: number;
  currency: string;
  stock: number;
  sku: string;
  status: 'DRAFT' | 'PENDING' | 'ACTIVE';
  autoPublish: boolean;
  complianceCheck: boolean;
}

const PLATFORMS = [
  { value: 'Amazon', label: 'Amazon' },
  { value: 'eBay', label: 'eBay' },
  { value: 'Shopify', label: 'Shopify' },
  { value: 'Walmart', label: 'Walmart' },
  { value: 'AliExpress', label: 'AliExpress' },
];

const CATEGORIES = [
  { value: 'Industrial Automation > Sensors', label: 'Industrial Automation > Sensors' },
  { value: 'Industrial Automation > Controllers', label: 'Industrial Automation > Controllers' },
  { value: 'Industrial Automation > Motors', label: 'Industrial Automation > Motors' },
  { value: 'Electronics > Components', label: 'Electronics > Components' },
  { value: 'Tools > Power Tools', label: 'Tools > Power Tools' },
];

const CURRENCIES = [
  { value: 'USD', label: 'USD - US Dollar' },
  { value: 'EUR', label: 'EUR - Euro' },
  { value: 'GBP', label: 'GBP - British Pound' },
  { value: 'CNY', label: 'CNY - Chinese Yuan' },
];

const ProductPublishForm: FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [variants, setVariants] = useState<ProductVariant[]>([]);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [activeTab, setActiveTab] = useState('basic');
  const [processingJobs, setProcessingJobs] = useState<any[]>([]);
  const [materialModalVisible, setMaterialModalVisible] = useState(false);
  const [selectedImage, setSelectedImage] = useState<string>('');
  const [processingType, setProcessingType] = useState<'image-to-image' | 'image-to-video'>('image-to-image');
  const [processingLoading, setProcessingLoading] = useState(false);
  const { t } = useLocale();

  const handleAddVariant = () => {
    const newVariant: ProductVariant = {
      id: `v${Date.now()}`,
      sku: '',
      name: '',
      price: 0,
      stock: 0,
      attributes: {},
    };
    setVariants([...variants, newVariant]);
  };

  const handleRemoveVariant = (id: string) => {
    setVariants(variants.filter(v => v.id !== id));
  };

  const handleVariantChange = (id: string, field: string, value: any) => {
    setVariants(variants.map(v => 
      v.id === id ? { ...v, [field]: value } : v
    ));
  };

  const handleOpenMaterialProcessing = (imageUrl: string, type: 'image-to-image' | 'image-to-video') => {
    setSelectedImage(imageUrl);
    setProcessingType(type);
    setMaterialModalVisible(true);
  };

  const handleProcessImage = async (params: ImageToImageParams | ImageToVideoParams) => {
    if (!selectedImage) {
      message.warning(t('product.publish.selectImage'));
      return;
    }
    
    setProcessingLoading(true);
    try {
      let job;
      if (processingType === 'image-to-image') {
        job = await materialProcessingDataSource.imageToImage(selectedImage, params as ImageToImageParams);
      } else {
        job = await materialProcessingDataSource.imageToVideo(selectedImage, params as ImageToVideoParams);
      }
      
      setProcessingJobs([...processingJobs, job]);
      message.success(t('product.publish.taskCreated', { id: job.id }));
      setMaterialModalVisible(false);
      
      // 轮询检查任务状态
      const checkInterval = setInterval(async () => {
        const updatedJob = await materialProcessingDataSource.getJobStatus(job.id);
        if (updatedJob.status === 'completed') {
          clearInterval(checkInterval);
          message.success(t('product.publish.processingComplete'));
          // 将处理结果添加到文件列表
          if (processingType === 'image-to-image') {
            setFileList([...fileList, {
              uid: `processed-${Date.now()}`,
              name: `processed-${Date.now()}.jpg`,
              status: 'done',
              url: updatedJob.outputUrl,
              thumbUrl: updatedJob.outputUrl,
            } as UploadFile]);
          } else {
            message.info(t('product.publish.videoGenerated'));
          }
          setProcessingJobs(processingJobs.map(j => j.id === job.id ? updatedJob : j));
        }
      }, 2000);
    } catch (error) {
      message.error(t('product.publish.processFailed'));
    } finally {
      setProcessingLoading(false);
    }
  };

  const handleSaveDraft = async () => {
    try {
      await form.validateFields();
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 1000));
      message.success(t('product.publish.draftSaved'));
    } catch (error) {
      message.error(t('product.publish.fillRequiredFields'));
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      
      // Step 1: 先保存到本地系统
      const productData = {
        ...values,
        variants,
        images: fileList.map(f => f.url || f.thumbUrl),
        createdAt: new Date().toISOString(),
        syncStatus: 'PENDING', // 待同步状态
      };
      
      // 模拟保存到本地数据库
      await new Promise(resolve => setTimeout(resolve, 800));
      message.success('Product saved to local system');
      
      // Step 2: 合规检查（本地进行）
      if (values.complianceCheck) {
        message.info('Running compliance check...');
        await new Promise(resolve => setTimeout(resolve, 600));
      }
      
      // Step 3: 提交审核（本地状态变更）
      await new Promise(resolve => setTimeout(resolve, 400));
      
      Modal.success({
        title: 'Product Created Successfully',
        content: (
          <div>
            <p>Product "{values.name}" has been saved to local system.</p>
            <p>Target platforms: {values.platform.join(', ')}</p>
            <p>Status: {values.autoPublish ? 'Will be auto-published after review' : 'Pending review'}</p>
            <p style={{ color: '#1890ff', marginTop: 8 }}>
              The product will be synced to platforms according to the sync schedule.
            </p>
          </div>
        ),
      });
      
      // 重置表单
      form.resetFields();
      setVariants([]);
      setFileList([]);
    } catch (error) {
      message.error('Please fill in required fields');
    } finally {
      setLoading(false);
    }
  };

  const variantColumns = [
    {
      title: 'SKU',
      dataIndex: 'sku',
      key: 'sku',
      render: (value: string, record: ProductVariant) => (
        <Input 
          value={value} 
          onChange={(e) => handleVariantChange(record.id, 'sku', e.target.value)}
          placeholder="SKU"
        />
      ),
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      render: (value: string, record: ProductVariant) => (
        <Input 
          value={value} 
          onChange={(e) => handleVariantChange(record.id, 'name', e.target.value)}
          placeholder="Variant Name"
        />
      ),
    },
    {
      title: 'Price',
      dataIndex: 'price',
      key: 'price',
      render: (value: number, record: ProductVariant) => (
        <InputNumber 
          value={value} 
          onChange={(v) => handleVariantChange(record.id, 'price', v)}
          min={0}
          precision={2}
          style={{ width: '100%' }}
        />
      ),
    },
    {
      title: 'Stock',
      dataIndex: 'stock',
      key: 'stock',
      render: (value: number, record: ProductVariant) => (
        <InputNumber 
          value={value} 
          onChange={(v) => handleVariantChange(record.id, 'stock', v)}
          min={0}
          style={{ width: '100%' }}
        />
      ),
    },
    {
      title: 'Action',
      key: 'action',
      render: (_: any, record: ProductVariant) => (
        <Button 
          type="text" 
          danger 
          icon={<DeleteOutlined />} 
          onClick={() => handleRemoveVariant(record.id)}
        />
      ),
    },
  ];

  return (
    <div className="product-publish-form-page">
      <Card title="Product Publish Form">
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            currency: 'USD',
            status: 'DRAFT',
            autoPublish: false,
            complianceCheck: true,
          }}
        >
          <Tabs 
            activeKey={activeTab} 
            onChange={setActiveTab}
            items={[
              { key: 'basic', label: 'Basic Info', children: (
                <>
                  <Row gutter={24}>
                    <Col span={12}>
                      <Form.Item
                        name="name"
                        label="Product Name"
                        rules={[{ required: true, message: 'Please enter product name' }]}
                      >
                        <Input placeholder="Enter product name" maxLength={200} showCount />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        name="platform"
                        label="Target Platforms"
                        rules={[{ required: true, message: 'Please select at least one platform' }]}
                      >
                        <Select mode="multiple" placeholder="Select platforms">
                          {PLATFORMS.map(p => (
                            <Option key={p.value} value={p.value}>{p.label}</Option>
                          ))}
                        </Select>
                      </Form.Item>
                    </Col>
                  </Row>

                  <Row gutter={24}>
                    <Col span={12}>
                      <Form.Item
                        name="category"
                        label="Category"
                        rules={[{ required: true, message: 'Please select category' }]}
                      >
                        <Select placeholder="Select category" showSearch>
                          {CATEGORIES.map(c => (
                            <Option key={c.value} value={c.value}>{c.label}</Option>
                          ))}
                        </Select>
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item name="brand" label="Brand">
                        <Input placeholder="Enter brand name" />
                      </Form.Item>
                    </Col>
                  </Row>

                  <Form.Item
                    name="description"
                    label="Description"
                    rules={[{ required: true, message: 'Please enter description' }]}
                  >
                    <TextArea rows={4} placeholder="Enter product description" maxLength={5000} showCount />
                  </Form.Item>

                  <Divider>{t('product.publish.productImages')}</Divider>

                  <Alert
                    message={t('product.publish.materialProcessing')}
                    description={t('product.publish.materialProcessingDesc')}
                    type="info"
                    showIcon
                    style={{ marginBottom: 16 }}
                  />

                  <Form.Item label={t('product.publish.images')}>
                    <Upload
                      listType="picture-card"
                      fileList={fileList}
                      onChange={({ fileList }) => setFileList(fileList)}
                      beforeUpload={() => false}
                      multiple
                      itemRender={(originNode, file) => (
                        <div style={{ position: 'relative' }}>
                          {originNode}
                          {file.status === 'done' && file.url && (
                            <div style={{
                              position: 'absolute',
                              bottom: 0,
                              left: 0,
                              right: 0,
                              background: 'rgba(0,0,0,0.5)',
                              display: 'flex',
                              justifyContent: 'center',
                              gap: 4,
                              padding: '2px 0',
                            }}>
                              <Tooltip title={t('product.publish.imageToImage')}>
                                <Button
                                  size="small"
                                  type="text"
                                  icon={<PictureOutlined style={{ color: '#fff' }} />}
                                  onClick={() => handleOpenMaterialProcessing(file.url || file.thumbUrl || '', 'image-to-image')}
                                />
                              </Tooltip>
                              <Tooltip title={t('product.publish.imageToVideo')}>
                                <Button
                                  size="small"
                                  type="text"
                                  icon={<VideoCameraOutlined style={{ color: '#fff' }} />}
                                  onClick={() => handleOpenMaterialProcessing(file.url || file.thumbUrl || '', 'image-to-video')}
                                />
                              </Tooltip>
                            </div>
                          )}
                        </div>
                      )}
                    >
                      {fileList.length >= 8 ? null : (
                        <div>
                          <PlusOutlined />
                          <div style={{ marginTop: 8 }}>{t('product.publish.upload')}</div>
                        </div>
                      )}
                    </Upload>
                  </Form.Item>

                  {processingJobs.length > 0 && (
                    <Card size="small" title={t('product.publish.processingTasks')} style={{ marginTop: 16 }}>
                      {processingJobs.map(job => (
                        <div key={job.id} style={{ marginBottom: 8 }}>
                          <Space>
                            <Tag color="blue">{job.type === 'image_to_image' ? t('product.publish.imageToImage') : t('product.publish.imageToVideo')}</Tag>
                            <Progress percent={job.progress} size="small" style={{ width: 200 }} />
                            <Tag color={job.status === 'processing' ? 'processing' : 'success'}>
                              {job.status}
                            </Tag>
                          </Space>
                        </div>
                      ))}
                    </Card>
                  )}
                </>
              )},
              { key: 'pricing', label: <><DollarOutlined /> {t('product.publish.pricing')}</>, children: (
                <>
                  <Alert
                    message={t('product.publish.profitMarginValidation')}
                    description={t('product.publish.profitMarginDesc')}
                    type="info"
                    showIcon
                    style={{ marginBottom: 24 }}
                  />

                  <Row gutter={24}>
                    <Col span={8}>
                      <Form.Item
                        name="price"
                        label={t('product.publish.sellingPrice')}
                        rules={[{ required: true, message: t('product.publish.enterPrice') }]}
                      >
                        <InputNumber
                          prefix="$"
                          min={0}
                          precision={2}
                          style={{ width: '100%' }}
                          placeholder="0.00"
                        />
                      </Form.Item>
                    </Col>
                    <Col span={8}>
                      <Form.Item
                        name="costPrice"
                        label={t('product.publish.costPrice')}
                        rules={[{ required: true, message: t('product.publish.enterCostPrice') }]}
                      >
                        <InputNumber
                          prefix="$"
                          min={0}
                          precision={2}
                          style={{ width: '100%' }}
                          placeholder="0.00"
                        />
                      </Form.Item>
                    </Col>
                    <Col span={8}>
                      <Form.Item name="currency" label={t('product.publish.currency')}>
                        <Select>
                          {CURRENCIES.map(c => (
                            <Option key={c.value} value={c.value}>{c.label}</Option>
                          ))}
                        </Select>
                      </Form.Item>
                    </Col>
                  </Row>
                </>
              )},
              { key: 'inventory', label: <><BoxPlotOutlined /> Inventory</>, children: (
                <>
                  <Row gutter={24}>
                    <Col span={12}>
                      <Form.Item
                        name="sku"
                        label="SKU"
                        rules={[{ required: true, message: 'Please enter SKU' }]}
                      >
                        <Input placeholder="Enter SKU" />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        name="stock"
                        label="Initial Stock"
                        rules={[{ required: true, message: 'Please enter stock quantity' }]}
                      >
                        <InputNumber min={0} style={{ width: '100%' }} placeholder="0" />
                      </Form.Item>
                    </Col>
                  </Row>

                  <Divider>Variants</Divider>

                  <div style={{ marginBottom: 16 }}>
                    <Button type="dashed" icon={<PlusOutlined />} onClick={handleAddVariant}>
                      Add Variant
                    </Button>
                  </div>

                  <Table
                    columns={variantColumns}
                    dataSource={variants}
                    rowKey="id"
                    pagination={false}
                    size="small"
                    locale={{ emptyText: 'No variants added' }}
                  />
                </>
              )},
              { key: 'settings', label: 'Publish Settings', children: (
                <>
                  <Row gutter={24}>
                    <Col span={12}>
                      <Form.Item
                        name="status"
                        label="Status"
                        rules={[{ required: true }]}
                      >
                        <Select>
                          <Option value="DRAFT">Draft</Option>
                          <Option value="PENDING">Pending Review</Option>
                          <Option value="ACTIVE">Active</Option>
                        </Select>
                      </Form.Item>
                    </Col>
                  </Row>

                  <Form.Item
                    name="complianceCheck"
                    label="Run Compliance Check"
                    valuePropName="checked"
                  >
                    <Switch checkedChildren="Yes" unCheckedChildren="No" />
                  </Form.Item>

                  <Form.Item
                    name="autoPublish"
                    label="Auto Publish After Compliance Check"
                    valuePropName="checked"
                    extra="Product will be automatically published if compliance check passes"
                  >
                    <Switch checkedChildren="Yes" unCheckedChildren="No" />
                  </Form.Item>

                  <Alert
                    message="Publishing Rules"
                    description={
                      <ul style={{ marginBottom: 0, paddingLeft: 20 }}>
                        <li>Products are first saved to local system, then synced to platforms</li>
                        <li>All products must pass compliance check before syncing</li>
                        <li>Products with profit margin below threshold will require manual approval</li>
                        <li>Platform sync happens according to configured schedule</li>
                      </ul>
                    }
                    type="warning"
                    showIcon
                  />
                </>
              )},
            ]}
          />

          <Divider />

          <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
            <Button onClick={() => form.resetFields()}>Reset</Button>
            <Button icon={<SaveOutlined />} onClick={handleSaveDraft} loading={loading}>
              Save Draft
            </Button>
            <Button type="primary" icon={<SendOutlined />} onClick={handleSubmit} loading={loading}>
              Save to System
            </Button>
          </Space>
        </Form>

        <Modal
          title={
            <Space>
              <ThunderboltOutlined style={{ color: '#1890ff' }} />
              {processingType === 'image-to-image' ? t('product.publish.imageToImage') : t('product.publish.imageToVideo')}
            </Space>
          }
          open={materialModalVisible}
          onCancel={() => setMaterialModalVisible(false)}
          footer={null}
          width={600}
        >
          {selectedImage && (
            <div style={{ marginBottom: 16 }}>
              <Text type="secondary">{t('product.publish.originalPreview')}</Text>
              <Image src={selectedImage} width={200} style={{ marginTop: 8, borderRadius: 8 }} />
            </div>
          )}

          <Form layout="vertical" onFinish={handleProcessImage}>
            {processingType === 'image-to-image' ? (
              <>
                <Form.Item name="prompt" label={t('product.publish.prompt')}>
                  <Input.TextArea 
                    rows={2} 
                    placeholder={t('product.publish.promptPlaceholder')}
                  />
                </Form.Item>
                <Row gutter={16}>
                  <Col span={12}>
                    <Form.Item name="style" label={t('product.publish.style')} 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={t('product.publish.strength')} initialValue={0.7}>
                      <InputNumber min={0} max={1} step={0.1} style={{ width: '100%' }} />
                    </Form.Item>
                  </Col>
                </Row>
              </>
            ) : (
              <>
                <Form.Item name="prompt" label={t('product.publish.prompt')}>
                  <Input.TextArea 
                    rows={2} 
                    placeholder={t('product.publish.promptPlaceholder')}
                  />
                </Form.Item>
                <Row gutter={16}>
                  <Col span={8}>
                    <Form.Item name="motion" label={t('product.publish.motion')} initialValue="zoom">
                      <Select>
                        <Option value="zoom">{t('product.publish.motionZoom')}</Option>
                        <Option value="pan">{t('product.publish.motionPan')}</Option>
                        <Option value="rotate">{t('product.publish.motionRotate')}</Option>
                        <Option value="dynamic">{t('product.publish.motionDynamic')}</Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item name="duration" label={t('product.publish.duration')} initialValue={5}>
                      <InputNumber min={1} max={30} style={{ width: '100%' }} />
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item name="fps" label={t('product.publish.fps')} 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>
              <Space>
                <Button type="primary" htmlType="submit" loading={processingLoading}>
                  {t('product.publish.startProcessing')}
                </Button>
                <Button onClick={() => setMaterialModalVisible(false)}>
                  {t('product.publish.cancel')}
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </div>
  );
};

export default ProductPublishForm;
