import React, { useState } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  InputNumber,
  Button,
  Space,
  Row,
  Col,
  Divider,
  Upload,
  message,
  Tabs,
  Table,
  Tag,
  Modal,
  Switch,
  Tooltip,
  Alert,
} from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  SaveOutlined,
  SendOutlined,
  InfoCircleOutlined,
  ShopOutlined,
  DollarOutlined,
  BoxPlotOutlined,
} from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';

const { Option } = Select;
const { TabPane } = Tabs;
const { TextArea } = Input;

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' },
];

export const ProductPublishForm: React.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 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 handleSaveDraft = async () => {
    try {
      await form.validateFields();
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 1000));
      message.success('Draft saved successfully');
    } catch (error) {
      message.error('Please fill in required fields');
    } 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}>
            <TabPane tab="Basic Info" key="basic">
              <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>Product Images</Divider>

              <Form.Item label="Images">
                <Upload
                  listType="picture-card"
                  fileList={fileList}
                  onChange={({ fileList }) => setFileList(fileList)}
                  beforeUpload={() => false}
                  multiple
                >
                  {fileList.length >= 8 ? null : (
                    <div>
                      <PlusOutlined />
                      <div style={{ marginTop: 8 }}>Upload</div>
                    </div>
                  )}
                </Upload>
              </Form.Item>
            </TabPane>

            <TabPane tab={<><DollarOutlined /> Pricing</>} key="pricing">
              <Alert
                message="Profit Margin Validation"
                description="B2B products must maintain at least 15% profit margin. B2C products require 20% minimum."
                type="info"
                showIcon
                style={{ marginBottom: 24 }}
              />

              <Row gutter={24}>
                <Col span={8}>
                  <Form.Item
                    name="price"
                    label="Selling Price"
                    rules={[{ required: true, message: 'Please enter price' }]}
                  >
                    <InputNumber
                      prefix="$"
                      min={0}
                      precision={2}
                      style={{ width: '100%' }}
                      placeholder="0.00"
                    />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    name="costPrice"
                    label="Cost Price"
                    rules={[{ required: true, message: 'Please enter cost price' }]}
                  >
                    <InputNumber
                      prefix="$"
                      min={0}
                      precision={2}
                      style={{ width: '100%' }}
                      placeholder="0.00"
                    />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item name="currency" label="Currency">
                    <Select>
                      {CURRENCIES.map(c => (
                        <Option key={c.value} value={c.value}>{c.label}</Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
            </TabPane>

            <TabPane tab={<><BoxPlotOutlined /> Inventory</>} key="inventory">
              <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' }}
              />
            </TabPane>

            <TabPane tab="Publish Settings" key="settings">
              <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
              />
            </TabPane>
          </Tabs>

          <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>
      </Card>
    </div>
  );
};

export default ProductPublishForm;
