/**
 * [FE-CMP-006] 批量编辑弹窗组件
 * 支持批量修改价格、库存、标题、类目等
 * AI注意: 所有产品批量操作必须通过此组件
 */

import {
  useState,
  useEffect,
  Modal,
  Form,
  Select,
  Input,
  InputNumber,
  Radio,
  Table,
  Button,
  Space,
  Tag,
  Alert,
  message,
  Divider,
  Card,
  Statistic,
  Row,
  Col,
  Tooltip,
  EditOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  RobotOutlined,
  ThunderboltOutlined,
  Option,
  TextArea,
  FC,
} from '@/imports';
import { batchOperationDataSource, BatchOperationValidation } from '../../../../services/batchOperationDataSource';

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

interface EditField {
  type: 'ABSOLUTE' | 'PERCENTAGE';
  value: number;
}

const BatchEditModal: FC<BatchEditModalProps> = ({
  visible,
  onClose,
  selectedProducts,
  tenantId,
  shopId,
  operatorId,
  operatorName,
  subscriptionLevel = 'BASIC',
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [validation, setValidation] = useState<BatchOperationValidation | null>(null);
  const [editType, setEditType] = useState<string>('price');
  const [priceChange, setPriceChange] = useState<EditField>({ type: 'ABSOLUTE', value: 0 });
  const [inventoryChange, setInventoryChange] = useState<EditField>({ type: 'ABSOLUTE', value: 0 });
  const [titleTemplate, setTitleTemplate] = useState<string>('');
  const [step, setStep] = useState<'select' | 'preview' | 'confirm' | 'result'>('select');

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

  const handleEditTypeChange = (type: string) => {
    setEditType(type);
  };

  const calculateNewValue = (currentValue: number, change: EditField): number => {
    if (change.type === 'ABSOLUTE') {
      return change.value;
    }
    return currentValue * (1 + change.value / 100);
  };

  const getPreviewData = () => {
    return selectedProducts.map((product) => {
      let newValue: any;
      let fieldName = '';

      switch (editType) {
        case 'price':
          newValue = calculateNewValue(product.price, priceChange);
          fieldName = 'price';
          break;
        case 'inventory':
          newValue = calculateNewValue(product.inventory, inventoryChange);
          fieldName = 'inventory';
          break;
        case 'title':
          newValue = titleTemplate || product.name;
          fieldName = 'name';
          break;
        case 'category':
          newValue = form.getFieldValue('category');
          fieldName = 'category';
          break;
        default:
          newValue = null;
      }

      return {
        ...product,
        newValue,
        fieldName,
      };
    });
  };

  const handleValidate = async () => {
    setLoading(true);
    try {
      const params = {
        tenantId,
        shopId,
        operatorId,
        operationType: `BATCH_EDIT_${editType.toUpperCase()}`,
        targetIds: selectedProducts.map((p) => p.id),
        targetType: 'PRODUCT' as const,
        subscriptionLevel,
        estimatedImpact: {
          quantity: selectedProducts.length,
          amount: editType === 'price'
            ? selectedProducts.reduce((sum, p) => sum + p.price, 0)
            : undefined,
        },
      };

      const result = await batchOperationDataSource.validateBatchOperation(params);
      setValidation(result);
      setStep('preview');
    } catch (error) {
      message.error('校验失败');
    } finally {
      setLoading(false);
    }
  };

  const handlePreview = () => {
    setStep('preview');
  };

  const handleConfirm = async () => {
    if (validation?.requiredAction === 'PENDING_REVIEW') {
      setStep('confirm');
      return;
    }

    await handleExecute();
  };

  const handleExecute = async () => {
    setLoading(true);
    try {
      const params: any = {
        tenantId,
        shopId,
        operatorId,
        productIds: selectedProducts.map((p) => p.id),
      };

      if (editType === 'price') {
        params.priceChange = priceChange;
        await batchOperationDataSource.batchEditPrice(params);
      } else if (editType === 'inventory') {
        params.inventoryChange = inventoryChange;
        await batchOperationDataSource.batchEditInventory(params);
      }

      message.success('批量操作执行成功');
      setStep('result');
      onSuccess?.();
    } catch (error) {
      message.error('执行失败');
    } finally {
      setLoading(false);
    }
  };

  const renderSelectStep = () => (
    <>
      <Form form={form} layout="vertical">
        <Form.Item label="编辑字段" name="editType">
          <Select
            placeholder="选择要编辑的字段"
            onChange={handleEditTypeChange}
            value={editType}
          >
            <Option value="price">价格</Option>
            <Option value="inventory">库存</Option>
            <Option value="title">标题</Option>
            <Option value="category">类目</Option>
            <Option value="packageWeight">包装重量</Option>
            <Option value="packageSize">包装尺寸</Option>
            <Option value="cod">到货付款</Option>
            <Option value="sellerSku">Seller SKU</Option>
          </Select>
        </Form.Item>

        {editType === 'price' && (
          <>
            <Form.Item label="价格调整方式">
              <Radio.Group
                value={priceChange.type}
                onChange={(e) => setPriceChange({ ...priceChange, type: e.target.value })}
              >
                <Radio value="ABSOLUTE">绝对值</Radio>
                <Radio value="PERCENTAGE">百分比</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item label={priceChange.type === 'ABSOLUTE' ? '新价格' : '调整百分比'}>
              <InputNumber
                style={{ width: '100%' }}
                value={priceChange.value}
                onChange={(value) => setPriceChange({ ...priceChange, value: value || 0 })}
                prefix={priceChange.type === 'PERCENTAGE' ? '%' : '$'}
                placeholder={priceChange.type === 'ABSOLUTE' ? '输入新价格' : '输入百分比'}
              />
            </Form.Item>
          </>
        )}

        {editType === 'inventory' && (
          <>
            <Form.Item label="库存调整方式">
              <Radio.Group
                value={inventoryChange.type}
                onChange={(e) => setInventoryChange({ ...inventoryChange, type: e.target.value })}
              >
                <Radio value="ABSOLUTE">绝对值</Radio>
                <Radio value="PERCENTAGE">百分比</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item label={inventoryChange.type === 'ABSOLUTE' ? '新库存' : '调整百分比'}>
              <InputNumber
                style={{ width: '100%' }}
                value={inventoryChange.value}
                onChange={(value) => setInventoryChange({ ...inventoryChange, value: value || 0 })}
                placeholder={inventoryChange.type === 'ABSOLUTE' ? '输入新库存' : '输入百分比'}
              />
            </Form.Item>
          </>
        )}

        {editType === 'title' && (
          <Form.Item label="新标题模板">
            <TextArea
              rows={3}
              value={titleTemplate}
              onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setTitleTemplate(e.target.value)}
              placeholder="输入新标题，支持模板变量"
            />
          </Form.Item>
        )}

        {editType === 'category' && (
          <Form.Item label="新类目" name="category">
            <Select placeholder="选择新类目">
              <Option value="electronics">电子产品</Option>
              <Option value="clothing">服装</Option>
              <Option value="home">家居</Option>
              <Option value="beauty">美妆</Option>
              <Option value="sports">运动</Option>
            </Select>
          </Form.Item>
        )}
      </Form>

      <Divider>已选择的产品 ({selectedProducts.length})</Divider>
      <Table
        size="small"
        dataSource={selectedProducts.slice(0, 5)}
        rowKey="id"
        pagination={false}
        columns={[
          { title: 'ID', dataIndex: 'id', width: 100 },
          { 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 renderPreviewStep = () => {
    const previewData = getPreviewData();

    return (
      <>
        {validation && (
          <Alert
            type={validation.autoExecute ? 'success' : 'warning'}
            icon={validation.autoExecute ? <ThunderboltOutlined /> : <ExclamationCircleOutlined />}
            message={
              validation.autoExecute
                ? 'AI将自动执行此操作'
                : '此操作需要人工确认'
            }
            description={
              <div>
                <div>置信度: {(validation.confidence * 100).toFixed(1)}%</div>
                <div>风险等级: {validation.riskLevel}</div>
                <div>原因: {validation.reason}</div>
                {validation.warnings.length > 0 && (
                  <div style={{ marginTop: 8 }}>
                    <strong>警告:</strong>
                    <ul style={{ margin: '4px 0', paddingLeft: 20 }}>
                      {validation.warnings.map((w, i) => (
                        <li key={i}>{w}</li>
                      ))}
                    </ul>
                  </div>
                )}
              </div>
            }
            style={{ marginBottom: 16 }}
          />
        )}

        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={8}>
            <Card size="small">
              <Statistic title="操作产品数" value={selectedProducts.length} />
            </Card>
          </Col>
          <Col span={8}>
            <Card size="small">
              <Statistic
                title="操作类型"
                value={editType === 'price' ? '修改价格' : editType === 'inventory' ? '修改库存' : editType}
              />
            </Card>
          </Col>
          <Col span={8}>
            <Card size="small">
              <Statistic
                title="订阅等级"
                value={subscriptionLevel}
                valueStyle={{ color: subscriptionLevel === 'ENTERPRISE' ? '#52c41a' : '#1890ff' }}
              />
            </Card>
          </Col>
        </Row>

        <Divider>变更预览</Divider>
        <Table
          size="small"
          dataSource={previewData}
          rowKey="id"
          pagination={false}
          scroll={{ y: 300 }}
          columns={[
            { title: 'ID', dataIndex: 'id', width: 100 },
            { title: '名称', dataIndex: 'name', ellipsis: true },
            {
              title: '当前值',
              dataIndex: editType === 'price' ? 'price' : editType === 'inventory' ? 'inventory' : 'name',
              render: (v, record: any) =>
                editType === 'price' ? `$${v?.toFixed(2)}` : editType === 'inventory' ? v : v,
            },
            {
              title: '新值',
              dataIndex: 'newValue',
              render: (v, record: any) => (
                <span style={{ color: '#52c41a' }}>
                  {editType === 'price' ? `$${v?.toFixed(2)}` : editType === 'inventory' ? v : v}
                </span>
              ),
            },
          ]}
        />
      </>
    );
  };

  const renderConfirmStep = () => (
    <>
      <Alert
        type="info"
        icon={<RobotOutlined />}
        message="AI建议等待确认"
        description={
          <div>
            <p>AI已分析您的批量操作请求，建议如下:</p>
            <ul>
              <li>操作类型: {editType}</li>
              <li>影响产品数: {selectedProducts.length}</li>
              <li>AI置信度: {(validation?.confidence ?? 0 * 100).toFixed(1)}%</li>
            </ul>
            <p>请确认是否执行此操作。</p>
          </div>
        }
        style={{ marginBottom: 16 }}
      />

      <div style={{ textAlign: 'center', padding: '40px 0' }}>
        <ExclamationCircleOutlined style={{ fontSize: 64, color: '#faad14' }} />
        <h3>确认执行批量操作？</h3>
        <p>此操作将影响 {selectedProducts.length} 个产品</p>
      </div>
    </>
  );

  const renderResultStep = () => (
    <>
      <div style={{ textAlign: 'center', padding: '40px 0' }}>
        <CheckCircleOutlined style={{ fontSize: 64, color: '#52c41a' }} />
        <h3>批量操作执行成功</h3>
        <p>已成功处理 {selectedProducts.length} 个产品</p>
      </div>
    </>
  );

  return (
    <Modal
      title={
        <Space>
          <EditOutlined />
          批量编辑产品
        </Space>
      }
      open={visible}
      onCancel={onClose}
      width={800}
      footer={
        <Space>
          {step === 'select' && (
            <>
              <Button onClick={onClose}>取消</Button>
              <Button type="primary" onClick={handlePreview}>
                下一步
              </Button>
            </>
          )}
          {step === 'preview' && (
            <>
              <Button onClick={() => setStep('select')}>上一步</Button>
              <Button type="primary" onClick={handleConfirm} loading={loading}>
                {validation?.autoExecute ? '确认执行' : '提交AI审核'}
              </Button>
            </>
          )}
          {step === 'confirm' && (
            <>
              <Button onClick={() => setStep('preview')}>上一步</Button>
              <Button type="primary" onClick={handleExecute} loading={loading}>
                确认执行
              </Button>
            </>
          )}
          {step === 'result' && (
            <Button type="primary" onClick={onClose}>
              完成
            </Button>
          )}
        </Space>
      }
    >
      {step === 'select' && renderSelectStep()}
      {step === 'preview' && renderPreviewStep()}
      {step === 'confirm' && renderConfirmStep()}
      {step === 'result' && renderResultStep()}
    </Modal>
  );
};

export default BatchEditModal;
