import { useState } from 'react';
import { Alert, Form, Input, InputNumber, Modal, Space, Tabs, 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,
  ConversionRateRow,
  RecognizedLedgerRow,
  CommissionSearchParam,
} from '@/api/commission';
import { GRAY, RADIUS, SHADOW } from '@/theme/tokens';

const fmt = (v: unknown) => (v as number)?.toLocaleString() ?? '-';
const fmtRate = (v: unknown) => v != null ? `${((v as number) * 100).toFixed(2)}%` : '-';

const RULE_COLS: ColDef<ConversionRateRow>[] = [
  { field: 'productName',    headerName: '상품명',   width: 180 },
  { field: 'conversionRate', headerName: '환산율',   width: 110, type: 'numericColumn', valueFormatter: (p) => fmtRate(p.value) },
  { field: 'effectiveFrom',  headerName: '적용시작', width: 120 },
  { field: 'effectiveTo',    headerName: '적용종료', width: 120 },
];

const LEDGER_COLS: ColDef<RecognizedLedgerRow>[] = [
  { field: 'settleMonth',       headerName: '정산월',     width: 110, pinned: 'left' },
  { field: 'agentName',         headerName: '설계사',     width: 130 },
  { field: 'contractNo',        headerName: '계약번호',   width: 140 },
  { field: 'premiumAmount',     headerName: '보험료',     flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'conversionRate',    headerName: '환산율',     width: 110, type: 'numericColumn', valueFormatter: (p) => fmtRate(p.value) },
  { field: 'convertedPremium',  headerName: '환산보험료', flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'recognitionRate',   headerName: '인정율',     width: 110, type: 'numericColumn', valueFormatter: (p) => fmtRate(p.value) },
  { field: 'recognizedAmount',  headerName: '인정실적',   flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'status',            headerName: '상태',       width: 100 },
];

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

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

  const { data: ledgersData, isLoading: ledgersLoading } = useQuery({
    queryKey: ['recognized', 'ledgers', ledgerParams],
    queryFn: () => commissionApi.recognizedLedgers(ledgerParams),
    retry: false,
  });

  const rules = rulesData?.list ?? [];
  const ledgers = ledgersData?.list ?? [];

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

  const handleSave = async () => {
    const values = await form.validateFields();
    try {
      if (editingRule) {
        await commissionApi.conversionRateUpdate(editingRule.rateId, values);
        message.success('수정 완료');
      } else {
        await commissionApi.conversionRateCreate(values);
        message.success('등록 완료');
      }
      qc.invalidateQueries({ queryKey: ['recognized', 'rules'] });
      setRuleModalOpen(false);
    } catch { /* request.ts 처리 */ }
  };

  const handleDelete = (id: number) => Modal.confirm({
    title: '환산율 삭제', content: '삭제하시겠습니까?',
    onOk: async () => {
      await commissionApi.conversionRateDelete(id);
      message.success('삭제 완료');
      qc.invalidateQueries({ queryKey: ['recognized', 'rules'] });
    },
  });

  const pinnedLedger = ledgers.length > 0 ? {
    agentName: '합계',
    premiumAmount: ledgers.reduce((s, r) => s + (r.premiumAmount ?? 0), 0),
    convertedPremium: ledgers.reduce((s, r) => s + (r.convertedPremium ?? 0), 0),
    recognizedAmount: ledgers.reduce((s, r) => s + (r.recognizedAmount ?? 0), 0),
  } as Partial<RecognizedLedgerRow> : undefined;

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

  return (
    <PageContainer title="인정실적" description="환산율 관리 및 인정실적원장 조회">
      {rulesError && (
        <Alert type="warning" showIcon message="API 미응답" description="/api/recognized-performances 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      <Tabs
        defaultActiveKey="rules"
        items={[
          {
            key: 'rules',
            label: '환산율',
            children: (
              <ProCard style={cardStyle}>
                <div style={{ marginBottom: 12 }}>
                  <PermissionButton menuCode="RECOGNIZED_PERF" permCode="CREATE" type="primary" onClick={openCreate}>
                    + 환산율 등록
                  </PermissionButton>
                </div>
                <DataGrid<ConversionRateRow>
                  rows={rules}
                  columns={[
                    ...RULE_COLS,
                    {
                      headerName: '액션', width: 160, pinned: 'right',
                      cellRenderer: (p: { data: ConversionRateRow }) => (
                        <Space>
                          <PermissionButton menuCode="RECOGNIZED_PERF" permCode="UPDATE" size="small" onClick={() => openEdit(p.data)}>수정</PermissionButton>
                          <PermissionButton menuCode="RECOGNIZED_PERF" permCode="DELETE" size="small" danger onClick={() => handleDelete(p.data.rateId)}>삭제</PermissionButton>
                        </Space>
                      ),
                    },
                  ]}
                  loading={rulesLoading}
                  height={520}
                  rowKey="rateId"
                />
              </ProCard>
            ),
          },
          {
            key: 'ledgers',
            label: '인정실적원장',
            children: (
              <>
                <SearchForm
                  conditions={[
                    { type: 'text',  name: 'agentName',  label: '설계사명', span: 6 },
                    { type: 'month', name: 'settleMonth', label: '정산월',   span: 6 },
                  ]}
                  onSearch={(v) => setLedgerParams({ ...v as CommissionSearchParam, pageSize: 200 })}
                  onReset={() => setLedgerParams({ settleMonth: dayjs().format('YYYYMM'), pageSize: 200 })}
                />
                <ProCard style={cardStyle}>
                  <DataGrid<RecognizedLedgerRow>
                    rows={ledgers}
                    columns={LEDGER_COLS}
                    loading={ledgersLoading}
                    height={520}
                    rowKey="ledgerId"
                    pinnedBottomRow={pinnedLedger}
                  />
                </ProCard>
              </>
            ),
          },
        ]}
      />

      <Modal
        title={editingRule ? '환산율 수정' : '환산율 등록'}
        open={ruleModalOpen}
        onOk={handleSave}
        onCancel={() => setRuleModalOpen(false)}
        okText="저장"
        cancelText="취소"
      >
        <Form form={form} layout="vertical">
          <Form.Item name="productId" label="상품ID" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={1} />
          </Form.Item>
          <Form.Item name="conversionRate" label="환산율(0~1)" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={0} max={1} step={0.0001} />
          </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>
  );
}
