import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  DatePicker,
  Select,
  Tag,
  Row,
  Col,
  Statistic,
  message,
  Divider,
  Descriptions,
  Empty,
  Spin,
  Typography,
  Progress,
  Tooltip,
} from 'antd';
import {
  LineChartOutlined,
  DollarOutlined,
  PercentageOutlined,
  RiseOutlined,
  FallOutlined,
  InfoCircleOutlined,
  SyncOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs, { Dayjs } from 'dayjs';
import { marketingDataSource, Ad } from '@/services/marketingDataSource';

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

interface ROIData {
  adPlanId: string;
  adPlanName: string;
  platform: string;
  totalSpend: number;
  totalSales: number;
  totalConversions: number;
  roi: number;
  roas: number;
  ctr: number;
  cpc: number;
  acos: number;
  impressions: number;
  clicks: number;
}

interface DateRange {
  startDate: string;
  endDate: string;
}

const PLATFORM_COLORS: Record<string, string> = {
  AMAZON: 'orange',
  EBAY: 'blue',
  SHOPEE: 'red',
  TIKTOK: 'cyan',
};

const MOCK_ROI_DATA: ROIData[] = [
  {
    adPlanId: 'ADP-001',
    adPlanName: 'Summer Sale Campaign',
    platform: 'AMAZON',
    totalSpend: 1250.5,
    totalSales: 5625.75,
    totalConversions: 162,
    roi: 350.0,
    roas: 4.5,
    ctr: 2.78,
    cpc: 0.89,
    acos: 22.22,
    impressions: 125000,
    clicks: 3475,
  },
  {
    adPlanId: 'ADP-002',
    adPlanName: 'New Product Launch',
    platform: 'SHOPEE',
    totalSpend: 3150.0,
    totalSales: 11025.0,
    totalConversions: 285,
    roi: 250.0,
    roas: 3.5,
    ctr: 3.15,
    cpc: 1.05,
    acos: 28.57,
    impressions: 180000,
    clicks: 5670,
  },
  {
    adPlanId: 'ADP-003',
    adPlanName: 'Brand Awareness Q3',
    platform: 'TIKTOK',
    totalSpend: 890.25,
    totalSales: 2670.75,
    totalConversions: 89,
    roi: 200.0,
    roas: 3.0,
    ctr: 4.52,
    cpc: 0.45,
    acos: 33.33,
    impressions: 95000,
    clicks: 4294,
  },
];

const AD_PLANS = [
  { id: 'ADP-001', name: 'Summer Sale Campaign', platform: 'AMAZON' },
  { id: 'ADP-002', name: 'New Product Launch', platform: 'SHOPEE' },
  { id: 'ADP-003', name: 'Brand Awareness Q3', platform: 'TIKTOK' },
];

export const ROIAnalysis: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [roiData, setRoiData] = useState<ROIData[]>([]);
  const [selectedAdPlanId, setSelectedAdPlanId] = useState<string | null>(null);
  const [dateRange, setDateRange] = useState<[Dayjs, Dayjs]>([
    dayjs().subtract(30, 'days'),
    dayjs(),
  ]);
  const [selectedRow, setSelectedRow] = useState<ROIData | null>(null);

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

  const loadROIData = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 800));
      setRoiData(MOCK_ROI_DATA);
    } catch (error) {
      message.error('Failed to load ROI data');
    } finally {
      setLoading(false);
    }
  };

  const handleRefresh = async () => {
    await loadROIData();
    message.success('ROI data refreshed');
  };

  const handleExport = () => {
    message.info('Export functionality coming soon');
  };

  const getROIColor = (roi: number) => {
    if (roi >= 300) return '#52c41a';
    if (roi >= 200) return '#73d13d';
    if (roi >= 100) return '#faad14';
    return '#ff4d4f';
  };

  const getROASColor = (roas: number) => {
    if (roas >= 4) return '#52c41a';
    if (roas >= 3) return '#73d13d';
    if (roas >= 2) return '#faad14';
    return '#ff4d4f';
  };

  const getACOSColor = (acos: number) => {
    if (acos <= 20) return '#52c41a';
    if (acos <= 30) return '#faad14';
    return '#ff4d4f';
  };

  const columns: ColumnsType<ROIData> = [
    {
      title: 'Ad Plan',
      dataIndex: 'adPlanName',
      key: 'adPlanName',
      width: 200,
      render: (name: string, record) => (
        <Space direction="vertical" size={0}>
          <Text strong>{name}</Text>
          <Tag color={PLATFORM_COLORS[record.platform]}>{record.platform}</Tag>
        </Space>
      ),
    },
    {
      title: 'Spend',
      dataIndex: 'totalSpend',
      key: 'totalSpend',
      width: 100,
      render: (spend: number) => (
        <Text type="danger">${spend.toLocaleString(undefined, { minimumFractionDigits: 2 })}</Text>
      ),
    },
    {
      title: 'Sales',
      dataIndex: 'totalSales',
      key: 'totalSales',
      width: 100,
      render: (sales: number) => (
        <Text type="success">${sales.toLocaleString(undefined, { minimumFractionDigits: 2 })}</Text>
      ),
    },
    {
      title: 'ROI',
      dataIndex: 'roi',
      key: 'roi',
      width: 100,
      sorter: (a, b) => a.roi - b.roi,
      render: (roi: number) => (
        <Space>
          {roi >= 100 ? <RiseOutlined style={{ color: getROIColor(roi) }} /> : <FallOutlined style={{ color: '#ff4d4f' }} />}
          <Text strong style={{ color: getROIColor(roi) }}>{roi.toFixed(2)}%</Text>
        </Space>
      ),
    },
    {
      title: 'ROAS',
      dataIndex: 'roas',
      key: 'roas',
      width: 80,
      sorter: (a, b) => a.roas - b.roas,
      render: (roas: number) => (
        <Text strong style={{ color: getROASColor(roas) }}>{roas.toFixed(2)}x</Text>
      ),
    },
    {
      title: 'ACoS',
      dataIndex: 'acos',
      key: 'acos',
      width: 80,
      sorter: (a, b) => a.acos - b.acos,
      render: (acos: number) => (
        <Text style={{ color: getACOSColor(acos) }}>{acos.toFixed(2)}%</Text>
      ),
    },
    {
      title: 'CTR',
      dataIndex: 'ctr',
      key: 'ctr',
      width: 80,
      render: (ctr: number) => `${ctr.toFixed(2)}%`,
    },
    {
      title: 'CPC',
      dataIndex: 'cpc',
      key: 'cpc',
      width: 80,
      render: (cpc: number) => `$${cpc.toFixed(2)}`,
    },
    {
      title: 'Conversions',
      dataIndex: 'totalConversions',
      key: 'totalConversions',
      width: 100,
      render: (conversions: number) => conversions.toLocaleString(),
    },
    {
      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(),
    },
  ];

  const filteredData = selectedAdPlanId
    ? roiData.filter(d => d.adPlanId === selectedAdPlanId)
    : roiData;

  const totalSpend = filteredData.reduce((sum, d) => sum + d.totalSpend, 0);
  const totalSales = filteredData.reduce((sum, d) => sum + d.totalSales, 0);
  const totalConversions = filteredData.reduce((sum, d) => sum + d.totalConversions, 0);
  const avgROI = filteredData.length > 0
    ? filteredData.reduce((sum, d) => sum + d.roi, 0) / filteredData.length
    : 0;
  const avgROAS = totalSpend > 0 ? totalSales / totalSpend : 0;

  return (
    <div className="roi-analysis-page">
      <Card 
        title={
          <Space>
            <LineChartOutlined />
            <span>ROI Analysis Dashboard</span>
          </Space>
        }
        extra={
          <Space>
            <RangePicker
              value={dateRange}
              onChange={(dates) => dates && setDateRange(dates as [Dayjs, Dayjs])}
              allowClear={false}
            />
            <Select
              placeholder="All Ad Plans"
              style={{ width: 200 }}
              allowClear
              onChange={(value) => setSelectedAdPlanId(value)}
            >
              {AD_PLANS.map(plan => (
                <Option key={plan.id} value={plan.id}>
                  {plan.name}
                </Option>
              ))}
            </Select>
            <Button icon={<SyncOutlined />} onClick={handleRefresh} loading={loading}>
              Refresh
            </Button>
          </Space>
        }
      >
        <Spin spinning={loading}>
          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col span={6}>
              <Card>
                <Statistic
                  title={
                    <Space>
                      Total Spend
                      <Tooltip title="Total advertising spend in selected period">
                        <InfoCircleOutlined />
                      </Tooltip>
                    </Space>
                  }
                  value={totalSpend}
                  precision={2}
                  prefix={<DollarOutlined style={{ color: '#ff4d4f' }} />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title={
                    <Space>
                      Total Sales
                      <Tooltip title="Total sales attributed to ads">
                        <InfoCircleOutlined />
                      </Tooltip>
                    </Space>
                  }
                  value={totalSales}
                  precision={2}
                  prefix={<DollarOutlined style={{ color: '#52c41a' }} />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title={
                    <Space>
                      Average ROI
                      <Tooltip title="(Sales - Spend) / Spend * 100%">
                        <InfoCircleOutlined />
                      </Tooltip>
                    </Space>
                  }
                  value={avgROI}
                  precision={2}
                  suffix="%"
                  prefix={<PercentageOutlined style={{ color: getROIColor(avgROI) }} />}
                  valueStyle={{ color: getROIColor(avgROI) }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title={
                    <Space>
                      Average ROAS
                      <Tooltip title="Return on Ad Spend: Sales / Spend">
                        <InfoCircleOutlined />
                      </Tooltip>
                    </Space>
                  }
                  value={avgROAS}
                  precision={2}
                  suffix="x"
                  valueStyle={{ color: getROASColor(avgROAS) }}
                />
              </Card>
            </Col>
          </Row>

          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col span={6}>
              <Card>
                <Statistic
                  title="Total Conversions"
                  value={totalConversions}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="Ad Plans Analyzed"
                  value={filteredData.length}
                />
              </Card>
            </Col>
            <Col span={12}>
              <Card title="ROI Performance">
                <div style={{ display: 'flex', gap: 16 }}>
                  {filteredData.slice(0, 3).map(item => (
                    <div key={item.adPlanId} style={{ flex: 1 }}>
                      <Text type="secondary">{item.adPlanName}</Text>
                      <Progress
                        percent={Math.min(item.roi / 5, 100)}
                        format={() => `${item.roi.toFixed(0)}%`}
                        strokeColor={getROIColor(item.roi)}
                        size="small"
                      />
                    </div>
                  ))}
                </div>
              </Card>
            </Col>
          </Row>

          <Divider>ROI Details by Ad Plan</Divider>

          {filteredData.length === 0 ? (
            <Empty description="No ROI data available for selected criteria" />
          ) : (
            <Table
              columns={columns}
              dataSource={filteredData}
              rowKey="adPlanId"
              pagination={false}
              scroll={{ x: 1200 }}
              onRow={(record) => ({
                onClick: () => setSelectedRow(record),
                style: { cursor: 'pointer' },
              })}
            />
          )}
        </Spin>
      </Card>

      {selectedRow && (
        <Card 
          title={`Detailed Analysis: ${selectedRow.adPlanName}`}
          style={{ marginTop: 16 }}
          extra={
            <Button onClick={() => setSelectedRow(null)}>Close</Button>
          }
        >
          <Row gutter={24}>
            <Col span={12}>
              <Descriptions bordered column={1} size="small">
                <Descriptions.Item label="Ad Plan ID">
                  <code>{selectedRow.adPlanId}</code>
                </Descriptions.Item>
                <Descriptions.Item label="Platform">
                  <Tag color={PLATFORM_COLORS[selectedRow.platform]}>{selectedRow.platform}</Tag>
                </Descriptions.Item>
                <Descriptions.Item label="Analysis Period">
                  {dateRange[0].format('YYYY-MM-DD')} ~ {dateRange[1].format('YYYY-MM-DD')}
                </Descriptions.Item>
              </Descriptions>
            </Col>
            <Col span={12}>
              <Descriptions bordered column={1} size="small">
                <Descriptions.Item label="ROI Formula">
                  <Text code>(Sales - Spend) / Spend × 100%</Text>
                </Descriptions.Item>
                <Descriptions.Item label="ROAS Formula">
                  <Text code>Sales / Spend</Text>
                </Descriptions.Item>
                <Descriptions.Item label="ACoS Formula">
                  <Text code>Spend / Sales × 100%</Text>
                </Descriptions.Item>
              </Descriptions>
            </Col>
          </Row>

          <Divider>Performance Breakdown</Divider>

          <Row gutter={16}>
            <Col span={8}>
              <Card size="small">
                <Statistic
                  title="Profit"
                  value={selectedRow.totalSales - selectedRow.totalSpend}
                  precision={2}
                  prefix="$"
                  valueStyle={{ 
                    color: selectedRow.totalSales - selectedRow.totalSpend > 0 ? '#52c41a' : '#ff4d4f' 
                  }}
                />
              </Card>
            </Col>
            <Col span={8}>
              <Card size="small">
                <Statistic
                  title="Conversion Rate"
                  value={selectedRow.clicks > 0 ? (selectedRow.totalConversions / selectedRow.clicks * 100) : 0}
                  precision={2}
                  suffix="%"
                />
              </Card>
            </Col>
            <Col span={8}>
              <Card size="small">
                <Statistic
                  title="Cost per Conversion"
                  value={selectedRow.totalConversions > 0 ? selectedRow.totalSpend / selectedRow.totalConversions : 0}
                  precision={2}
                  prefix="$"
                />
              </Card>
            </Col>
          </Row>
        </Card>
      )}

      <Card style={{ marginTop: 16 }}>
        <Descriptions title="ROI Calculation Standards" bordered column={2}>
          <Descriptions.Item label="ROI Threshold (B2B)">
            <Tag color="red">Minimum 15%</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="ROI Threshold (B2C)">
            <Tag color="orange">Minimum 20%</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="ROAS Target">
            <Tag color="green">≥ 3.0x (Recommended)</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="ACoS Target">
            <Tag color="green">≤ 30% (Recommended)</Tag>
          </Descriptions.Item>
        </Descriptions>
      </Card>
    </div>
  );
};

export default ROIAnalysis;
