import { useState } from 'react';
import { Alert, Col, Form, Input, InputNumber, Modal, Row, Space, Tabs, Tag, Typography, message } from 'antd';
import { ProCard } from '@ant-design/pro-components';
import { useQuery, useQueryClient } from '@tanstack/react-query';
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 PermissionButton from '@/components/common/PermissionButton';
import {
  commissionApi,
  PersistencyRuleRow, PersistencyBonusRow,
  CommissionSearchParam,
} from '@/api/commission';
import { GRAY, RADIUS, SHADOW, COLOR_PRIMARY, COLOR_SUCCESS, COLOR_WARNING } from '@/theme/tokens';

const { Text } = Typography;
const fmt = (v: unknown) => (v as number)?.toLocaleString() ?? '-';
const fmtPct = (v: unknown) => `${((v as number) ?? 0).toFixed(1)}%`;

// 유지보수수당 등급별 색상
const BONUS_TYPE_COLOR: Record<string, string> = {
  '13M': COLOR_PRIMARY,
  '25M': COLOR_SUCCESS,
  '37M': COLOR_WARNING,
  '49M': '#7C3AED',
};

const RULE_COLS: ColDef<PersistencyRuleRow>[] = [
  {
    field: 'bonusType', headerName: '유지 기준', width: 100,
    cellRenderer: (p: { value: string }) => (
      <Tag style={{ background: BONUS_TYPE_COLOR[p.value] ?? GRAY[200], color: '#fff', border: 'none', borderRadius: 4 }}>
        {p.value}
      </Tag>
    ),
  },
  { field: 'minRate',       headerName: '최저유지율(%)', width: 130, type: 'numericColumn', valueFormatter: (p) => fmtPct(p.value) },
  { field: 'bonusAmount',   headerName: '정액지급',     flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'bonusRate',     headerName: '정률지급(%)',  flex: 1, type: 'numericColumn', valueFormatter: (p) => p.value != null ? fmtPct(p.value) : '-' },
  { field: 'effectiveFrom', headerName: '적용시작',     width: 120 },
  { field: 'effectiveTo',   headerName: '적용종료',     width: 120 },
  { field: 'status',        headerName: '상태',         width: 90 },
];

const BONUS_COLS: ColDef<PersistencyBonusRow>[] = [
  { field: 'evaluationMonth', headerName: '평가월',   width: 110, pinned: 'left' },
  { field: 'agentName',       headerName: '설계사',   width: 120 },
  {
    field: 'bonusType', headerName: '기준', width: 90,
    cellRenderer: (p: { value: string }) => (
      <Tag style={{ background: BONUS_TYPE_COLOR[p.value] ?? GRAY[200], color: '#fff', border: 'none', borderRadius: 4 }}>
        {p.value}
      </Tag>
    ),
  },
  { field: 'retentionRate', headerName: '유지율(%)', width: 110, type: 'numericColumn', valueFormatter: (p) => fmtPct(p.value) },
  { field: 'bonusAmount',   headerName: '지급액',   flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'paidYn',        headerName: '지급여부', width: 90 },
  { field: 'status',        headerName: '상태',     width: 90 },
];

export default function PersistencyBonus() {
  const qc = useQueryClient();
  const [bonusParams, setBonusParams] = useState<CommissionSearchParam>({
    settleMonth: dayjs().format('YYYYMM'), pageSize: 200,
  });
  const [ruleModalOpen, setRuleModalOpen] = useState(false);
  const [editingRule, setEditingRule] = useState<PersistencyRuleRow | null>(null);
  const [form] = Form.useForm();

  const { data: rulesData, isLoading: rulesLoading, isError } = useQuery({
    queryKey: ['persistency', 'rules'],
    queryFn: () => commissionApi.persistencyRules(),
    retry: false,
  });

  const { data: bonusData, isLoading: bonusLoading } = useQuery({
    queryKey: ['persistency', 'bonuses', bonusParams],
    queryFn: () => commissionApi.persistencyBonuses(bonusParams),
    retry: false,
  });

  const rules = rulesData?.list ?? [];
  const bonuses = bonusData?.list ?? [];

  // 등급별 통계 카드
  const byType = ['13M', '25M', '37M', '49M'].map((t) => ({
    type: t,
    count: bonuses.filter((b) => b.bonusType === t).length,
    total: bonuses.filter((b) => b.bonusType === t).reduce((s, b) => s + (b.bonusAmount ?? 0), 0),
  }));

  const openCreate = () => { setEditingRule(null); form.resetFields(); setRuleModalOpen(true); };
  const openEdit = (row: PersistencyRuleRow) => { setEditingRule(row); form.setFieldsValue(row); setRuleModalOpen(true); };

  const handleSave = async () => {
    const values = await form.validateFields();
    try {
      if (editingRule) {
        await commissionApi.persistencyRuleUpdate(editingRule.ruleId, values);
      } else {
        await commissionApi.persistencyRuleCreate(values);
      }
      message.success('저장 완료');
      qc.invalidateQueries({ queryKey: ['persistency', 'rules'] });
      setRuleModalOpen(false);
    } catch { /* handled */ }
  };

  const handleDelete = (id: number) => Modal.confirm({
    title: '룰 삭제', onOk: async () => {
      await commissionApi.persistencyRuleDelete(id);
      message.success('삭제 완료');
      qc.invalidateQueries({ queryKey: ['persistency', 'rules'] });
    },
  });

  const pinnedBonus = bonuses.length > 0 ? {
    agentName: '합계',
    bonusAmount: bonuses.reduce((s, b) => s + (b.bonusAmount ?? 0), 0),
  } as Partial<PersistencyBonusRow> : undefined;

  const cardStyle = { background: '#fff', borderRadius: RADIUS.lg, border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm };

  return (
    <PageContainer title="유지보수수당" description="13M/25M/37M/49M 유지율 기반 보너스 관리">
      {isError && (
        <Alert type="warning" showIcon message="API 미응답" description="/api/persistency-bonus 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      <Tabs
        defaultActiveKey="rules"
        items={[
          {
            key: 'rules',
            label: '지급 룰',
            children: (
              <ProCard style={cardStyle}>
                <div style={{ marginBottom: 12 }}>
                  <PermissionButton menuCode="PERSIST_BONUS" permCode="CREATE" type="primary" onClick={openCreate}>
                    + 룰 등록
                  </PermissionButton>
                </div>
                <DataGrid<PersistencyRuleRow>
                  rows={rules}
                  columns={[
                    ...RULE_COLS,
                    {
                      headerName: '액션', width: 160, pinned: 'right',
                      cellRenderer: (p: { data: PersistencyRuleRow }) => (
                        <Space>
                          <PermissionButton menuCode="PERSIST_BONUS" permCode="UPDATE" size="small" onClick={() => openEdit(p.data)}>수정</PermissionButton>
                          <PermissionButton menuCode="PERSIST_BONUS" permCode="DELETE" size="small" danger onClick={() => handleDelete(p.data.ruleId)}>삭제</PermissionButton>
                        </Space>
                      ),
                    },
                  ]}
                  loading={rulesLoading}
                  height={420}
                  rowKey="ruleId"
                />
              </ProCard>
            ),
          },
          {
            key: 'bonuses',
            label: '지급 이력',
            children: (
              <>
                <SearchForm
                  conditions={[
                    { type: 'text',  name: 'agentName',  label: '설계사명', span: 6 },
                    { type: 'month', name: 'settleMonth', label: '평가월',   span: 6 },
                  ]}
                  onSearch={(v) => setBonusParams({ ...v as CommissionSearchParam, pageSize: 200 })}
                  onReset={() => setBonusParams({ settleMonth: dayjs().format('YYYYMM'), pageSize: 200 })}
                />

                {/* 등급별 통계 카드 */}
                <Row gutter={16} style={{ marginBottom: 16 }}>
                  {byType.map((t) => (
                    <Col span={6} key={t.type}>
                      <div style={{
                        ...cardStyle, padding: '16px 20px',
                        borderLeft: `4px solid ${BONUS_TYPE_COLOR[t.type] ?? GRAY[300]}`,
                      }}>
                        <Text style={{ fontSize: 13, color: GRAY[500] }}>{t.type} 유지</Text>
                        <div style={{ fontSize: 20, fontWeight: 700, color: BONUS_TYPE_COLOR[t.type] ?? GRAY[700] }}>
                          {t.count}건
                        </div>
                        <Text style={{ fontSize: 12, color: GRAY[400] }}>{t.total.toLocaleString()}원</Text>
                      </div>
                    </Col>
                  ))}
                </Row>

                <ProCard style={cardStyle}>
                  <DataGrid<PersistencyBonusRow>
                    rows={bonuses}
                    columns={BONUS_COLS}
                    loading={bonusLoading}
                    height={480}
                    rowKey="bonusId"
                    pinnedBottomRow={pinnedBonus}
                  />
                </ProCard>
              </>
            ),
          },
        ]}
      />

      <Modal
        title={editingRule ? '룰 수정' : '룰 등록'}
        open={ruleModalOpen}
        onOk={handleSave}
        onCancel={() => setRuleModalOpen(false)}
        okText="저장" cancelText="취소"
      >
        <Form form={form} layout="vertical">
          <Form.Item name="bonusType" label="유지 기준" rules={[{ required: true }]}>
            <Input placeholder="13M / 25M / 37M / 49M" />
          </Form.Item>
          <Form.Item name="minRate" label="최저유지율(%)" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={0} max={100} step={0.1} />
          </Form.Item>
          <Form.Item name="bonusAmount" label="정액지급(원)">
            <InputNumber style={{ width: '100%' }} min={0} />
          </Form.Item>
          <Form.Item name="bonusRate" label="정률지급(%)">
            <InputNumber style={{ width: '100%' }} min={0} max={100} step={0.01} />
          </Form.Item>
          <Form.Item name="effectiveFrom" label="적용시작" rules={[{ required: true }]}><Input placeholder="YYYY-MM-DD" /></Form.Item>
          <Form.Item name="effectiveTo" label="적용종료"><Input placeholder="YYYY-MM-DD" /></Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
