import { useState } from 'react';
import { Alert, Form, Input, InputNumber, Modal, Select, Space, Tabs, message } from 'antd';
import { ProCard } from '@ant-design/pro-components';
import { useQuery, useMutation, 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,
  AwardRuleRow,
  AwardLedgerRow,
  AwardClawbackReq,
  CommissionSearchParam,
} from '@/api/commission';
import { GRAY, RADIUS, SHADOW } from '@/theme/tokens';

const fmt = (v: unknown) => (v as number)?.toLocaleString() ?? '-';

const AWARD_TYPE_OPTIONS = [
  { value: 'NEW_RECRUIT', label: '신인도입' },
  { value: 'CORPORATE',   label: '법인' },
  { value: 'RETENTION',   label: '유지율' },
  { value: 'PERFORMANCE', label: '실적' },
];

const RULE_COLS: ColDef<AwardRuleRow>[] = [
  { field: 'awardType',        headerName: '시상유형',   width: 130 },
  { field: 'calcType',         headerName: '계산방식',   width: 110 },
  { field: 'thresholdAmount',  headerName: '기준실적',   flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'awardRate',        headerName: '시상율',     width: 110, type: 'numericColumn' },
  { field: 'awardFixed',       headerName: '시상정액',   flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'effectiveFrom',    headerName: '적용시작',   width: 120 },
  { field: 'effectiveTo',      headerName: '적용종료',   width: 120 },
];

const LEDGER_COLS: ColDef<AwardLedgerRow>[] = [
  { field: 'settleMonth',    headerName: '정산월',   width: 110, pinned: 'left' },
  { field: 'agentName',      headerName: '설계사',   width: 130 },
  { field: 'awardType',      headerName: '시상유형', width: 120 },
  { field: 'baseAmount',     headerName: '기준실적', flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'awardAmount',    headerName: '시상금',   flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'clawbackAmount', headerName: '환수액',   flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'netAmount',      headerName: '실지급',   flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'status',         headerName: '상태',     width: 110 },
];

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

  const [clawbackTarget, setClawbackTarget] = useState<AwardLedgerRow | null>(null);
  const [clawbackForm] = Form.useForm();

  const clawbackMutation = useMutation({
    mutationFn: ({ ledgerId, body }: { ledgerId: number; body: AwardClawbackReq }) =>
      commissionApi.awardLedgerClawback(ledgerId, body),
    onSuccess: () => {
      message.success('환수처리 완료');
      qc.invalidateQueries({ queryKey: ['award', 'ledgers'] });
      setClawbackTarget(null);
      clawbackForm.resetFields();
    },
  });

  const handleClawbackOk = async () => {
    const values = await clawbackForm.validateFields();
    clawbackMutation.mutate({ ledgerId: clawbackTarget!.ledgerId, body: values });
  };

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

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

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

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

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

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

  const pinnedLedger = ledgers.length > 0 ? {
    agentName: '합계',
    baseAmount:     ledgers.reduce((s, r) => s + (r.baseAmount ?? 0), 0),
    awardAmount:    ledgers.reduce((s, r) => s + (r.awardAmount ?? 0), 0),
    clawbackAmount: ledgers.reduce((s, r) => s + (r.clawbackAmount ?? 0), 0),
    netAmount:      ledgers.reduce((s, r) => s + (r.netAmount ?? 0), 0),
  } as Partial<AwardLedgerRow> : 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/awards 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      <Tabs
        defaultActiveKey="rules"
        items={[
          {
            key: 'rules',
            label: '시상 룰',
            children: (
              <ProCard style={cardStyle}>
                <div style={{ marginBottom: 12 }}>
                  <PermissionButton menuCode="AWARD" permCode="CREATE" type="primary" onClick={openCreate}>
                    + 룰 등록
                  </PermissionButton>
                </div>
                <DataGrid<AwardRuleRow>
                  rows={rules}
                  columns={[
                    ...RULE_COLS,
                    {
                      headerName: '액션', width: 160, pinned: 'right',
                      cellRenderer: (p: { data: AwardRuleRow }) => (
                        <Space>
                          <PermissionButton menuCode="AWARD" permCode="UPDATE" size="small" onClick={() => openEdit(p.data)}>수정</PermissionButton>
                          <PermissionButton menuCode="AWARD" permCode="DELETE" size="small" danger onClick={() => handleDelete(p.data.ruleId)}>삭제</PermissionButton>
                        </Space>
                      ),
                    },
                  ]}
                  loading={rulesLoading}
                  height={520}
                  rowKey="ruleId"
                />
              </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<AwardLedgerRow>
                    rows={ledgers}
                    columns={[
                      ...LEDGER_COLS,
                      {
                        headerName: '액션', width: 110, pinned: 'right',
                        cellRenderer: (p: { data: AwardLedgerRow }) => (
                          <PermissionButton
                            menuCode="AWARD"
                            permCode="UPDATE"
                            size="small"
                            disabled={p.data?.status === 'CANCELLED'}
                            onClick={() => { setClawbackTarget(p.data); clawbackForm.resetFields(); }}
                          >
                            환수처리
                          </PermissionButton>
                        ),
                      },
                    ]}
                    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="awardType" label="시상유형" rules={[{ required: true }]}>
            <Select options={AWARD_TYPE_OPTIONS} />
          </Form.Item>
          <Form.Item name="calcType" label="계산방식" rules={[{ required: true }]}>
            <Select options={[{ value: 'RATE', label: '정률' }, { value: 'FIXED', label: '정액' }]} />
          </Form.Item>
          <Form.Item name="thresholdAmount" label="기준실적(이상)">
            <InputNumber style={{ width: '100%' }} min={0} />
          </Form.Item>
          <Form.Item name="awardRate" label="시상율(0~1)">
            <InputNumber style={{ width: '100%' }} min={0} max={1} step={0.0001} />
          </Form.Item>
          <Form.Item name="awardFixed" label="시상정액">
            <InputNumber style={{ width: '100%' }} min={0} />
          </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>

      <Modal
        title="환수처리"
        open={!!clawbackTarget}
        onOk={handleClawbackOk}
        onCancel={() => { setClawbackTarget(null); clawbackForm.resetFields(); }}
        okText="처리"
        cancelText="취소"
        confirmLoading={clawbackMutation.isPending}
      >
        {clawbackTarget && (
          <div style={{ marginBottom: 12, color: '#666', fontSize: 13 }}>
            {clawbackTarget.agentName} / {clawbackTarget.settleMonth} / 시상금 {fmt(clawbackTarget.awardAmount)}
          </div>
        )}
        <Form form={clawbackForm} layout="vertical">
          <Form.Item
            name="clawbackAmount"
            label="환수액"
            rules={[{ required: true, message: '환수액을 입력하세요' }]}
          >
            <InputNumber style={{ width: '100%' }} min={0} placeholder="환수할 금액" />
          </Form.Item>
          <Form.Item
            name="reason"
            label="사유"
            rules={[{ required: true, message: '사유를 입력하세요' }]}
          >
            <Input.TextArea rows={3} placeholder="환수 사유를 입력하세요" />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
