import { useMemo, useState } from 'react';
import { Alert, Col, Row, Select, 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 PageContainer from '@/components/common/PageContainer';
import SearchForm from '@/components/common/SearchForm';
import DataGrid from '@/components/common/DataGrid';
import { kpiApi, OrgSummaryRow, KpiSearchParam } from '@/api/kpi';
import {
  COLOR_PRIMARY, COLOR_SUCCESS, GRAY, SHADOW, RADIUS,
} from '@/theme/tokens';
import dayjs from 'dayjs';

const { Text } = Typography;

const fmt = (v: number) => v.toLocaleString();

// AG Grid 컬럼
const COLUMNS: ColDef<OrgSummaryRow>[] = [
  { field: 'orgName',      headerName: '조직명',     width: 160, pinned: 'left' },
  { field: 'orgType',      headerName: '조직유형',   width: 110 },
  { field: 'yyyymm',       headerName: '정산월',     width: 110 },
  { field: 'agentCount',   headerName: '설계사수',   width: 100, type: 'numericColumn', valueFormatter: (p) => fmt(p.value ?? 0) },
  { field: 'totalGross',   headerName: '총수수료',   flex: 1,    type: 'numericColumn', valueFormatter: (p) => fmt(p.value ?? 0) },
  { field: 'totalNet',     headerName: '총지급',     flex: 1,    type: 'numericColumn', valueFormatter: (p) => fmt(p.value ?? 0) },
  { field: 'totalRecruit', headerName: '모집',       flex: 1,    type: 'numericColumn', valueFormatter: (p) => fmt(p.value ?? 0) },
  { field: 'totalMaintain',headerName: '유지',       flex: 1,    type: 'numericColumn', valueFormatter: (p) => fmt(p.value ?? 0) },
];

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

export default function KpiOrgSummary() {
  const [params, setParams] = useState<KpiSearchParam>({
    fromMonth: dayjs().format('YYYYMM'),
    toMonth: dayjs().format('YYYYMM'),
    pageSize: 200,
  });
  const [selectedOrg, setSelectedOrg] = useState<number | undefined>();

  const { data, isLoading, isError } = useQuery({
    queryKey: ['kpi', 'org', params],
    queryFn: () => kpiApi.orgSummary({ ...params, orgId: selectedOrg }),
    retry: false,
  });

  const rows = data?.list ?? [];

  // 합계행
  const pinnedRow = rows.length > 0 ? {
    orgName: '합계',
    agentCount: rows.reduce((s, r) => s + r.agentCount, 0),
    totalGross: rows.reduce((s, r) => s + r.totalGross, 0),
    totalNet: rows.reduce((s, r) => s + r.totalNet, 0),
    totalRecruit: rows.reduce((s, r) => s + (r.totalRecruit ?? 0), 0),
    totalMaintain: rows.reduce((s, r) => s + (r.totalMaintain ?? 0), 0),
  } as Partial<OrgSummaryRow> : undefined;

  // 조직 목록 (드롭다운)
  const orgOptions = useMemo(() => {
    const seen = new Set<number>();
    return rows
      .filter((r) => { if (seen.has(r.orgId)) return false; seen.add(r.orgId); return true; })
      .map((r) => ({ value: r.orgId, label: r.orgName }));
  }, [rows]);

  // 차트 — 조직별 총수수료 상위 10개
  const chartData = useMemo(() => {
    const byOrg: Record<number, { orgName: string; totalGross: number }> = {};
    for (const r of rows) {
      if (!byOrg[r.orgId]) byOrg[r.orgId] = { orgName: r.orgName, totalGross: 0 };
      byOrg[r.orgId].totalGross += r.totalGross;
    }
    return Object.values(byOrg)
      .sort((a, b) => b.totalGross - a.totalGross)
      .slice(0, 10)
      .map((x) => ({ name: x.orgName, 수수료: Math.round(x.totalGross / 1_000_000) }));
  }, [rows]);

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

  return (
    <PageContainer
      title="조직별 정산 요약"
      description="조직 단위 월별 수수료 / 설계사 집계"
    >
      <SearchForm
        conditions={[
          { type: 'month', name: 'fromMonth', label: '시작 월', span: 6 },
          { type: 'month', name: 'toMonth',   label: '종료 월', span: 6 },
        ]}
        onSearch={handleSearch}
        onReset={() => {
          setSelectedOrg(undefined);
          setParams({ fromMonth: dayjs().format('YYYYMM'), toMonth: dayjs().format('YYYYMM'), pageSize: 200 });
        }}
      />

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

      <Row gutter={20} style={{ marginBottom: 20 }}>
        {/* 좌측: 조직 필터 Select */}
        <Col span={5}>
          <ProCard
            title={<Text style={{ fontSize: 14, fontWeight: 600, color: GRAY[700] }}>조직 선택</Text>}
            style={{
              background: '#ffffff', borderRadius: RADIUS.lg,
              border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm,
              height: '100%',
            }}
          >
            <Select
              style={{ width: '100%' }}
              placeholder="전체 조직"
              allowClear
              options={orgOptions}
              value={selectedOrg}
              onChange={(v) => setSelectedOrg(v)}
              showSearch
              filterOption={(input, opt) =>
                (opt?.label as string ?? '').toLowerCase().includes(input.toLowerCase())
              }
            />
            <div style={{ marginTop: 12 }}>
              <Text style={{ fontSize: 12, color: GRAY[400] }}>
                조직 선택 후 검색 버튼 클릭
              </Text>
            </div>
          </ProCard>
        </Col>

        {/* 우측: 차트 */}
        <Col span={19}>
          <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,
            }}
          >
            <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} />
                <YAxis type="category" dataKey="name" width={80} 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) => [`${v}백만`, '수수료']}
                />
                <Bar dataKey="수수료" radius={[0, 4, 4, 0]}>
                  {chartData.map((_, i) => (
                    <Cell key={i} fill={PALETTE[i % PALETTE.length]} />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </ProCard>
        </Col>
      </Row>

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