import { useMemo, useState } from 'react';
import { Alert, Col, Row, Tabs, Typography } from 'antd';
import { ProCard } from '@ant-design/pro-components';
import { useQuery } from '@tanstack/react-query';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid,
  Tooltip, ResponsiveContainer, Cell,
} from 'recharts';
import type { ColDef } from '@ag-grid-community/core';
import dayjs from 'dayjs';
import PageContainer from '@/components/common/PageContainer';
import SearchForm from '@/components/common/SearchForm';
import DataGrid from '@/components/common/DataGrid';
import { kpiApi, CumulativeRow, KpiSearchParam } from '@/api/kpi';
import {
  COLOR_PRIMARY, COLOR_SUCCESS, COLOR_ERROR, GRAY, SHADOW, RADIUS,
} from '@/theme/tokens';

const { Text } = Typography;

const fmt = (v: number) => v.toLocaleString();
const fmtM = (v: number) => `${(v / 1_000_000).toFixed(1)}M`;

// ────────────────────────────────────────────────────────
// 컬럼 (AGENT / ORG 공통 구조)
// ────────────────────────────────────────────────────────

function buildColumns(levelType: 'AGENT' | 'ORG'): ColDef<CumulativeRow>[] {
  return [
    {
      field: 'entityName',
      headerName: levelType === 'AGENT' ? '설계사명' : '조직명',
      width: 150, pinned: 'left',
    },
    {
      field: 'orgName',
      headerName: '소속 조직',
      width: 140,
      hide: levelType === 'ORG',
    },
    { field: 'settleMonthCount', headerName: '정산 월수', width: 100, type: 'numericColumn', valueFormatter: (p) => fmt(p.value ?? 0) },
    { field: 'cumGross',         headerName: '누적 수수료',  flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value ?? 0) },
    { field: 'cumChargeback',    headerName: '누적 환수',    flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value ?? 0) },
    { field: 'cumIncentive',     headerName: '누적 시책',    flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value ?? 0) },
    {
      headerName: '순수익',
      flex: 1,
      type: 'numericColumn',
      sortable: true,
      valueGetter: (p) => (p.data?.cumGross ?? 0) - (p.data?.cumChargeback ?? 0),
      valueFormatter: (p) => fmt(p.value ?? 0),
      cellStyle: (p) => ({
        color: p.value > 0 ? COLOR_SUCCESS : p.value < 0 ? COLOR_ERROR : GRAY[500],
        fontWeight: 600,
      }),
    },
  ];
}

// ────────────────────────────────────────────────────────
// 합계행 계산
// ────────────────────────────────────────────────────────

function buildPinned(rows: CumulativeRow[]): Partial<CumulativeRow> | undefined {
  if (!rows.length) return undefined;
  return {
    entityName: '합계',
    cumGross: rows.reduce((s, r) => s + r.cumGross, 0),
    cumChargeback: rows.reduce((s, r) => s + r.cumChargeback, 0),
    cumIncentive: rows.reduce((s, r) => s + r.cumIncentive, 0),
    cumNet: rows.reduce((s, r) => s + r.cumNet, 0),
    settleMonthCount: rows.reduce((s, r) => s + r.settleMonthCount, 0),
  };
}

// ────────────────────────────────────────────────────────
// Top10 차트
// ────────────────────────────────────────────────────────

const PALETTE = [
  COLOR_PRIMARY, COLOR_SUCCESS, '#F59E0B', '#8B5CF6', '#06B6D4',
  '#EC4899', '#14B8A6', '#F97316', '#6366F1', '#84CC16',
];

function Top10Chart({ rows }: { rows: CumulativeRow[] }) {
  const chartData = useMemo(() =>
    [...rows]
      .map((r) => ({
        name: r.entityName,
        순수익: Math.round((r.cumGross - r.cumChargeback) / 1_000_000),
      }))
      .sort((a, b) => b.순수익 - a.순수익)
      .slice(0, 10),
  [rows]);

  return (
    <ProCard
      title={<span style={{ fontSize: 15, fontWeight: 700, color: GRAY[800] }}>순수익 상위 10</span>}
      subTitle={<span style={{ fontSize: 13, color: GRAY[400] }}>단위: 백만원 (수수료 - 환수)</span>}
      headerBordered
      style={{
        background: '#ffffff', borderRadius: RADIUS.lg,
        border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm,
        marginBottom: 20,
      }}
    >
      <ResponsiveContainer width="100%" height={240}>
        <BarChart data={chartData} layout="vertical" margin={{ top: 4, right: 24, left: 8, bottom: 0 }}>
          <CartesianGrid strokeDasharray="3 3" stroke={GRAY[100]} horizontal={false} />
          <XAxis type="number" tick={{ fontSize: 11, fill: GRAY[500] }} axisLine={false} tickLine={false}
            tickFormatter={(v) => `${v}M`}
          />
          <YAxis type="category" dataKey="name" width={90} tick={{ fontSize: 11, fill: GRAY[600] }} axisLine={false} tickLine={false} />
          <Tooltip
            contentStyle={{ borderRadius: 12, border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.md, fontSize: 13 }}
            formatter={(v: number) => [`${fmtM(v * 1_000_000)}`, '순수익']}
          />
          <Bar dataKey="순수익" radius={[0, 4, 4, 0]}>
            {chartData.map((_, i) => (
              <Cell key={i} fill={PALETTE[i % PALETTE.length]} />
            ))}
          </Bar>
        </BarChart>
      </ResponsiveContainer>
    </ProCard>
  );
}

// ────────────────────────────────────────────────────────
// 탭 패널
// ────────────────────────────────────────────────────────

interface PanelProps {
  levelType: 'AGENT' | 'ORG';
  params: KpiSearchParam;
}

function CumulativePanel({ levelType, params }: PanelProps) {
  const { data, isLoading, isError } = useQuery({
    queryKey: ['kpi', 'cumulative', levelType, params],
    queryFn: () => kpiApi.cumulative({ ...params, levelType }),
    retry: false,
  });

  const rows = data?.list ?? [];
  const columns = useMemo(() => buildColumns(levelType), [levelType]);
  const pinnedRow = buildPinned(rows);

  return (
    <>
      {isError && (
        <Alert type="warning" showIcon
          message="API 미응답"
          description="/api/kpi/cumulative 를 확인하세요."
          style={{ marginBottom: 16 }}
        />
      )}

      {/* 요약 카드 3개 */}
      <Row gutter={20} style={{ marginBottom: 20 }}>
        {[
          { label: '누적 수수료 합계', value: rows.reduce((s, r) => s + r.cumGross, 0), color: COLOR_PRIMARY, bg: '#EBF3FF' },
          { label: '누적 환수 합계',   value: rows.reduce((s, r) => s + r.cumChargeback, 0), color: COLOR_ERROR,   bg: '#FEF0F1' },
          { label: '누적 순수익',      value: rows.reduce((s, r) => s + r.cumGross - r.cumChargeback, 0), color: COLOR_SUCCESS, bg: '#E8FAF3' },
        ].map((card) => (
          <Col span={8} key={card.label}>
            <div style={{
              background: '#ffffff', borderRadius: RADIUS.lg,
              border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm,
              padding: '20px 24px', display: 'flex', flexDirection: 'column', gap: 8,
            }}>
              <Text style={{ fontSize: 13, fontWeight: 500, color: GRAY[500] }}>{card.label}</Text>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
                <span style={{ fontSize: 30, fontWeight: 700, color: card.color, lineHeight: 1, fontFeatureSettings: "'tnum'" }}>
                  {fmtM(card.value)}
                </span>
                <Text style={{ fontSize: 13, color: GRAY[500] }}>원</Text>
              </div>
            </div>
          </Col>
        ))}
      </Row>

      <Top10Chart rows={rows} />

      <ProCard
        style={{
          background: '#ffffff', borderRadius: RADIUS.lg,
          border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm,
        }}
      >
        <DataGrid<CumulativeRow>
          rows={rows}
          columns={columns}
          loading={isLoading}
          height={500}
          pinnedBottomRow={pinnedRow}
        />
      </ProCard>
    </>
  );
}

// ────────────────────────────────────────────────────────
// 메인
// ────────────────────────────────────────────────────────

export default function KpiCumulative() {
  const [activeTab, setActiveTab] = useState<'AGENT' | 'ORG'>('AGENT');
  const [params, setParams] = useState<KpiSearchParam>({
    toMonth: dayjs().format('YYYYMM'),
    pageSize: 500,
  });

  const handleSearch = (values: Record<string, unknown>) => {
    setParams({
      toMonth: values.toMonth as string | undefined,
      orgId: values.orgId as number | undefined,
      pageSize: 500,
    });
  };

  return (
    <PageContainer
      title="누계 현황"
      description="설계사 / 조직별 누적 수수료 · 환수 · 순수익"
    >
      <SearchForm
        conditions={[
          { type: 'month', name: 'toMonth', label: '기준 월', span: 6 },
        ]}
        onSearch={handleSearch}
        onReset={() => setParams({ toMonth: dayjs().format('YYYYMM'), pageSize: 500 })}
      />

      <Tabs
        activeKey={activeTab}
        onChange={(k) => setActiveTab(k as 'AGENT' | 'ORG')}
        items={[
          { key: 'AGENT', label: '설계사별' },
          { key: 'ORG',   label: '조직별' },
        ]}
        style={{ marginBottom: 16 }}
      />

      <CumulativePanel key={activeTab} levelType={activeTab} params={params} />
    </PageContainer>
  );
}
