import { useState } from 'react';
import { Alert, Form, Input, InputNumber, Modal, 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 { operationApi, ReserveFundRow } from '@/api/operation';
import { GRAY, RADIUS, SHADOW } from '@/theme/tokens';

const fmt = (v: unknown) => (v as number)?.toLocaleString() ?? '-';
const cardStyle = { background: '#fff', borderRadius: RADIUS.lg, border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm };

const COLS: ColDef<ReserveFundRow>[] = [
  { field: 'settleMonth', headerName: '정산월',   width: 110, pinned: 'left' },
  { field: 'agentName',   headerName: '설계사',   width: 130 },
  { field: 'reserveIn',   headerName: '적립액',   flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'reserveOut',  headerName: '인출액',   flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'balance',     headerName: '잔액',     flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'createdAt',   headerName: '등록일',   width: 130 },
];

export default function ReserveFund() {
  const qc = useQueryClient();
  const [searchParams, setSearchParams] = useState<{ settleMonth?: string; agentName?: string }>({
    settleMonth: dayjs().format('YYYYMM'),
  });
  const [modalOpen, setModalOpen] = useState(false);
  const [form] = Form.useForm();

  const { data, isLoading, isError } = useQuery({
    queryKey: ['reserve-fund', 'list', searchParams],
    queryFn: () => operationApi.reserveFundList(searchParams),
    retry: false,
  });

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

  const pinnedRow = rows.length > 0 ? {
    agentName: '합계',
    reserveIn:  rows.reduce((s, r) => s + (r.reserveIn ?? 0), 0),
    reserveOut: rows.reduce((s, r) => s + (r.reserveOut ?? 0), 0),
    balance:    rows.reduce((s, r) => s + (r.balance ?? 0), 0),
  } as Partial<ReserveFundRow> : undefined;

  const handleUpsert = async () => {
    const values = await form.validateFields();
    try {
      await operationApi.reserveFundUpsert(values);
      message.success('등록/수정 완료');
      qc.invalidateQueries({ queryKey: ['reserve-fund', 'list'] });
      setModalOpen(false);
      form.resetFields();
    } catch { /* request.ts 처리 */ }
  };

  return (
    <PageContainer title="적립금" description="환수 대비 수수료 적립금 관리">
      {isError && (
        <Alert type="warning" showIcon message="API 미응답" description="/api/reserve-funds 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      <SearchForm
        conditions={[
          { type: 'month', name: 'settleMonth', label: '정산월',   span: 6 },
          { type: 'text',  name: 'agentName',   label: '설계사명', span: 6 },
        ]}
        initialValues={{ settleMonth: dayjs() }}
        onSearch={(v) => setSearchParams({ settleMonth: v.settleMonth as string, agentName: v.agentName as string })}
        onReset={() => setSearchParams({ settleMonth: dayjs().format('YYYYMM') })}
      />

      <ProCard style={cardStyle}>
        <div style={{ marginBottom: 12 }}>
          <PermissionButton menuCode="RESERVE_FUND" permCode="CREATE" type="primary" onClick={() => { form.resetFields(); setModalOpen(true); }}>
            + 적립금 등록
          </PermissionButton>
        </div>
        <DataGrid<ReserveFundRow>
          rows={rows}
          columns={COLS}
          loading={isLoading}
          height={520}
          rowKey="reserveId"
          pinnedBottomRow={pinnedRow}
        />
      </ProCard>

      <Modal
        title="적립금 등록(upsert)"
        open={modalOpen}
        onOk={handleUpsert}
        onCancel={() => setModalOpen(false)}
        okText="저장"
        cancelText="취소"
      >
        <Form form={form} layout="vertical">
          <Form.Item name="agentId" label="설계사ID" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={1} />
          </Form.Item>
          <Form.Item name="settleMonth" label="정산월(YYYYMM)" rules={[{ required: true }]}>
            <Input placeholder={dayjs().format('YYYYMM')} />
          </Form.Item>
          <Form.Item name="reserveIn" label="적립액" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={0} />
          </Form.Item>
          <Form.Item name="reserveOut" label="인출액" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={0} />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
