import { useState, useEffect, useCallback } from 'react';
import { Card, Row, Col, Statistic, Table, Segmented, Alert, Skeleton, Tag } from 'antd';
import {
  EyeOutlined,
  ThunderboltOutlined,
  PercentageOutlined,
  TeamOutlined,
} from '@ant-design/icons';
import { useOutletContext } from 'react-router-dom';
import { api } from '@/lib/api';
import type { AppOutletContext } from '@/types/api';
import FeatureGate from '@/components/FeatureGate';
import { getErrorMessage } from '@/utils/getErrorMessage';

interface DailyData {
  date: string;
  impressions: number;
  clicks: number;
}

interface TopAd {
  id: number;
  title: string;
  type: string;
  impressions: number;
  clicks: number;
  ctr: number;
}

interface PlacementData {
  placement: string;
  label: string;
  adCount: number;
  impressions: number;
  clicks: number;
}

interface AggregateAnalytics {
  daily: DailyData[];
  totals: {
    impressions: number;
    clicks: number;
    uniqueSessions: number;
    ctr: number;
  };
  topAds: TopAd[];
  byPlacement: PlacementData[];
}

const TYPE_COLORS: Record<string, string> = {
  system: 'blue',
  payment_subscribe: 'purple',
  payment_donate: 'green',
  payment_shop: 'orange',
  custom: 'default',
};

const TYPE_LABELS: Record<string, string> = {
  system: 'System',
  payment_subscribe: 'Subscribe',
  payment_donate: 'Donate',
  payment_shop: 'Shop',
  custom: 'Custom',
};

export default function AdAnalyticsDashboardPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [data, setData] = useState<AggregateAnalytics | null>(null);
  const [days, setDays] = useState<number>(30);

  useEffect(() => {
    setPageHeader({
      title: 'Ad Analytics',
      subtitle: 'Aggregate performance across all gallery ads',
    });
    return () => setPageHeader(null);
  }, [setPageHeader]);

  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const { data: result } = await api.get('/gallery-ads/admin/analytics/aggregate', {
        params: { days },
      });
      setData(result);
    } catch (err: unknown) {
      setError(getErrorMessage(err, 'Failed to load analytics'));
    } finally {
      setLoading(false);
    }
  }, [days]);

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

  const topAdsColumns = [
    {
      title: 'Rank',
      key: 'rank',
      width: 60,
      render: (_: unknown, __: unknown, index: number) => (
        <span style={{ fontSize: 16, fontWeight: 'bold', color: index < 3 ? '#faad14' : '#999' }}>
          #{index + 1}
        </span>
      ),
    },
    {
      title: 'Title',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true,
    },
    {
      title: 'Type',
      dataIndex: 'type',
      key: 'type',
      width: 110,
      render: (type: string) => (
        <Tag color={TYPE_COLORS[type] || 'default'}>{TYPE_LABELS[type] || type}</Tag>
      ),
    },
    {
      title: 'Impressions',
      dataIndex: 'impressions',
      key: 'impressions',
      width: 110,
      render: (v: number) => v.toLocaleString(),
    },
    {
      title: 'Clicks',
      dataIndex: 'clicks',
      key: 'clicks',
      width: 80,
      render: (v: number) => v.toLocaleString(),
    },
    {
      title: 'CTR',
      dataIndex: 'ctr',
      key: 'ctr',
      width: 70,
      render: (v: number) => `${v}%`,
    },
  ];

  const placementColumns = [
    {
      title: 'Placement',
      dataIndex: 'label',
      key: 'label',
    },
    {
      title: '# Ads',
      dataIndex: 'adCount',
      key: 'adCount',
      width: 80,
    },
    {
      title: 'Impressions',
      dataIndex: 'impressions',
      key: 'impressions',
      width: 110,
      render: (v: number) => v.toLocaleString(),
    },
    {
      title: 'Clicks',
      dataIndex: 'clicks',
      key: 'clicks',
      width: 80,
      render: (v: number) => v.toLocaleString(),
    },
  ];

  const dailyColumns = [
    { title: 'Date', dataIndex: 'date', key: 'date' },
    {
      title: 'Impressions',
      dataIndex: 'impressions',
      key: 'impressions',
      render: (v: number) => v.toLocaleString(),
    },
    {
      title: 'Clicks',
      dataIndex: 'clicks',
      key: 'clicks',
      render: (v: number) => v.toLocaleString(),
    },
    {
      title: 'CTR',
      key: 'ctr',
      render: (_: unknown, row: DailyData) =>
        row.impressions > 0
          ? `${((row.clicks / row.impressions) * 100).toFixed(1)}%`
          : '-',
    },
  ];

  return (
    <FeatureGate feature="enableGalleryAds">
      <div style={{ marginBottom: 16 }}>
        <Segmented
          value={days}
          onChange={(v) => setDays(v as number)}
          options={[
            { label: '7d', value: 7 },
            { label: '30d', value: 30 },
            { label: '90d', value: 90 },
          ]}
        />
      </div>

      {error && (
        <Alert
          type="error"
          message={error}
          showIcon
          closable
          style={{ marginBottom: 16 }}
        />
      )}

      {loading ? (
        <>
          <Row gutter={16} style={{ marginBottom: 24 }}>
            {[1, 2, 3, 4].map((i) => (
              <Col xs={12} sm={6} key={i}>
                <Card size="small"><Skeleton active paragraph={false} /></Card>
              </Col>
            ))}
          </Row>
          <Skeleton active />
        </>
      ) : data ? (
        <>
          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col xs={12} sm={6}>
              <Card size="small">
                <Statistic
                  title="Total Impressions"
                  value={data.totals.impressions}
                  prefix={<EyeOutlined />}
                />
              </Card>
            </Col>
            <Col xs={12} sm={6}>
              <Card size="small">
                <Statistic
                  title="Total Clicks"
                  value={data.totals.clicks}
                  prefix={<ThunderboltOutlined />}
                />
              </Card>
            </Col>
            <Col xs={12} sm={6}>
              <Card size="small">
                <Statistic
                  title="Overall CTR"
                  value={data.totals.ctr}
                  suffix="%"
                  prefix={<PercentageOutlined />}
                />
              </Card>
            </Col>
            <Col xs={12} sm={6}>
              <Card size="small">
                <Statistic
                  title="Unique Sessions"
                  value={data.totals.uniqueSessions}
                  prefix={<TeamOutlined />}
                />
              </Card>
            </Col>
          </Row>

          <Card title="Top Performing Ads" size="small" style={{ marginBottom: 24 }}>
            <Table
              dataSource={data.topAds}
              columns={topAdsColumns}
              scroll={{ x: 'max-content' }}
              rowKey="id"
              pagination={false}
              size="small"
            />
          </Card>

          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Card title="Performance by Placement" size="small" style={{ marginBottom: 24 }}>
                <Table
                  dataSource={data.byPlacement}
                  columns={placementColumns}
                  scroll={{ x: 'max-content' }}
                  rowKey="placement"
                  pagination={false}
                  size="small"
                />
              </Card>
            </Col>
            <Col xs={24} md={12}>
              <Card title={`Daily Breakdown (Last ${days} Days)`} size="small" style={{ marginBottom: 24 }}>
                {data.daily.length === 0 ? (
                  <div style={{ textAlign: 'center', color: '#999', padding: 24 }}>
                    No data recorded yet
                  </div>
                ) : (
                  <Table
                    dataSource={data.daily}
                    columns={dailyColumns}
                    scroll={{ x: 'max-content', y: 400 }}
                    rowKey="date"
                    pagination={false}
                    size="small"
                  />
                )}
              </Card>
            </Col>
          </Row>
        </>
      ) : null}
    </FeatureGate>
  );
}
