import type { Ad } from '@/services/marketingDataSource';
import {
  useState,
  useEffect,
  Table,
  Button,
  Input,
  Select,
  DatePicker,
  message,
  Card,
  Modal,
  Form,
  InputNumber,
  Row,
  Col,
  Switch,
  Tag,
  Divider,
  Alert,
  Tooltip,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  InfoCircleOutlined,
  RocketOutlined,
  VideoCameraOutlined,
  marketingDataSource,
  Option,
  RangePicker,
  Search,
  TextArea,
  FC,
} from '@/imports';

const Ads: FC = () => {
  const [ads, setAds] = useState<Ad[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingAd, setEditingAd] = useState<Ad | null>(null);
  const [form] = Form.useForm();
  const [selectedPlatform, setSelectedPlatform] = useState<string>('');
  const [gmvMaxType, setGmvMaxType] = useState<string>('product');
  const [filters, setFilters] = useState({
    platform: '',
    status: '',
    search: '',
    dateRange: null as any,
  });

  useEffect(() => {
    fetchAds();
  }, [filters]);

  const fetchAds = async () => {
    setLoading(true);
    try {
      const data = await marketingDataSource.fetchAds(filters);
      setAds(data);
    } catch (error) {
      message.error('Failed to load ads');
    } finally {
      setLoading(false);
    }
  };

  const handleAddAd = () => {
    setEditingAd(null);
    setSelectedPlatform('');
    setGmvMaxType('product');
    form.resetFields();
    form.setFieldsValue({
      status: 'paused',
      budget: 100,
      dailyBudget: 10,
      bidStrategy: 'auto',
      targetAudience: 'all',
      gmvMaxType: 'product',
      optimizationGoal: 'gmv',
      autoCreative: true,
      autoTargeting: true,
    });
    setModalVisible(true);
  };

  const handleEditAd = (id: string) => {
    const ad = ads.find(a => a.id === id);
    if (ad) {
      setEditingAd(ad);
      setSelectedPlatform(ad.platform || '');
      setGmvMaxType(ad.gmvMaxType || 'product');
      form.setFieldsValue(ad);
      setModalVisible(true);
    }
  };

  const handleSaveAd = async () => {
    try {
      const values = await form.validateFields();
      if (editingAd) {
        const updatedAds = ads.map(ad => 
          ad.id === editingAd.id ? { ...ad, ...values } : ad
        );
        setAds(updatedAds);
        message.success('广告已更新');
      } else {
        const newAd: Ad = {
          id: `ad-${Date.now()}`,
          ...values,
          spend: 0,
          clicks: 0,
          conversions: 0,
          roi: 0,
          createdAt: new Date().toISOString(),
        };
        setAds([...ads, newAd]);
        message.success('广告已创建');
      }
      setModalVisible(false);
    } catch (error) {
      message.error('保存失败');
    }
  };

  const handleStartAd = (id: string) => {
    const updatedAds = ads.map(ad =>
      ad.id === id ? { ...ad, status: 'active' as const } : ad
    );
    setAds(updatedAds);
    message.success('广告已启动');
  };

  const handlePauseAd = (id: string) => {
    const updatedAds = ads.map(ad =>
      ad.id === id ? { ...ad, status: 'paused' as const } : ad
    );
    setAds(updatedAds);
    message.success('广告已暂停');
  };

  const handleDeleteAd = (id: string) => {
    const updatedAds = ads.filter(ad => ad.id !== id);
    setAds(updatedAds);
    message.success('广告已删除');
  };

  const handlePlatformChange = (value: string) => {
    setSelectedPlatform(value);
    if (value === 'TikTok GMV Max') {
      form.setFieldsValue({
        bidStrategy: 'gmv_max',
        autoCreative: true,
        autoTargeting: true,
        optimizationGoal: 'gmv',
      });
    }
  };

  const isGMVMax = selectedPlatform === 'TikTok GMV Max';

  const columns = [
    {
      title: '广告名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '平台',
      dataIndex: 'platform',
      key: 'platform',
      render: (platform: string, record: Ad) => {
        const colorMap: Record<string, string> = {
          Facebook: 'blue',
          Google: 'red',
          Instagram: 'purple',
          TikTok: 'magenta',
          'TikTok GMV Max': 'gold',
        };
        return (
          <div>
            <Tag color={colorMap[platform] || 'default'}>{platform}</Tag>
            {platform === 'TikTok GMV Max' && record.gmvMaxType && (
              <Tag color="cyan" style={{ marginLeft: 4 }}>
                {record.gmvMaxType === 'product' ? '商品推广' : '直播推广'}
              </Tag>
            )}
          </div>
        );
      },
    },
    {
      title: '活动',
      dataIndex: 'campaign',
      key: 'campaign',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap: Record<string, { label: string; color: string }> = {
          active: { label: '活跃', color: 'success' },
          paused: { label: '暂停', color: 'warning' },
          completed: { label: '已完成', color: 'default' },
        };
        const config = statusMap[status] || { label: status, color: 'default' };
        return <Tag color={config.color}>{config.label}</Tag>;
      },
    },
    {
      title: '预算',
      dataIndex: 'budget',
      key: 'budget',
      render: (budget: number) => `$${budget?.toFixed(2) || '0.00'}`,
    },
    {
      title: '支出',
      dataIndex: 'spend',
      key: 'spend',
      render: (spend: number) => `$${spend?.toFixed(2) || '0.00'}`,
    },
    {
      title: 'GMV',
      dataIndex: 'gmv',
      key: 'gmv',
      render: (gmv: number, record: Ad) => {
        if (record.platform === 'TikTok GMV Max') {
          return <Tag color="green">${(gmv || 0).toFixed(2)}</Tag>;
        }
        return '-';
      },
    },
    {
      title: '点击量',
      dataIndex: 'clicks',
      key: 'clicks',
    },
    {
      title: '转化数',
      dataIndex: 'conversions',
      key: 'conversions',
    },
    {
      title: 'ROI',
      dataIndex: 'roi',
      key: 'roi',
      render: (roi: number) => `${(roi || 0).toFixed(2)}x`,
    },
    {
      title: '操作',
      key: 'action',
      render: (_: unknown, record: Ad) => (
        <div>
          {record.status === 'active' ? (
            <Button
              type="link"
              icon={<PauseCircleOutlined />}
              onClick={() => handlePauseAd(record.id)}
            >
              暂停
            </Button>
          ) : (
            <Button
              type="link"
              icon={<PlayCircleOutlined />}
              onClick={() => handleStartAd(record.id)}
            >
              启动
            </Button>
          )}
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEditAd(record.id)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteAd(record.id)}
          >
            删除
          </Button>
        </div>
      ),
    },
  ];

  return (
    <div className="ads">
      <div className="page-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <h1>广告管理</h1>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleAddAd}
        >
          创建广告
        </Button>
      </div>

      <div className="filter-section" style={{ marginBottom: 24, display: 'flex', gap: 16, flexWrap: 'wrap' }}>
        <Search
          placeholder="搜索广告名称或活动"
          style={{ width: 300 }}
          onChange={(e) => setFilters({ ...filters, search: e.target.value })}
        />
        <Select
          placeholder="平台"
          style={{ width: 150 }}
          onChange={(value) => setFilters({ ...filters, platform: value })}
        >
          <Option value="">全部</Option>
          <Option value="Facebook">Facebook</Option>
          <Option value="Google">Google</Option>
          <Option value="Instagram">Instagram</Option>
          <Option value="TikTok">TikTok</Option>
          <Option value="TikTok GMV Max">TikTok GMV Max</Option>
        </Select>
        <Select
          placeholder="状态"
          style={{ width: 120 }}
          onChange={(value) => setFilters({ ...filters, status: value })}
        >
          <Option value="">全部</Option>
          <Option value="active">活跃</Option>
          <Option value="paused">暂停</Option>
          <Option value="completed">已完成</Option>
        </Select>
        <RangePicker
          style={{ width: 300 }}
          onChange={(dates) => setFilters({ ...filters, dateRange: dates })}
        />
        <Button
          icon={<SearchOutlined />}
          onClick={fetchAds}
        >
          筛选
        </Button>
      </div>

      <Card title="广告列表">
        <Table
          columns={columns}
          dataSource={ads}
          loading={loading}
          rowKey="id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
          }}
        />
      </Card>

      <Modal
        title={editingAd ? '编辑广告' : '创建广告'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={handleSaveAd}
        width={900}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="广告名称"
                rules={[{ required: true, message: '请输入广告名称' }]}
              >
                <Input placeholder="输入广告名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="platform"
                label="平台"
                rules={[{ required: true, message: '请选择平台' }]}
              >
                <Select placeholder="选择平台" onChange={handlePlatformChange}>
                  <Option value="Facebook">Facebook</Option>
                  <Option value="Google">Google</Option>
                  <Option value="Instagram">Instagram</Option>
                  <Option value="TikTok">TikTok</Option>
                  <Option value="TikTok GMV Max">
                    <Tag color="gold">NEW</Tag> TikTok GMV Max
                  </Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          {isGMVMax && (
            <>
              <Alert
                message="GMV Max - TikTok AI自动化广告解决方案"
                description="GMV Max 是 TikTok 2025年推出的 AI 自动化广告解决方案，旨在最大化 GMV（总交易额）。系统将自动优化创意、定向和出价，无需手动调整。"
                type="info"
                showIcon
                icon={<RocketOutlined />}
                style={{ marginBottom: 16 }}
              />

              <Divider orientation="left">GMV Max 配置</Divider>

              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    name="gmvMaxType"
                    label={
                      <span>
                        GMV Max 类型
                        <Tooltip title="Product GMV Max 用于商品推广，LIVE GMV Max 用于直播推广">
                          <InfoCircleOutlined style={{ marginLeft: 4, color: '#999' }} />
                        </Tooltip>
                      </span>
                    }
                    rules={[{ required: true, message: '请选择 GMV Max 类型' }]}
                  >
                    <Select placeholder="选择类型" onChange={(v) => setGmvMaxType(v)}>
                      <Option value="product">
                        <RocketOutlined style={{ marginRight: 8 }} />
                        Product GMV Max - 商品推广
                      </Option>
                      <Option value="live">
                        <VideoCameraOutlined style={{ marginRight: 8 }} />
                        LIVE GMV Max - 直播推广
                      </Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="optimizationGoal"
                    label="优化目标"
                  >
                    <Select placeholder="选择优化目标">
                      <Option value="gmv">最大化 GMV</Option>
                      <Option value="roas">最大化 ROAS</Option>
                      <Option value="conversion">最大化转化数</Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>

              {gmvMaxType === 'product' && (
                <Row gutter={16}>
                  <Col span={12}>
                    <Form.Item
                      name="productIds"
                      label="推广商品ID"
                      rules={[{ required: true, message: '请输入商品ID' }]}
                    >
                      <Input placeholder="输入商品ID，多个用逗号分隔" />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      name="productCategory"
                      label="商品类目"
                    >
                      <Select placeholder="选择商品类目">
                        <Option value="fashion">服饰鞋包</Option>
                        <Option value="beauty">美妆护肤</Option>
                        <Option value="electronics">电子产品</Option>
                        <Option value="home">家居生活</Option>
                        <Option value="food">食品饮料</Option>
                        <Option value="other">其他</Option>
                      </Select>
                    </Form.Item>
                  </Col>
                </Row>
              )}

              {gmvMaxType === 'live' && (
                <Row gutter={16}>
                  <Col span={12}>
                    <Form.Item
                      name="liveRoomId"
                      label="直播间ID"
                      rules={[{ required: true, message: '请输入直播间ID' }]}
                    >
                      <Input placeholder="输入直播间ID" />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      name="liveSchedule"
                      label="直播时间"
                    >
                      <RangePicker 
                        showTime 
                        style={{ width: '100%' }}
                        placeholder={['开始时间', '结束时间']}
                      />
                    </Form.Item>
                  </Col>
                </Row>
              )}

              <Row gutter={16}>
                <Col span={8}>
                  <Form.Item
                    name="autoCreative"
                    label="自动创意优化"
                    valuePropName="checked"
                  >
                    <Switch checkedChildren="开" unCheckedChildren="关" />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    name="autoTargeting"
                    label="自动定向优化"
                    valuePropName="checked"
                  >
                    <Switch checkedChildren="开" unCheckedChildren="关" />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    name="autoBid"
                    label="自动出价优化"
                    valuePropName="checked"
                  >
                    <Switch checkedChildren="开" unCheckedChildren="关" defaultChecked />
                  </Form.Item>
                </Col>
              </Row>

              <Divider orientation="left">预算设置</Divider>
            </>
          )}

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="campaign"
                label="活动名称"
                rules={[{ required: true, message: '请输入活动名称' }]}
              >
                <Input placeholder="输入活动名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select placeholder="选择状态">
                  <Option value="active">活跃</Option>
                  <Option value="paused">暂停</Option>
                  <Option value="completed">已完成</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="budget"
                label={isGMVMax ? "GMV Max 总预算 ($)" : "总预算 ($)"}
                rules={[{ required: true, message: '请输入总预算' }]}
              >
                <InputNumber
                  min={0}
                  precision={2}
                  style={{ width: '100%' }}
                  placeholder="输入总预算"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="dailyBudget"
                label="日预算 ($)"
                rules={[{ required: true, message: '请输入日预算' }]}
              >
                <InputNumber
                  min={0}
                  precision={2}
                  style={{ width: '100%' }}
                  placeholder="输入日预算"
                />
              </Form.Item>
            </Col>
          </Row>

          {!isGMVMax && (
            <>
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    name="bidStrategy"
                    label="出价策略"
                  >
                    <Select placeholder="选择出价策略">
                      <Option value="auto">自动出价</Option>
                      <Option value="manual">手动出价</Option>
                      <Option value="target_cpa">目标CPA</Option>
                      <Option value="target_roas">目标ROAS</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="targetAudience"
                    label="目标受众"
                  >
                    <Select placeholder="选择目标受众">
                      <Option value="all">所有用户</Option>
                      <Option value="new">新用户</Option>
                      <Option value="returning">回访用户</Option>
                      <Option value="similar">相似受众</Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
            </>
          )}

          <Form.Item
            name="description"
            label="广告描述"
          >
            <TextArea rows={3} placeholder="输入广告描述" />
          </Form.Item>

          {!isGMVMax && (
            <Form.Item
              name="targetUrl"
              label="目标URL"
              rules={[{ type: 'url', message: '请输入有效的URL' }]}
            >
              <Input placeholder="https://example.com" />
            </Form.Item>
          )}
        </Form>
      </Modal>
    </div>
  );
};

export default Ads;
