/**
 * [FE-CMP-007] 批量上架弹窗组件
 * 支持批量上架产品到多个平台/店铺
 * AI注意: 所有批量上架操作必须通过此组件
 */

import {
  useState,
  useEffect,
  Modal,
  Form,
  Select,
  InputNumber,
  Table,
  Button,
  Space,
  Tag,
  Alert,
  message,
  Divider,
  Steps,
  Card,
  Statistic,
  Row,
  Col,
  Progress,
  UploadOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  RobotOutlined,
  ThunderboltOutlined,
  ShopOutlined,
  FC,
} from '@/imports';

interface Platform {
  value: string;
  label: string;
  icon?: string;
}

interface Shop {
  id: string;
  name: string;
  platform: string;
}

interface ListingData {
  price?: number;
  inventory?: number;
  category?: string;
}

interface BatchListingModalProps {
  visible: boolean;
  onClose: () => void;
  selectedProducts: Array<{
    id: string;
    name: string;
    price: number;
    inventory: number;
    image?: string;
  }>;
  tenantId: string;
  operatorId: string;
  operatorName: string;
  subscriptionLevel?: 'FREE' | 'BASIC' | 'PROFESSIONAL' | 'ENTERPRISE';
  onSuccess?: () => void;
}

const BatchListingModal: FC<BatchListingModalProps> = ({
  visible,
  onClose,
  selectedProducts,
  tenantId,
  operatorId,
  operatorName,
  subscriptionLevel = 'BASIC',
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [step, setStep] = useState<'select' | 'analyze' | 'confirm' | 'executing' | 'result'>('select');
  const [selectedPlatforms, setSelectedPlatforms] = useState<string[]>([]);
  const [selectedShops, setSelectedShops] = useState<string[]>([]);
  const [listingData, setListingData] = useState<ListingData>({});
  const [aiAnalysisResult, setAiAnalysisResult] = useState<{
    confidence: number;
    recommendation: string;
    riskLevel: 'LOW' | 'MEDIUM' | 'HIGH';
    warnings: string[];
  } | null>(null);
  const [executionProgress, setExecutionProgress] = useState(0);

  const platforms: Platform[] = [
    { value: 'amazon', label: 'Amazon' },
    { value: 'shopee', label: 'Shopee' },
    { value: 'aliexpress', label: 'AliExpress' },
    { value: 'tiktok', label: 'TikTok' },
    { value: 'ebay', label: 'Ebay' },
    { value: 'lazada', label: 'Lazada' },
    { value: 'walmart', label: 'Walmart' },
    { value: 'etsy', label: 'Etsy' },
  ];

  useEffect(() => {
    if (!visible) {
      setStep('select');
      setAiAnalysisResult(null);
      setExecutionProgress(0);
      form.resetFields();
    }
  }, [visible]);

  const handlePlatformChange = (values: string[]) => {
    setSelectedPlatforms(values);
  };

  const handleShopChange = (values: string[]) => {
    setSelectedShops(values);
  };

  const handleAnalyze = async () => {
    setLoading(true);
    try {
      await new Promise((resolve) => setTimeout(resolve, 1500));

      const mockResult = {
        confidence: subscriptionLevel === 'ENTERPRISE' ? 0.88 :
                    subscriptionLevel === 'PROFESSIONAL' ? 0.76 :
                    subscriptionLevel === 'BASIC' ? 0.65 : 0.5,
        recommendation: selectedPlatforms.length > 1
          ? '建议分批上架，优先选择Amazon和Shopee'
          : '可以立即执行上架',
        riskLevel: selectedProducts.length > 20 ? 'MEDIUM' as const : 'LOW' as const,
        warnings: selectedProducts.some(p => p.price > 100)
          ? ['部分产品价格较高，建议单独审核']
          : [],
      };

      setAiAnalysisResult(mockResult);
      setStep('analyze');
    } catch (error) {
      message.error('AI分析失败');
    } finally {
      setLoading(false);
    }
  };

  const handleConfirm = () => {
    setStep('confirm');
  };

  const handleExecute = async () => {
    setStep('executing');
    setLoading(true);

    try {
      for (let i = 0; i <= 100; i += 10) {
        await new Promise((resolve) => setTimeout(resolve, 300));
        setExecutionProgress(i);
      }

      message.success('批量上架任务已提交');
      setStep('result');
      onSuccess?.();
    } catch (error) {
      message.error('执行失败');
      setStep('confirm');
    } finally {
      setLoading(false);
    }
  };

  const stepItems = [
    { title: '选择平台', icon: <ShopOutlined /> },
    { title: 'AI分析', icon: <RobotOutlined /> },
    { title: '确认执行', icon: <CheckCircleOutlined /> },
    { title: '执行结果', icon: <CheckCircleOutlined /> },
  ];

  const getStepIndex = () => {
    switch (step) {
      case 'select': return 0;
      case 'analyze': return 1;
      case 'confirm': return 2;
      case 'executing':
      case 'result': return 3;
      default: return 0;
    }
  };

  const renderSelectStep = () => (
    <>
      <Form form={form} layout="vertical">
        <Form.Item
          label="目标平台"
          name="platforms"
          rules={[{ required: true, message: '请选择至少一个平台' }]}
        >
          <Select
            mode="multiple"
            placeholder="选择要上架的平台"
            onChange={handlePlatformChange}
            value={selectedPlatforms}
          >
            {platforms.map((p) => (
              <Select.Option key={p.value} value={p.value}>
                {p.label}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          label="目标店铺"
          name="shops"
          rules={[{ required: true, message: '请选择至少一个店铺' }]}
        >
          <Select
            mode="multiple"
            placeholder="选择目标店铺"
            onChange={handleShopChange}
            value={selectedShops}
          >
            <Select.Option value="shop-1">Amazon US Store</Select.Option>
            <Select.Option value="shop-2">Shopee SG Store</Select.Option>
            <Select.Option value="shop-3">AliExpress Store</Select.Option>
            <Select.Option value="shop-4">TikTok Shop US</Select.Option>
          </Select>
        </Form.Item>

        <Divider>上架设置（可选）</Divider>

        <Row gutter={16}>
          <Col span={8}>
            <Form.Item label="默认价格" name="price">
              <InputNumber
                style={{ width: '100%' }}
                placeholder="留空则使用原价"
                min={0}
                step={0.01}
                prefix="$"
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="默认库存" name="inventory">
              <InputNumber
                style={{ width: '100%' }}
                placeholder="留空则使用原库存"
                min={0}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="默认类目" name="category">
              <Select placeholder="选择类目" allowClear>
                <Select.Option value="electronics">电子产品</Select.Option>
                <Select.Option value="clothing">服装</Select.Option>
                <Select.Option value="home">家居</Select.Option>
                <Select.Option value="beauty">美妆</Select.Option>
                <Select.Option value="sports">运动</Select.Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>
      </Form>

      <Divider>待上架产品 ({selectedProducts.length})</Divider>
      <Table
        size="small"
        dataSource={selectedProducts.slice(0, 5)}
        rowKey="id"
        pagination={false}
        scroll={{ y: 200 }}
        columns={[
          { title: 'ID', dataIndex: 'id', width: 80 },
          { title: '名称', dataIndex: 'name', ellipsis: true },
          { title: '价格', dataIndex: 'price', render: (v) => `$${v?.toFixed(2)}` },
          { title: '库存', dataIndex: 'inventory' },
        ]}
      />
      {selectedProducts.length > 5 && (
        <div style={{ textAlign: 'center', marginTop: 8, color: '#999' }}>
          还有 {selectedProducts.length - 5} 个产品...
        </div>
      )}
    </>
  );

  const renderAnalyzeStep = () => (
    <>
      {aiAnalysisResult && (
        <Alert
          type={aiAnalysisResult.riskLevel === 'LOW' ? 'success' : 'warning'}
          icon={aiAnalysisResult.riskLevel === 'LOW' ? <ThunderboltOutlined /> : <ExclamationCircleOutlined />}
          message="AI分析完成"
          description={
            <div>
              <Row gutter={16} style={{ marginTop: 16 }}>
                <Col span={8}>
                  <Statistic
                    title="AI置信度"
                    value={(aiAnalysisResult.confidence * 100).toFixed(0) + '%'}
                    valueStyle={{ color: aiAnalysisResult.confidence >= 0.7 ? '#52c41a' : '#faad14' }}
                  />
                </Col>
                <Col span={8}>
                  <Statistic
                    title="风险等级"
                    value={aiAnalysisResult.riskLevel}
                    valueStyle={{
                      color: aiAnalysisResult.riskLevel === 'LOW' ? '#52c41a' :
                             aiAnalysisResult.riskLevel === 'MEDIUM' ? '#faad14' : '#ff4d4f',
                    }}
                  />
                </Col>
                <Col span={8}>
                  <Statistic
                    title="产品数量"
                    value={selectedProducts.length}
                  />
                </Col>
              </Row>
              <Divider style={{ margin: '16px 0' }} />
              <div>
                <strong>AI建议:</strong>
                <p>{aiAnalysisResult.recommendation}</p>
              </div>
              {aiAnalysisResult.warnings.length > 0 && (
                <div style={{ marginTop: 12 }}>
                  <strong style={{ color: '#faad14' }}>⚠️ 警告:</strong>
                  <ul style={{ margin: '8px 0', paddingLeft: 20 }}>
                    {aiAnalysisResult.warnings.map((w, i) => (
                      <li key={i}>{w}</li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          }
          style={{ marginBottom: 16 }}
        />
      )}

      <Divider>执行摘要</Divider>
      <Card size="small">
        <Row gutter={16}>
          <Col span={6}>
            <Statistic title="目标平台" value={selectedPlatforms.length} suffix="个" />
          </Col>
          <Col span={6}>
            <Statistic title="目标店铺" value={selectedShops.length} suffix="个" />
          </Col>
          <Col span={6}>
            <Statistic title="待上架产品" value={selectedProducts.length} suffix="个" />
          </Col>
          <Col span={6}>
            <Statistic
              title="预计操作"
              value={selectedProducts.length * selectedPlatforms.length}
              suffix="次"
            />
          </Col>
        </Row>
      </Card>
    </>
  );

  const renderConfirmStep = () => (
    <>
      <Alert
        type="info"
        icon={<RobotOutlined />}
        message="确认执行批量上架"
        description={
          <div>
            <p>您即将执行以下批量上架操作:</p>
            <ul>
              <li>目标平台: {selectedPlatforms.join(', ')}</li>
              <li>目标店铺: {selectedShops.length} 个</li>
              <li>产品数量: {selectedProducts.length} 个</li>
              <li>预计操作次数: {selectedProducts.length * selectedPlatforms.length} 次</li>
            </ul>
          </div>
        }
        style={{ marginBottom: 16 }}
      />

      <div style={{ textAlign: 'center', padding: '40px 0' }}>
        <ExclamationCircleOutlined style={{ fontSize: 64, color: '#1890ff' }} />
        <h3>确认开始批量上架？</h3>
        <p>此操作将创建 {selectedProducts.length * selectedPlatforms.length} 个上架任务</p>
      </div>
    </>
  );

  const renderExecutingStep = () => (
    <>
      <div style={{ textAlign: 'center', padding: '60px 0' }}>
        <Progress
          type="circle"
          percent={executionProgress}
          size={120}
          strokeColor="#52c41a"
        />
        <h3 style={{ marginTop: 24 }}>正在执行批量上架...</h3>
        <p>预计完成时间: 约 {Math.ceil(selectedProducts.length * selectedPlatforms.length * 2)} 秒</p>
      </div>
    </>
  );

  const renderResultStep = () => (
    <>
      <div style={{ textAlign: 'center', padding: '40px 0' }}>
        <CheckCircleOutlined style={{ fontSize: 64, color: '#52c41a' }} />
        <h3 style={{ marginTop: 16 }}>批量上架任务已提交</h3>
        <p>任务已加入队列，请到任务中心查看执行进度</p>
      </div>

      <Card size="small" style={{ marginTop: 24 }}>
        <Row gutter={16}>
          <Col span={8}>
            <Statistic title="提交成功" value={selectedProducts.length} suffix="个" />
          </Col>
          <Col span={8}>
            <Statistic title="目标平台" value={selectedPlatforms.length} />
          </Col>
          <Col span={8}>
            <Statistic title="目标店铺" value={selectedShops.length} />
          </Col>
        </Row>
      </Card>
    </>
  );

  return (
    <Modal
      title={
        <Space>
          <UploadOutlined />
          批量上架产品
        </Space>
      }
      open={visible}
      onCancel={onClose}
      width={900}
      footer={
        <Space>
          {step === 'select' && (
            <>
              <Button onClick={onClose}>取消</Button>
              <Button
                type="primary"
                onClick={handleAnalyze}
                loading={loading}
                disabled={selectedPlatforms.length === 0 || selectedShops.length === 0}
              >
                AI分析
              </Button>
            </>
          )}
          {step === 'analyze' && (
            <>
              <Button onClick={() => setStep('select')}>上一步</Button>
              <Button type="primary" onClick={handleConfirm}>
                确认执行
              </Button>
            </>
          )}
          {step === 'confirm' && (
            <>
              <Button onClick={() => setStep('analyze')}>上一步</Button>
              <Button type="primary" onClick={handleExecute} loading={loading}>
                开始执行
              </Button>
            </>
          )}
          {step === 'executing' && null}
          {step === 'result' && (
            <Button type="primary" onClick={onClose}>
              完成
            </Button>
          )}
        </Space>
      }
    >
      <Steps current={getStepIndex()} items={stepItems} style={{ marginBottom: 24 }} />

      {step === 'select' && renderSelectStep()}
      {step === 'analyze' && renderAnalyzeStep()}
      {step === 'confirm' && renderConfirmStep()}
      {step === 'executing' && renderExecutingStep()}
      {step === 'result' && renderResultStep()}
    </Modal>
  );
};

export default BatchListingModal;
