import { Area, Bar, Line } from '@ant-design/plots';
import { Col, Row, Table, Tabs, Typography } from 'antd';
import type { ColumnsType } from 'antd/es/table';

import { EmptyState } from '../components/common/EmptyState';
import { SectionCard } from '../components/common/SectionCard';
import {
  buildDomainRanking,
  buildEngagementTrend,
  buildTopLinks,
  buildTrendSeries
} from '../frontend/analytics-model.js';
import { brandColors } from '../frontend/theme';
import type { Analytics } from '../frontend/types';

export interface DashboardChartCopy {
  sent: string;
  delivered: string;
  failed: string;
  opens: string;
  clicks: string;
  deliveryQuality: string;
  engagementAnalysis: string;
  deliveryTrend: string;
  engagementTrend: string;
  domainRanking: string;
  topLinks: string;
  link: string;
  uniqueClicks: string;
  noDeliveryData: string;
  noDomainData: string;
  noEngagementData: string;
}

export default function DashboardCharts({
  analytics,
  copy,
  activeSection,
  onSectionChange
}: {
  analytics: Analytics;
  copy: DashboardChartCopy;
  activeSection: 'delivery' | 'engagement';
  onSectionChange: (section: 'delivery' | 'engagement') => void;
}) {
  const trend = buildTrendSeries(analytics);
  const deliveryTrend = trend.flatMap((item) => [
    { date: item.date, type: copy.sent, value: item.total },
    { date: item.date, type: copy.delivered, value: item.accepted },
    { date: item.date, type: copy.failed, value: item.failed }
  ]);
  const engagementTrend = buildEngagementTrend(analytics).flatMap((item) => [
    { date: item.date, type: copy.opens, value: item.opens },
    { date: item.date, type: copy.clicks, value: item.clicks }
  ]);
  const ranking = buildDomainRanking(analytics).slice(0, 8);
  const topLinks = buildTopLinks(analytics).slice(0, 8);
  const linkColumns: ColumnsType<(typeof topLinks)[number]> = [
    { title: copy.link, dataIndex: 'target', ellipsis: true, render: (value) => <Typography.Text ellipsis={{ tooltip: value }}>{value || '-'}</Typography.Text> },
    { title: copy.uniqueClicks, dataIndex: 'uniqueClicks', width: 110 },
    { title: copy.clicks, dataIndex: 'clicks', width: 90 }
  ];

  return (
    <SectionCard>
      <Tabs
        activeKey={activeSection}
        onChange={(key) => onSectionChange(key === 'engagement' ? 'engagement' : 'delivery')}
        items={[
          {
            key: 'delivery',
            label: copy.deliveryQuality,
            children: (
              <Row gutter={[16, 16]}>
                <Col xs={24} xl={15}>
                  <Typography.Title level={5}>{copy.deliveryTrend}</Typography.Title>
                  {deliveryTrend.some((item) => item.value > 0) ? (
                    <Area
                      data={deliveryTrend}
                      xField="date"
                      yField="value"
                      colorField="type"
                      height={300}
                      shapeField="smooth"
                      scale={{ color: { range: [brandColors.chartPrimary, brandColors.chartSuccess, brandColors.chartDanger] } }}
                      axis={{ x: { title: false }, y: { title: false } }}
                    />
                  ) : <EmptyState description={copy.noDeliveryData} />}
                </Col>
                <Col xs={24} xl={9}>
                  <Typography.Title level={5}>{copy.domainRanking}</Typography.Title>
                  {ranking.length ? (
                    <Bar data={ranking} xField="total" yField="domain" height={300} colorField="domain" legend={false} scale={{ color: { range: [brandColors.chartPrimary] } }} />
                  ) : <EmptyState description={copy.noDomainData} />}
                </Col>
              </Row>
            )
          },
          {
            key: 'engagement',
            label: copy.engagementAnalysis,
            children: (
              <Row gutter={[16, 16]}>
                <Col xs={24} xl={15}>
                  <Typography.Title level={5}>{copy.engagementTrend}</Typography.Title>
                  {engagementTrend.some((item) => item.value > 0) ? (
                    <Line data={engagementTrend} xField="date" yField="value" colorField="type" height={300} scale={{ color: { range: [brandColors.chartPrimary, brandColors.chartSuccess] } }} />
                  ) : <EmptyState description={copy.noEngagementData} />}
                </Col>
                <Col xs={24} xl={9}>
                  <Typography.Title level={5}>{copy.topLinks}</Typography.Title>
                  {topLinks.length ? <Table rowKey="fingerprint" size="small" columns={linkColumns} dataSource={topLinks} pagination={false} scroll={{ x: 440 }} /> : <EmptyState description={copy.noEngagementData} />}
                </Col>
              </Row>
            )
          }
        ]}
      />
    </SectionCard>
  );
}
