import { useState } from 'react';
import { Alert, Descriptions, Drawer, Form, Input, InputNumber, Modal, Select, Space, 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 PageContainer from '@/components/common/PageContainer';
import SearchForm from '@/components/common/SearchForm';
import DataGrid from '@/components/common/DataGrid';
import PermissionButton from '@/components/common/PermissionButton';
import {
  advancePaymentApi,
  AdvancePaymentRow,
  AdvancePaymentSaveReq,
  AdvanceRecoveryRow,
  AdvancePaymentSearchParam,
} from '@/api/settle';
import { GRAY, RADIUS, SHADOW } from '@/theme/tokens';

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

const STATUS_OPTIONS = [
  { value: 'OUTSTANDING', label: '미상환' },
  { value: 'PARTIAL',     label: '부분상환' },
  { value: 'CLEARED',     label: '완료' },
  { value: 'WAIVED',      label: '면제' },
];

const LIST_COLS: ColDef<AdvancePaymentRow>[] = [
  { field: 'advanceMonth',     headerName: '선지급월', width: 110, pinned: 'left' },
  { field: 'agentName',        headerName: '설계사',   width: 130 },
  { field: 'principalAmount',  headerName: '원금',     flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'recoveredAmount',  headerName: '회수액',   flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'balance',          headerName: '잔액',     flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'status',           headerName: '상태',     width: 110 },
  { field: 'memo',             headerName: '메모',     flex: 1 },
];

const RECOVERY_COLS: ColDef<AdvanceRecoveryRow>[] = [
  { field: 'settleMonth',    headerName: '정산월',   width: 120 },
  { field: 'recoveryAmount', headerName: '상계액',   flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
];

export default function AdvancePayment() {
  const qc = useQueryClient();
  const [searchParams, setSearchParams] = useState<AdvancePaymentSearchParam>({ pageSize: 200 });
  const [createOpen, setCreateOpen] = useState(false);
  const [drawerTarget, setDrawerTarget] = useState<AdvancePaymentRow | null>(null);
  const [form] = Form.useForm<AdvancePaymentSaveReq>();

  const { data: listData, isLoading, isError } = useQuery({
    queryKey: ['advancePayment', 'list', searchParams],
    queryFn: () => advancePaymentApi.list(searchParams),
    retry: false,
  });

  const { data: recoveries = [], isLoading: recLoading } = useQuery({
    queryKey: ['advancePayment', 'recoveries', drawerTarget?.advanceId],
    queryFn: () => advancePaymentApi.recoveries(drawerTarget!.advanceId),
    enabled: !!drawerTarget,
  });

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

  const createMutation = useMutation({
    mutationFn: (body: AdvancePaymentSaveReq) => advancePaymentApi.create(body),
    onSuccess: () => {
      message.success('등록 완료');
      qc.invalidateQueries({ queryKey: ['advancePayment', 'list'] });
      setCreateOpen(false);
      form.resetFields();
    },
  });

  const waiveMutation = useMutation({
    mutationFn: (advanceId: number) => advancePaymentApi.waive(advanceId),
    onSuccess: () => {
      message.success('면제 처리 완료');
      qc.invalidateQueries({ queryKey: ['advancePayment', 'list'] });
    },
  });

  const handleCreate = async () => {
    const values = await form.validateFields();
    createMutation.mutate(values);
  };

  const handleWaive = (row: AdvancePaymentRow) => Modal.confirm({
    title: '면제 처리',
    content: `${row.agentName} 의 선지급 잔액 ${fmt(row.balance)}원을 면제하시겠습니까?`,
    onOk: () => waiveMutation.mutateAsync(row.advanceId),
  });

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

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

  return (
    <PageContainer title="선지급정산" description="선지급금 등록·회수·잔액 관리">
      {isError && (
        <Alert type="warning" showIcon message="API 미응답" description="/api/advance-payments 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      <SearchForm
        conditions={[
          { type: 'text',   name: 'agentName',    label: '설계사명', span: 6 },
          { type: 'month',  name: 'advanceMonth',  label: '선지급월', span: 6 },
          { type: 'code', name: 'status', label: '상태', span: 6, groupCode: 'ADVANCE_STATUS' },
        ]}
        onSearch={(v) => setSearchParams({ ...v as AdvancePaymentSearchParam, pageSize: 200 })}
        onReset={() => setSearchParams({ pageSize: 200 })}
      />

      <ProCard style={cardStyle}>
        <div style={{ marginBottom: 12 }}>
          <PermissionButton menuCode="ADVANCE_PAYMENT" permCode="CREATE" type="primary" onClick={() => setCreateOpen(true)}>
            + 선지급 등록
          </PermissionButton>
        </div>
        <DataGrid<AdvancePaymentRow>
          rows={rows}
          columns={[
            ...LIST_COLS,
            {
              headerName: '액션', width: 180, pinned: 'right',
              cellRenderer: (p: { data: AdvancePaymentRow }) => (
                <Space>
                  <PermissionButton
                    menuCode="ADVANCE_PAYMENT" permCode="READ" size="small"
                    onClick={() => setDrawerTarget(p.data)}
                  >
                    상계내역
                  </PermissionButton>
                  <PermissionButton
                    menuCode="ADVANCE_PAYMENT" permCode="UPDATE" size="small"
                    disabled={p.data.status === 'CLEARED' || p.data.status === 'WAIVED'}
                    onClick={() => handleWaive(p.data)}
                  >
                    면제
                  </PermissionButton>
                </Space>
              ),
            },
          ]}
          loading={isLoading}
          height={520}
          rowKey="advanceId"
          pinnedBottomRow={pinnedRow}
        />
      </ProCard>

      {/* 등록 모달 */}
      <Modal
        title="선지급 등록"
        open={createOpen}
        onOk={handleCreate}
        onCancel={() => { setCreateOpen(false); form.resetFields(); }}
        okText="등록"
        cancelText="취소"
        confirmLoading={createMutation.isPending}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="agentId" label="설계사 ID" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={1} placeholder="설계사 ID" />
          </Form.Item>
          <Form.Item name="advanceMonth" label="선지급월(YYYYMM)" rules={[{ required: true }]}>
            <Input placeholder="예: 202601" />
          </Form.Item>
          <Form.Item name="principalAmount" label="선지급 원금" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={1} />
          </Form.Item>
          <Form.Item name="memo" label="메모">
            <Input.TextArea rows={2} />
          </Form.Item>
        </Form>
      </Modal>

      {/* 상계내역 Drawer */}
      <Drawer
        title={drawerTarget ? `상계내역 — ${drawerTarget.agentName} / ${drawerTarget.advanceMonth}` : '상계내역'}
        open={!!drawerTarget}
        onClose={() => setDrawerTarget(null)}
        width={480}
      >
        {drawerTarget && (
          <>
            <Descriptions size="small" column={2} bordered style={{ marginBottom: 16 }}>
              <Descriptions.Item label="원금">{fmt(drawerTarget.principalAmount)}</Descriptions.Item>
              <Descriptions.Item label="회수액">{fmt(drawerTarget.recoveredAmount)}</Descriptions.Item>
              <Descriptions.Item label="잔액">{fmt(drawerTarget.balance)}</Descriptions.Item>
              <Descriptions.Item label="상태">{drawerTarget.status}</Descriptions.Item>
            </Descriptions>
            <DataGrid<AdvanceRecoveryRow>
              rows={recoveries}
              columns={RECOVERY_COLS}
              loading={recLoading}
              height={300}
              rowKey="recoveryId"
            />
          </>
        )}
      </Drawer>
    </PageContainer>
  );
}
