import React, { useState } from 'react';
import { Card, Table, Button, Select, DatePicker, Space, Modal, Typography, Badge, message, Tabs, Row, Col, Statistic } from 'antd';
import { PlusOutlined, EyeOutlined, EditOutlined, DeleteOutlined, ReloadOutlined, PlayCircleOutlined, PauseCircleOutlined, BarChartOutlined, DollarOutlined } from '@ant-design/icons';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { Title, Text } = Typography;
const { TabPane } = Tabs;

const mockAds = [
  {
    id: '1',
    name: 'Electronics Sale Campaign',
    platform: 'Amazon',
    status: 'active',
    budget: 1000,
    spent: 650,
    clicks: 1250,
    impressions: 15000,
    ctr: 8.33,
    conversions: 85,
    cpa: 7.65,
    roi: 2.5,
    createdAt: '2026-03-01',
    updatedAt: '2026-03-18',
  },
  {
    id: '2',
    name: 'Fashion Week Promotion',
    platform: 'eBay',
    status: 'paused',
    budget: 800,
    spent: 400,
    clicks: 800,
    impressions: 10000,
    ctr: 8.0,
    conversions: 45,
    cpa: 8.89,
    roi: 1.8,
    createdAt: '2026-03-05',
    updatedAt: '2026-03-15',
  },
  {
    id: '3',
    name: 'Home Decor Spring Sale',
    platform: 'Shopee',
    status: 'active',
    budget: 600,
    spent: 350,
    clicks: 700,
    impressions: 9000,
    ctr: 7.78,
    conversions: 40,
    cpa: 8.75,
    roi: 2.2,
    createdAt: '2026-03-10',
    updatedAt: '2026-03-18',
  },
  {
    id: '4',
    name: 'Sports Equipment Launch',
    platform: 'Amazon',
    status: 'completed',
    budget: 1200,
    spent: 1180,
    clicks: 2400,
    impressions: 30000,
    ctr: 8.0,
    conversions: 180,
    cpa: 6.56,
    roi: 3.2,
    createdAt: '2026-02-20',
    updatedAt: '2026-03-10',
  },
];

const AdPage: React.FC = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const [selectedAd, setSelectedAd] = useState<any>(null);
  const [activeTab, setActiveTab] = useState('campaigns');

  const handleViewDetail = (record: any) => {
    setSelectedAd(record);
    setIsDetailModalVisible(true);
  };

  const handleCreateAd = () => {
    message.success('Create ad campaign form opened');
  };

  const handleEditAd = (record: any) => {
    message.success(`Edit ad campaign ${record.name}`);
  };

  const handleDeleteAd = (record: any) => {
    message.success(`Delete ad campaign ${record.name}`);
  };

  const handleStartAd = (record: any) => {
    message.success(`Start ad campaign ${record.name}`);
  };

  const handlePauseAd = (record: any) => {
    message.success(`Pause ad campaign ${record.name}`);
  };

  const handleBatchDelete = () => {
    message.success('Batch delete initiated');
  };

  const handleBatchPause = () => {
    message.success('Batch pause initiated');
  };

  const handleBatchStart = () => {
    message.success('Batch start initiated');
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active': return 'success';
      case 'paused': return 'warning';
      case 'completed': return 'default';
      case 'error': return 'error';
      default: return 'default';
    }
  };

  const columns = [
    {
      title: 'Campaign Name',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'Platform',
      dataIndex: 'platform',
      key: 'platform',
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Badge status={getStatusColor(status)} text={status} />
      ),
    },
    {
      title: 'Budget',
      dataIndex: 'budget',
      key: 'budget',
      render: (value: number) => `$${value.toFixed(2)}`,
    },
    {
      title: 'Spent',
      dataIndex: 'spent',
      key: 'spent',
      render: (value: number) => `$${value.toFixed(2)}`,
    },
    {
      title: 'Clicks',
      dataIndex: 'clicks',
      key: 'clicks',
    },
    {
      title: 'Impressions',
      dataIndex: 'impressions',
      key: 'impressions',
    },
    {
      title: 'CTR',
      dataIndex: 'ctr',
      key: 'ctr',
      render: (value: number) => `${value.toFixed(2)}%`,
    },
    {
      title: 'Conversions',
      dataIndex: 'conversions',
      key: 'conversions',
    },
    {
      title: 'CPA',
      dataIndex: 'cpa',
      key: 'cpa',
      render: (value: number) => `$${value.toFixed(2)}`,
    },
    {
      title: 'ROI',
      dataIndex: 'roi',
      key: 'roi',
      render: (value: number) => `${value.toFixed(2)}x`,
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button icon={<EyeOutlined />} onClick={() => handleViewDetail(record)}>View</Button>
          <Button icon={<EditOutlined />} onClick={() => handleEditAd(record)}>Edit</Button>
          {record.status === 'active' ? (
            <Button icon={<PauseCircleOutlined />} onClick={() => handlePauseAd(record)}>Pause</Button>
          ) : (
            <Button icon={<PlayCircleOutlined />} onClick={() => handleStartAd(record)}>Start</Button>
          )}
          <Button icon={<BarChartOutlined />} onClick={() => handleViewDetail(record)}>Analytics</Button>
          <Button icon={<DeleteOutlined />} danger onClick={() => handleDeleteAd(record)}>Delete</Button>
        </Space>
      ),
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: React.Key[]) => {
      setSelectedRowKeys(keys);
    },
  };

  return (
    <div className="ad-page">
      <div className="page-header" style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Title level={4}>Advertising Management</Title>
        <Space>
          <Button icon={<PlusOutlined />} type="primary" onClick={handleCreateAd}>Create Campaign</Button>
          <Button icon={<ReloadOutlined />}>Refresh</Button>
          <Button onClick={handleBatchStart} disabled={selectedRowKeys.length === 0}>Batch Start</Button>
          <Button onClick={handleBatchPause} disabled={selectedRowKeys.length === 0}>Batch Pause</Button>
          <Button onClick={handleBatchDelete} disabled={selectedRowKeys.length === 0} danger>Batch Delete</Button>
        </Space>
      </div>

      <Card style={{ marginBottom: 24 }}>
        <Row gutter={[16, 16]}>
          <Col span={6}>
            <Statistic
              title="Total Budget"
              value={3600}
              precision={2}
              prefix="$"
              valueStyle={{ color: '#3f8600' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="Total Spent"
              value={2580}
              precision={2}
              prefix="$"
              valueStyle={{ color: '#cf1322' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="Total Clicks"
              value={5150}
              valueStyle={{ color: '#1890ff' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="Total Conversions"
              value={350}
              valueStyle={{ color: '#52c41a' }}
            />
          </Col>
        </Row>
      </Card>

      <Card style={{ marginBottom: 24 }}>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="Campaigns" key="campaigns">
            <div style={{ display: 'flex', gap: 16, marginBottom: 16, flexWrap: 'wrap' }}>
              <Select placeholder="Select Platform" style={{ width: 150 }}>
                <Option value="all">All Platforms</Option>
                <Option value="amazon">Amazon</Option>
                <Option value="ebay">eBay</Option>
                <Option value="shopee">Shopee</Option>
              </Select>
              <Select placeholder="Select Status" style={{ width: 150 }}>
                <Option value="all">All Status</Option>
                <Option value="active">Active</Option>
                <Option value="paused">Paused</Option>
                <Option value="completed">Completed</Option>
              </Select>
              <RangePicker style={{ width: 300 }} />
            </div>

            <Table
              rowSelection={rowSelection}
              columns={columns}
              dataSource={mockAds}
              rowKey="id"
              pagination={{
                pageSize: 10,
              }}
            />
          </TabPane>
          <TabPane tab="Analytics" key="analytics">
            <div style={{ padding: 24, textAlign: 'center' }}>
              <Text type="secondary">Analytics dashboard will be displayed here</Text>
            </div>
          </TabPane>
          <TabPane tab="Optimization" key="optimization">
            <div style={{ padding: 24, textAlign: 'center' }}>
              <Text type="secondary">AI optimization suggestions will be displayed here</Text>
            </div>
          </TabPane>
        </Tabs>
      </Card>

      <Modal
        title={`Campaign Detail - ${selectedAd?.name}`}
        open={isDetailModalVisible}
        onCancel={() => setIsDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setIsDetailModalVisible(false)}>
            Close
          </Button>,
        ]}
        width={1000}
      >
        {selectedAd && (
          <Tabs defaultActiveKey="details">
            <TabPane tab="Campaign Details" key="details">
              <div style={{ marginBottom: 24 }}>
                <h3>Basic Information</h3>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 16 }}>
                  <div>
                    <Text strong>Campaign Name:</Text> {selectedAd.name}
                  </div>
                  <div>
                    <Text strong>Platform:</Text> {selectedAd.platform}
                  </div>
                  <div>
                    <Text strong>Status:</Text> <Badge status={getStatusColor(selectedAd.status)} text={selectedAd.status} />
                  </div>
                  <div>
                    <Text strong>Budget:</Text> ${selectedAd.budget.toFixed(2)}
                  </div>
                  <div>
                    <Text strong>Spent:</Text> ${selectedAd.spent.toFixed(2)}
                  </div>
                  <div>
                    <Text strong>Created At:</Text> {selectedAd.createdAt}
                  </div>
                  <div>
                    <Text strong>Updated At:</Text> {selectedAd.updatedAt}
                  </div>
                </div>
              </div>
              <div>
                <h3>Performance Metrics</h3>
                <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
                  <Col span={8}>
                    <Card>
                      <Statistic
                        title="Clicks"
                        value={selectedAd.clicks}
                        valueStyle={{ color: '#1890ff' }}
                      />
                    </Card>
                  </Col>
                  <Col span={8}>
                    <Card>
                      <Statistic
                        title="Impressions"
                        value={selectedAd.impressions}
                        valueStyle={{ color: '#52c41a' }}
                      />
                    </Card>
                  </Col>
                  <Col span={8}>
                    <Card>
                      <Statistic
                        title="CTR"
                        value={selectedAd.ctr}
                        precision={2}
                        suffix="%"
                        valueStyle={{ color: '#faad14' }}
                      />
                    </Card>
                  </Col>
                  <Col span={8}>
                    <Card>
                      <Statistic
                        title="Conversions"
                        value={selectedAd.conversions}
                        valueStyle={{ color: '#722ed1' }}
                      />
                    </Card>
                  </Col>
                  <Col span={8}>
                    <Card>
                      <Statistic
                        title="CPA"
                        value={selectedAd.cpa}
                        precision={2}
                        prefix="$"
                        valueStyle={{ color: '#eb2f96' }}
                      />
                    </Card>
                  </Col>
                  <Col span={8}>
                    <Card>
                      <Statistic
                        title="ROI"
                        value={selectedAd.roi}
                        precision={2}
                        suffix="x"
                        valueStyle={{ color: '#3f8600' }}
                      />
                    </Card>
                  </Col>
                </Row>
              </div>
            </TabPane>
            <TabPane tab="Analytics" key="analytics">
              <div style={{ padding: 24, textAlign: 'center' }}>
                <Text type="secondary">Detailed analytics will be displayed here</Text>
              </div>
            </TabPane>
            <TabPane tab="Optimization" key="optimization">
              <div style={{ padding: 24, textAlign: 'center' }}>
                <Text type="secondary">AI optimization suggestions will be displayed here</Text>
              </div>
            </TabPane>
          </Tabs>
        )}
      </Modal>
    </div>
  );
};

export default AdPage;