/**
 * [FE-CMP-008] 批量广告操作组件
 * 支持批量创建、启动、暂停广告
 * AI注意: 所有广告批量操作必须通过此组件
 */

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

interface AdCampaign {
  id: string;
  name: string;
  status: 'ACTIVE' | 'PAUSED' | 'ENDED';
  budget: number;
  spend: number;
  roas: number;
}

interface BatchAdModalProps {
  visible: boolean;
  onClose: () => void;
  operationType: 'CREATE' | 'RESUME' | 'PAUSE';
  selectedCampaigns?: AdCampaign[];
  tenantId: string;
  shopId: string;
  operatorId: string;
  operatorName: string;
  subscriptionLevel?: 'FREE' | 'BASIC' | 'PROFESSIONAL' | 'ENTERPRISE';
  onSuccess?: () => void;
}

const BatchAdModal: FC<BatchAdModalProps> = ({
  visible,
  onClose,
  operationType,
  selectedCampaigns = [],
  tenantId,
  shopId,
  operatorId,
  operatorName,
  subscriptionLevel = 'BASIC',
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [step, setStep] = useState<'select' | 'preview' | 'result'>('select');
  const [batchResult, setBatchResult] = useState<{
    success: number;
    failed: number;
  } | null>(null);

  const getOperationTitle = () => {
    switch (operationType) {
      case 'CREATE': return '批量创建广告';
      case 'RESUME': return '批量启动广告';
      case 'PAUSE': return '批量暂停广告';
      default: return '批量广告操作';
    }
  };

  const getOperationIcon = () => {
    switch (operationType) {
      case 'CREATE': return <PlusOutlined />;
      case 'RESUME': return <PlayCircleOutlined />;
      case 'PAUSE': return <PauseCircleOutlined />;
      default: return null;
    }
  };

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

  const handlePreview = async () => {
    setLoading(true);
    try {
      const result = await batchOperationDataSource.validateBatchOperation({
        tenantId,
        shopId,
        operatorId,
        operationType: `BATCH_AD_${operationType}`,
        targetIds: selectedCampaigns.map(c => c.id),
        targetType: 'AD_CAMPAIGN',
        subscriptionLevel,
      });

      if (!result.allowed) {
        message.error(result.reason);
        return;
      }

      setStep('preview');
    } catch (error) {
      message.error('校验失败');
    } finally {
      setLoading(false);
    }
  };

  const handleExecute = async () => {
    setLoading(true);
    try {
      const batch = await batchOperationDataSource.createBatchOperation({
        tenantId,
        shopId,
        operatorId,
        operatorName,
        operationType: `BATCH_AD_${operationType}`,
        targetType: 'AD_CAMPAIGN',
        targetIds: selectedCampaigns.map(c => c.id),
        subscriptionLevel,
      });

      const result = await batchOperationDataSource.executeBatchOperation(batch.id, {});

      setBatchResult({
        success: result.processedCount,
        failed: result.errorCount,
      });
      setStep('result');
      onSuccess?.();
    } catch (error) {
      message.error('执行失败');
    } finally {
      setLoading(false);
    }
  };

  const renderSelectStep = () => (
    <>
      <Alert
        type="info"
        message={`${getOperationTitle()} - 选择广告计划`}
        description={`已选择 ${selectedCampaigns.length} 个广告计划`}
        style={{ marginBottom: 16 }}
      />

      <Table
        size="small"
        dataSource={selectedCampaigns}
        rowKey="id"
        pagination={false}
        scroll={{ y: 300 }}
        columns={[
          { title: 'ID', dataIndex: 'id', width: 100 },
          { title: '广告计划名称', dataIndex: 'name', ellipsis: true },
          {
            title: '状态',
            dataIndex: 'status',
            render: (status) => (
              <Tag color={status === 'ACTIVE' ? 'green' : status === 'PAUSED' ? 'orange' : 'red'}>
                {status === 'ACTIVE' ? '投放中' : status === 'PAUSED' ? '已暂停' : '已结束'}
              </Tag>
            ),
          },
          {
            title: '预算',
            dataIndex: 'budget',
            render: (v) => `$${v?.toFixed(2)}`,
          },
          {
            title: '花费',
            dataIndex: 'spend',
            render: (v) => `$${v?.toFixed(2)}`,
          },
          {
            title: 'ROAS',
            dataIndex: 'roas',
            render: (v) => v?.toFixed(2),
          },
        ]}
      />

      {operationType === 'CREATE' && (
        <Form form={form} layout="vertical" style={{ marginTop: 16 }}>
          <Divider>新建广告设置</Divider>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="广告计划名称" name="campaignName">
                <Select placeholder="选择模板或输入新名称">
                  <Option value="auto">自动命名</Option>
                  <Option value="custom">自定义</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="每日预算" name="dailyBudget">
                <InputNumber
                  style={{ width: '100%' }}
                  min={1}
                  step={1}
                  prefix="$"
                  placeholder="输入每日预算"
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      )}
    </>
  );

  const renderPreviewStep = () => (
    <>
      <Alert
        type="success"
        icon={<ThunderboltOutlined />}
        message="AI分析通过，可以执行"
        description={
          <div>
            <p>AI已确认此批量操作安全且有效。</p>
            <ul>
              <li>操作类型: {getOperationTitle()}</li>
              <li>影响广告计划: {selectedCampaigns.length} 个</li>
            </ul>
          </div>
        }
        style={{ marginBottom: 16 }}
      />

      <Card size="small">
        <Row gutter={16}>
          <Col span={8}>
            <Statistic title="操作数量" value={selectedCampaigns.length} suffix="个" />
          </Col>
          <Col span={8}>
            <Statistic
              title="操作类型"
              value={operationType === 'CREATE' ? '创建' : operationType === 'RESUME' ? '启动' : '暂停'}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="订阅等级"
              value={subscriptionLevel}
              valueStyle={{ color: subscriptionLevel === 'ENTERPRISE' ? '#52c41a' : '#1890ff' }}
            />
          </Col>
        </Row>
      </Card>
    </>
  );

  const renderResultStep = () => (
    <>
      <div style={{ textAlign: 'center', padding: '40px 0' }}>
        <CheckCircleOutlined style={{ fontSize: 64, color: '#52c41a' }} />
        <h3 style={{ marginTop: 16 }}>批量操作执行完成</h3>
        <p>成功: {batchResult?.success} 个 | 失败: {batchResult?.failed} 个</p>
      </div>
    </>
  );

  return (
    <Modal
      title={
        <Space>
          {getOperationIcon()}
          {getOperationTitle()}
        </Space>
      }
      open={visible}
      onCancel={onClose}
      width={800}
      footer={
        <Space>
          {step === 'select' && (
            <>
              <Button onClick={onClose}>取消</Button>
              <Button
                type="primary"
                onClick={handlePreview}
                loading={loading}
                disabled={selectedCampaigns.length === 0}
              >
                下一步
              </Button>
            </>
          )}
          {step === 'preview' && (
            <>
              <Button onClick={() => setStep('select')}>上一步</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 === 'result' && renderResultStep()}
    </Modal>
  );
};

export default BatchAdModal;
