import { useState } from 'react';
import { Alert, Descriptions, Drawer, Form, Input, InputNumber, Modal, 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 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 {
  carrierReconInApi,
  CarrierReconInRow,
  CarrierReconInSaveReq,
  ReconciliationVarianceRow,
  CarrierReconSearchParam,
} from '@/api/settle';
import { GRAY, RADIUS, SHADOW } from '@/theme/tokens';

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

const STATUS_OPTIONS = [
  { value: 'RECEIVED', label: '입수' },
  { value: 'MATCHED',  label: '일치' },
  { value: 'VARIANCE', label: '차이' },
  { value: 'APPROVED', label: '승인' },
];

const LIST_COLS: ColDef<CarrierReconInRow>[] = [
  { field: 'settleMonth',    headerName: '정산월',   width: 110, pinned: 'left' },
  { field: 'companyName',    headerName: '보험사',   width: 130 },
  { field: 'fileName',       headerName: '파일명',   flex: 1 },
  { field: 'recordCount',    headerName: '건수',     width: 80,  type: 'numericColumn' },
  { field: 'reportedTotal',  headerName: '보고합계', flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'systemTotal',    headerName: '시스템합계', flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'varianceAmount', headerName: '차이금액', flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'status',         headerName: '상태',     width: 110 },
];

const VARIANCE_COLS: ColDef<ReconciliationVarianceRow>[] = [
  { field: 'policyNo',        headerName: '증권번호',   width: 140 },
  { field: 'expectedAmount',  headerName: '시스템금액', flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'reportedAmount',  headerName: '보고금액',   flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'varianceReason',  headerName: '차이사유',   flex: 1 },
];

export default function CarrierReconIn() {
  const qc = useQueryClient();
  const [searchParams, setSearchParams] = useState<CarrierReconSearchParam>({
    settleMonth: dayjs().format('YYYYMM'), pageSize: 200,
  });
  const [createOpen, setCreateOpen] = useState(false);
  const [drawerTarget, setDrawerTarget] = useState<CarrierReconInRow | null>(null);
  const [form] = Form.useForm<CarrierReconInSaveReq>();

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

  const { data: variances = [], isLoading: varLoading } = useQuery({
    queryKey: ['carrierReconIn', 'variances', drawerTarget?.reconId],
    queryFn: () => carrierReconInApi.variances(drawerTarget!.reconId),
    enabled: !!drawerTarget,
  });

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

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

  const reconcileMutation = useMutation({
    mutationFn: (reconId: number) => carrierReconInApi.reconcile(reconId),
    onSuccess: () => {
      message.success('대사 실행 완료');
      qc.invalidateQueries({ queryKey: ['carrierReconIn', 'list'] });
    },
  });

  const approveMutation = useMutation({
    mutationFn: (reconId: number) => carrierReconInApi.approve(reconId),
    onSuccess: () => {
      message.success('승인 완료');
      qc.invalidateQueries({ queryKey: ['carrierReconIn', 'list'] });
    },
  });

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

  const handleReconcile = (row: CarrierReconInRow) => Modal.confirm({
    title: '대사 실행',
    content: `${row.companyName} / ${row.settleMonth} 대사를 실행하시겠습니까?`,
    onOk: () => reconcileMutation.mutateAsync(row.reconId),
  });

  const handleApprove = (row: CarrierReconInRow) => Modal.confirm({
    title: '승인',
    content: '해당 대사 결과를 승인하시겠습니까?',
    onOk: () => approveMutation.mutateAsync(row.reconId),
  });

  const pinnedRow = rows.length > 0 ? {
    companyName:   '합계',
    reportedTotal:  rows.reduce((s, r) => s + (r.reportedTotal ?? 0), 0),
    systemTotal:    rows.reduce((s, r) => s + (r.systemTotal ?? 0), 0),
    varianceAmount: rows.reduce((s, r) => s + (r.varianceAmount ?? 0), 0),
  } as Partial<CarrierReconInRow> : undefined;

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

  return (
    <PageContainer title="정산대사입수" description="보험사 통보 정산자료 vs GA 원장 대사">
      {isError && (
        <Alert type="warning" showIcon message="API 미응답" description="/api/carrier-recon-in 을 확인하세요." style={{ marginBottom: 16 }} />
      )}

      <SearchForm
        conditions={[
          { type: 'month',  name: 'settleMonth', label: '정산월', span: 6 },
          { type: 'code', name: 'status', label: '상태', span: 6, groupCode: 'RECON_IN_STATUS' },
        ]}
        onSearch={(v) => setSearchParams({ ...v as CarrierReconSearchParam, pageSize: 200 })}
        onReset={() => setSearchParams({ settleMonth: dayjs().format('YYYYMM'), pageSize: 200 })}
      />

      <ProCard style={cardStyle}>
        <div style={{ marginBottom: 12 }}>
          <PermissionButton menuCode="CARRIER_RECON_IN" permCode="CREATE" type="primary" onClick={() => setCreateOpen(true)}>
            + 대사 등록
          </PermissionButton>
        </div>
        <DataGrid<CarrierReconInRow>
          rows={rows}
          columns={[
            ...LIST_COLS,
            {
              headerName: '액션', width: 220, pinned: 'right',
              cellRenderer: (p: { data: CarrierReconInRow }) => (
                <Space>
                  <PermissionButton
                    menuCode="CARRIER_RECON_IN" permCode="UPDATE" size="small"
                    disabled={p.data.status === 'APPROVED'}
                    onClick={() => handleReconcile(p.data)}
                  >
                    대사실행
                  </PermissionButton>
                  <PermissionButton
                    menuCode="CARRIER_RECON_IN" permCode="UPDATE" size="small"
                    disabled={p.data.status === 'APPROVED' || p.data.status === 'RECEIVED'}
                    onClick={() => handleApprove(p.data)}
                  >
                    승인
                  </PermissionButton>
                  <PermissionButton
                    menuCode="CARRIER_RECON_IN" permCode="READ" size="small"
                    onClick={() => setDrawerTarget(p.data)}
                  >
                    차이내역
                  </PermissionButton>
                </Space>
              ),
            },
          ]}
          loading={isLoading}
          height={520}
          rowKey="reconId"
          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="companyId" label="보험사 ID" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={1} />
          </Form.Item>
          <Form.Item name="settleMonth" label="정산월(YYYYMM)" rules={[{ required: true }]}>
            <Input placeholder="예: 202601" />
          </Form.Item>
          <Form.Item name="fileName" label="파일명">
            <Input placeholder="업로드 파일명" />
          </Form.Item>
          <Form.Item name="recordCount" label="건수" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={0} />
          </Form.Item>
          <Form.Item name="reportedTotal" label="보고 합계금액" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={0} />
          </Form.Item>
        </Form>
      </Modal>

      {/* 차이내역 Drawer */}
      <Drawer
        title={drawerTarget ? `차이내역 — ${drawerTarget.companyName} / ${drawerTarget.settleMonth}` : '차이내역'}
        open={!!drawerTarget}
        onClose={() => setDrawerTarget(null)}
        width={560}
      >
        {drawerTarget && (
          <>
            <Descriptions size="small" column={2} bordered style={{ marginBottom: 16 }}>
              <Descriptions.Item label="보고합계">{fmt(drawerTarget.reportedTotal)}</Descriptions.Item>
              <Descriptions.Item label="시스템합계">{fmt(drawerTarget.systemTotal)}</Descriptions.Item>
              <Descriptions.Item label="차이금액">{fmt(drawerTarget.varianceAmount)}</Descriptions.Item>
              <Descriptions.Item label="상태">{drawerTarget.status}</Descriptions.Item>
            </Descriptions>
            <DataGrid<ReconciliationVarianceRow>
              rows={variances}
              columns={VARIANCE_COLS}
              loading={varLoading}
              height={380}
              rowKey="varianceId"
            />
          </>
        )}
      </Drawer>
    </PageContainer>
  );
}
