import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  Tag,
  Tooltip,
  Row,
  Col,
  Statistic,
  message,
  Progress,
  Divider,
  Alert,
  Descriptions,
} from 'antd';
import {
  RocketOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  EyeOutlined,
  DollarOutlined,
  ThunderboltOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SyncOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { marketingDataSource, Ad } from '@/services/marketingDataSource';

const { Option } = Select;

type CampaignStatus = 'PENDING' | 'RUNNING' | 'PAUSED' | 'COMPLETED' | 'FAILED';

interface AdCampaign {
  id: string;
  ad_plan_id: string;
  tenant_id: string;
  product_id?: string;
  sku_id?: string;
  bid_amount: number;
  clicks: number;
  impressions: number;
  spend: number;
  sales: number;
  conversions: number;
  status: CampaignStatus;
  created_at: string;
  updated_at: string;
}

interface AdPlan {
  id: string;
  name: string;
  platform: string;
  budget: number;
  status: string;
}

interface ExecuteCampaignParams {
  adPlanId: string;
  productId?: string;
  skuId?: string;
  bidAmount: number;
}

const CAMPAIGN_STATUS_COLORS: Record<CampaignStatus, string> = {
  PENDING: 'default',
  RUNNING: 'green',
  PAUSED: 'orange',
  COMPLETED: 'blue',
  FAILED: 'red',
};

const CAMPAIGN_STATUS_ICONS: Record<CampaignStatus, React.ReactNode> = {
  PENDING: <SyncOutlined spin />,
  RUNNING: <PlayCircleOutlined />,
  PAUSED: <PauseCircleOutlined />,
  COMPLETED: <CheckCircleOutlined />,
  FAILED: <CloseCircleOutlined />,
};

const MOCK_AD_PLANS: AdPlan[] = [
  { id: 'ADP-001', name: 'Summer Sale Campaign', platform: 'AMAZON', budget: 5000, status: 'ACTIVE' },
  { id: 'ADP-002', name: 'New Product Launch', platform: 'SHOPEE', budget: 15000, status: 'ACTIVE' },
  { id: 'ADP-003', name: 'Brand Awareness Q3', platform: 'TIKTOK', budget: 8000, status: 'DRAFT' },
];

const MOCK_CAMPAIGNS: AdCampaign[] = [
  {
    id: 'CAMP-001',
    ad_plan_id: 'ADP-001',
    tenant_id: 'T001',
    product_id: 'P001',
    sku_id: 'SKU001',
    bid_amount: 2.5,
    clicks: 1250,
    impressions: 45000,
    spend: 312.5,
    sales: 1562.5,
    conversions: 45,
    status: 'RUNNING',
    created_at: '2026-06-01T10:00:00Z',
    updated_at: '2026-06-15T14:30:00Z',
  },
  {
    id: 'CAMP-002',
    ad_plan_id: 'ADP-001',
    tenant_id: 'T001',
    product_id: 'P002',
    sku_id: 'SKU002',
    bid_amount: 1.8,
    clicks: 890,
    impressions: 32000,
    spend: 160.2,
    sales: 890.0,
    conversions: 28,
    status: 'RUNNING',
    created_at: '2026-06-02T09:00:00Z',
    updated_at: '2026-06-15T14:30:00Z',
  },
  {
    id: 'CAMP-003',
    ad_plan_id: 'ADP-002',
    tenant_id: 'T001',
    product_id: 'P003',
    bid_amount: 3.0,
    clicks: 2100,
    impressions: 78000,
    spend: 630.0,
    sales: 3150.0,
    conversions: 72,
    status: 'RUNNING',
    created_at: '2026-07-01T08:00:00Z',
    updated_at: '2026-07-10T16:45:00Z',
  },
];

const MOCK_PRODUCTS = [
  { id: 'P001', name: 'Wireless Earbuds Pro', sku: 'SKU001' },
  { id: 'P002', name: 'Smart Watch X200', sku: 'SKU002' },
  { id: 'P003', name: 'Bluetooth Speaker Mini', sku: 'SKU003' },
  { id: 'P004', name: 'USB-C Hub 7-in-1', sku: 'SKU004' },
];

export const AdDelivery: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [campaigns, setCampaigns] = useState<AdCampaign[]>(MOCK_CAMPAIGNS);
  const [adPlans, setAdPlans] = useState<AdPlan[]>(MOCK_AD_PLANS);
  const [modalVisible, setModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedCampaign, setSelectedCampaign] = useState<AdCampaign | null>(null);
  const [selectedAdPlanId, setSelectedAdPlanId] = useState<string | null>(null);

  useEffect(() => {
    loadCampaigns();
  }, []);

  const loadCampaigns = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      setCampaigns(MOCK_CAMPAIGNS);
    } catch (error) {
      message.error('Failed to load campaigns');
    } finally {
      setLoading(false);
    }
  };

  const handleExecuteCampaign = async (values: ExecuteCampaignParams) => {
    setLoading(true);
    try {
      const newCampaign: AdCampaign = {
        id: `CAMP-${Date.now()}`,
        ad_plan_id: values.adPlanId,
        tenant_id: 'T001',
        product_id: values.productId,
        sku_id: values.skuId,
        bid_amount: values.bidAmount,
        clicks: 0,
        impressions: 0,
        spend: 0,
        sales: 0,
        conversions: 0,
        status: 'RUNNING',
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
      };

      setCampaigns([...campaigns, newCampaign]);
      setModalVisible(false);
      form.resetFields();
      message.success('Campaign started successfully');
    } catch (error) {
      message.error('Failed to start campaign');
    } finally {
      setLoading(false);
    }
  };

  const handlePauseCampaign = async (campaignId: string) => {
    setLoading(true);
    try {
      setCampaigns(campaigns.map(c => 
        c.id === campaignId 
          ? { ...c, status: 'PAUSED' as CampaignStatus, updated_at: new Date().toISOString() }
          : c
      ));
      message.success('Campaign paused');
    } catch (error) {
      message.error('Failed to pause campaign');
    } finally {
      setLoading(false);
    }
  };

  const handleResumeCampaign = async (campaignId: string) => {
    setLoading(true);
    try {
      setCampaigns(campaigns.map(c => 
        c.id === campaignId 
          ? { ...c, status: 'RUNNING' as CampaignStatus, updated_at: new Date().toISOString() }
          : c
      ));
      message.success('Campaign resumed');
    } catch (error) {
      message.error('Failed to resume campaign');
    } finally {
      setLoading(false);
    }
  };

  const openDetailModal = (campaign: AdCampaign) => {
    setSelectedCampaign(campaign);
    setDetailModalVisible(true);
  };

  const getAdPlanName = (adPlanId: string) => {
    const plan = adPlans.find(p => p.id === adPlanId);
    return plan ? plan.name : adPlanId;
  };

  const calculateCTR = (clicks: number, impressions: number) => {
    if (impressions === 0) return 0;
    return ((clicks / impressions) * 100).toFixed(2);
  };

  const calculateCPC = (spend: number, clicks: number) => {
    if (clicks === 0) return 0;
    return (spend / clicks).toFixed(2);
  };

  const calculateROAS = (sales: number, spend: number) => {
    if (spend === 0) return 0;
    return (sales / spend).toFixed(2);
  };

  const columns: ColumnsType<AdCampaign> = [
    {
      title: 'Campaign ID',
      dataIndex: 'id',
      key: 'id',
      width: 120,
      render: (id: string) => <code>{id}</code>,
    },
    {
      title: 'Ad Plan',
      dataIndex: 'ad_plan_id',
      key: 'ad_plan_id',
      width: 180,
      render: (adPlanId: string) => getAdPlanName(adPlanId),
    },
    {
      title: 'Product',
      dataIndex: 'product_id',
      key: 'product_id',
      width: 150,
      render: (productId?: string) => {
        const product = MOCK_PRODUCTS.find(p => p.id === productId);
        return product ? product.name : productId || '-';
      },
    },
    {
      title: 'Bid Amount',
      dataIndex: 'bid_amount',
      key: 'bid_amount',
      width: 100,
      render: (bid: number) => <strong>${bid.toFixed(2)}</strong>,
    },
    {
      title: 'Impressions',
      dataIndex: 'impressions',
      key: 'impressions',
      width: 100,
      render: (impressions: number) => impressions.toLocaleString(),
    },
    {
      title: 'Clicks',
      dataIndex: 'clicks',
      key: 'clicks',
      width: 80,
      render: (clicks: number) => clicks.toLocaleString(),
    },
    {
      title: 'CTR',
      key: 'ctr',
      width: 80,
      render: (_, record) => (
        <span>{calculateCTR(record.clicks, record.impressions)}%</span>
      ),
    },
    {
      title: 'Spend',
      dataIndex: 'spend',
      key: 'spend',
      width: 100,
      render: (spend: number) => (
        <span style={{ color: '#ff4d4f' }}>${spend.toFixed(2)}</span>
      ),
    },
    {
      title: 'Sales',
      dataIndex: 'sales',
      key: 'sales',
      width: 100,
      render: (sales: number) => (
        <span style={{ color: '#52c41a' }}>${sales.toFixed(2)}</span>
      ),
    },
    {
      title: 'ROAS',
      key: 'roas',
      width: 80,
      render: (_, record) => {
        const roas = parseFloat(calculateROAS(record.sales, record.spend));
        const color = roas >= 3 ? '#52c41a' : roas >= 2 ? '#faad14' : '#ff4d4f';
        return <span style={{ color }}>{roas.toFixed(2)}x</span>;
      },
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: CampaignStatus) => (
        <Tag color={CAMPAIGN_STATUS_COLORS[status]} icon={CAMPAIGN_STATUS_ICONS[status]}>
          {status}
        </Tag>
      ),
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="View Details">
            <Button 
              type="link" 
              size="small" 
              icon={<EyeOutlined />}
              onClick={() => openDetailModal(record)}
            />
          </Tooltip>
          {record.status === 'RUNNING' && (
            <Tooltip title="Pause">
              <Button 
                type="link" 
                size="small" 
                icon={<PauseCircleOutlined />}
                onClick={() => handlePauseCampaign(record.id)}
              />
            </Tooltip>
          )}
          {record.status === 'PAUSED' && (
            <Tooltip title="Resume">
              <Button 
                type="link" 
                size="small" 
                icon={<PlayCircleOutlined />}
                onClick={() => handleResumeCampaign(record.id)}
              />
            </Tooltip>
          )}
        </Space>
      ),
    },
  ];

  const totalSpend = campaigns.reduce((sum, c) => sum + c.spend, 0);
  const totalSales = campaigns.reduce((sum, c) => sum + c.sales, 0);
  const totalClicks = campaigns.reduce((sum, c) => sum + c.clicks, 0);
  const totalImpressions = campaigns.reduce((sum, c) => sum + c.impressions, 0);
  const runningCampaigns = campaigns.filter(c => c.status === 'RUNNING').length;

  return (
    <div className="ad-delivery-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="Running Campaigns"
              value={runningCampaigns}
              prefix={<ThunderboltOutlined style={{ color: '#1890ff' }} />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Total Spend"
              value={totalSpend}
              precision={2}
              prefix={<DollarOutlined style={{ color: '#ff4d4f' }} />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Total Sales"
              value={totalSales}
              precision={2}
              prefix={<DollarOutlined style={{ color: '#52c41a' }} />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Overall ROAS"
              value={totalSpend > 0 ? (totalSales / totalSpend).toFixed(2) : 0}
              suffix="x"
              valueStyle={{ 
                color: totalSpend > 0 && totalSales / totalSpend >= 3 ? '#52c41a' : '#faad14' 
              }}
            />
          </Card>
        </Col>
      </Row>

      {runningCampaigns > 0 && (
        <Alert
          message={`${runningCampaigns} campaign(s) currently running`}
          description={`Total impressions: ${totalImpressions.toLocaleString()} | Total clicks: ${totalClicks.toLocaleString()} | CTR: ${calculateCTR(totalClicks, totalImpressions)}%`}
          type="info"
          showIcon
          icon={<RocketOutlined />}
          style={{ marginBottom: 16 }}
        />
      )}

      <Card 
        title="Ad Campaign Management"
        extra={
          <Space>
            <Select
              placeholder="Filter by Ad Plan"
              style={{ width: 200 }}
              allowClear
              onChange={(value) => setSelectedAdPlanId(value)}
            >
              {adPlans.filter(p => p.status === 'ACTIVE').map(plan => (
                <Option key={plan.id} value={plan.id}>{plan.name}</Option>
              ))}
            </Select>
            <Button 
              type="primary" 
              icon={<RocketOutlined />} 
              onClick={() => setModalVisible(true)}
            >
              Launch Campaign
            </Button>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={selectedAdPlanId 
            ? campaigns.filter(c => c.ad_plan_id === selectedAdPlanId)
            : campaigns
          }
          rowKey="id"
          loading={loading}
          scroll={{ x: 1400 }}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showTotal: (total) => `Total ${total} campaigns`,
          }}
        />
      </Card>

      <Modal
        title="Launch New Campaign"
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          form.resetFields();
        }}
        footer={null}
        width={500}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleExecuteCampaign}
        >
          <Form.Item
            name="adPlanId"
            label="Ad Plan"
            rules={[{ required: true, message: 'Please select an ad plan' }]}
          >
            <Select placeholder="Select Ad Plan">
              {adPlans.filter(p => p.status === 'ACTIVE').map(plan => (
                <Option key={plan.id} value={plan.id}>
                  {plan.name} ({plan.platform})
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="productId"
            label="Product"
          >
            <Select placeholder="Select Product (Optional)" allowClear>
              {MOCK_PRODUCTS.map(product => (
                <Option key={product.id} value={product.id}>
                  {product.name} ({product.sku})
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="bidAmount"
            label="Bid Amount ($)"
            rules={[{ required: true, message: 'Please enter bid amount' }]}
          >
            <InputNumber
              min={0.01}
              precision={2}
              step={0.1}
              style={{ width: '100%' }}
              placeholder="Enter bid amount"
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading} icon={<RocketOutlined />}>
                Launch Campaign
              </Button>
              <Button onClick={() => {
                setModalVisible(false);
                form.resetFields();
              }}>
                Cancel
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Campaign Details"
        open={detailModalVisible}
        onCancel={() => {
          setDetailModalVisible(false);
          setSelectedCampaign(null);
        }}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            Close
          </Button>,
        ]}
        width={700}
      >
        {selectedCampaign && (
          <div>
            <Descriptions bordered column={2}>
              <Descriptions.Item label="Campaign ID">
                <code>{selectedCampaign.id}</code>
              </Descriptions.Item>
              <Descriptions.Item label="Status">
                <Tag color={CAMPAIGN_STATUS_COLORS[selectedCampaign.status]} icon={CAMPAIGN_STATUS_ICONS[selectedCampaign.status]}>
                  {selectedCampaign.status}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Ad Plan">{getAdPlanName(selectedCampaign.ad_plan_id)}</Descriptions.Item>
              <Descriptions.Item label="Bid Amount">${selectedCampaign.bid_amount.toFixed(2)}</Descriptions.Item>
              <Descriptions.Item label="Product">
                {MOCK_PRODUCTS.find(p => p.id === selectedCampaign.product_id)?.name || selectedCampaign.product_id || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="SKU">{selectedCampaign.sku_id || '-'}</Descriptions.Item>
            </Descriptions>

            <Divider>Performance Metrics</Divider>

            <Row gutter={16}>
              <Col span={6}>
                <Statistic
                  title="Impressions"
                  value={selectedCampaign.impressions}
                />
              </Col>
              <Col span={6}>
                <Statistic
                  title="Clicks"
                  value={selectedCampaign.clicks}
                />
              </Col>
              <Col span={6}>
                <Statistic
                  title="CTR"
                  value={calculateCTR(selectedCampaign.clicks, selectedCampaign.impressions)}
                  suffix="%"
                />
              </Col>
              <Col span={6}>
                <Statistic
                  title="CPC"
                  value={calculateCPC(selectedCampaign.spend, selectedCampaign.clicks)}
                  prefix="$"
                />
              </Col>
            </Row>
            <Row gutter={16} style={{ marginTop: 16 }}>
              <Col span={6}>
                <Statistic
                  title="Spend"
                  value={selectedCampaign.spend}
                  precision={2}
                  prefix="$"
                  valueStyle={{ color: '#ff4d4f' }}
                />
              </Col>
              <Col span={6}>
                <Statistic
                  title="Sales"
                  value={selectedCampaign.sales}
                  precision={2}
                  prefix="$"
                  valueStyle={{ color: '#52c41a' }}
                />
              </Col>
              <Col span={6}>
                <Statistic
                  title="Conversions"
                  value={selectedCampaign.conversions}
                />
              </Col>
              <Col span={6}>
                <Statistic
                  title="ROAS"
                  value={calculateROAS(selectedCampaign.sales, selectedCampaign.spend)}
                  suffix="x"
                  valueStyle={{ 
                    color: parseFloat(calculateROAS(selectedCampaign.sales, selectedCampaign.spend)) >= 3 
                      ? '#52c41a' 
                      : '#faad14' 
                  }}
                />
              </Col>
            </Row>

            <Divider>Timeline</Divider>
            <Descriptions column={2}>
              <Descriptions.Item label="Created">
                {dayjs(selectedCampaign.created_at).format('YYYY-MM-DD HH:mm:ss')}
              </Descriptions.Item>
              <Descriptions.Item label="Last Updated">
                {dayjs(selectedCampaign.updated_at).format('YYYY-MM-DD HH:mm:ss')}
              </Descriptions.Item>
            </Descriptions>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default AdDelivery;
