import { useState } from 'react';
import { Alert, Form, Input, InputNumber, Modal, Space, Switch, Typography, 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 CodeBadge from '@/components/common/CodeBadge';
import { withdrawApi, WithdrawRequestRow, WithdrawRequestSaveReq, WithdrawSearchParam } from '@/api/withdraw';
import { GRAY, RADIUS, SHADOW } from '@/theme/tokens';

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

const COLUMNS: ColDef<WithdrawRequestRow>[] = [
  { field: 'agentName',     headerName: '설계사',   width: 120, pinned: 'left' },
  { field: 'settleMonth',   headerName: '정산월',   width: 110 },
  { field: 'requestAmount', headerName: '신청금액', flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'bankCode',      headerName: '은행',     width: 100 },
  { field: 'accountNo',     headerName: '계좌번호', width: 160 },
  { field: 'accountHolder', headerName: '예금주',   width: 110 },
  {
    field: 'status', headerName: '출금 상태', width: 120,
    cellRenderer: (p: { value: string }) => <CodeBadge groupCode="WITHDRAW_STATUS" value={p.value} />,
  },
  {
    field: 'approvalStatus', headerName: '결재 상태', width: 110,
    cellRenderer: (p: { value?: string }) =>
      p.value ? <CodeBadge groupCode="APPROVAL_STATUS" value={p.value} /> : <Text style={{ color: GRAY[400], fontSize: 12 }}>-</Text>,
  },
  { field: 'requestedAt', headerName: '신청일', width: 120 },
  { field: 'completedAt', headerName: '완료일', width: 120 },
  { field: 'transferTxId',  headerName: '펌뱅킹 거래ID', width: 200 },
  { field: 'transferStatus', headerName: '펌뱅킹 상태',  width: 110 },
  { field: 'transferAt',     headerName: '펌뱅킹 시각',  width: 150 },
];

export default function WithdrawRequest() {
  const qc = useQueryClient();
  const [viewAll, setViewAll] = useState(false);
  const [params, setParams] = useState<WithdrawSearchParam>({
    settleMonth: dayjs().format('YYYYMM'),
    pageSize: 100,
  });
  const [createOpen, setCreateOpen] = useState(false);
  const [form] = Form.useForm();

  const { data, isLoading, isError } = useQuery({
    queryKey: ['withdraw-requests', params, viewAll],
    queryFn: () => withdrawApi.list({ ...params, viewAll }),
    retry: false,
  });

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

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

  const handleCreate = async () => {
    const values = await form.validateFields() as WithdrawRequestSaveReq;
    try {
      await withdrawApi.create(values);
      message.success('출금 신청 완료 — 결재 요청이 자동 생성됩니다');
      qc.invalidateQueries({ queryKey: ['withdraw-requests'] });
      setCreateOpen(false);
      form.resetFields();
    } catch { /* handled */ }
  };

  return (
    <PageContainer
      title="출금 신청"
      description="정산 출금 신청, 결재 진행, 펌뱅킹 상태 조회"
      extra={
        <Space>
          <Space align="center">
            <Text style={{ fontSize: 13, color: GRAY[500] }}>전체 보기</Text>
            <Switch checked={viewAll} onChange={setViewAll} size="small" />
          </Space>
          <PermissionButton menuCode="WITHDRAW_REQUESTS" permCode="CREATE" type="primary" onClick={() => setCreateOpen(true)}>
            + 출금 신청
          </PermissionButton>
        </Space>
      }
    >
      {isError && (
        <Alert type="warning" showIcon message="API 미응답" description="/api/withdraw-requests 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      <SearchForm
        conditions={[
          { type: 'text',  name: 'agentName',  label: '설계사명', span: 6 },
          { type: 'month', name: 'settleMonth', label: '정산월',   span: 6 },
          { type: 'code',  name: 'status',      label: '상태',     groupCode: 'WITHDRAW_STATUS', span: 6 },
        ]}
        onSearch={(v) => setParams({ ...v as WithdrawSearchParam, pageSize: 100 })}
        onReset={() => setParams({ settleMonth: dayjs().format('YYYYMM'), pageSize: 100 })}
      />

      <ProCard style={{ background: '#fff', borderRadius: RADIUS.lg, border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm }}>
        <DataGrid<WithdrawRequestRow>
          rows={rows}
          columns={COLUMNS}
          loading={isLoading}
          height={600}
          rowKey="withdrawId"
          pinnedBottomRow={pinnedRow}
        />
      </ProCard>

      <Modal
        title="출금 신청"
        open={createOpen}
        onOk={handleCreate}
        onCancel={() => setCreateOpen(false)}
        okText="신청"
        cancelText="취소"
        width={480}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="settleMonth" label="정산월" rules={[{ required: true }]} initialValue={dayjs().format('YYYYMM')}>
            <Input placeholder="YYYYMM" />
          </Form.Item>
          <Form.Item name="requestAmount" label="신청금액" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={0} step={1000} formatter={(v) => `${v}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')} />
          </Form.Item>
          <Form.Item name="bankCode" label="은행코드" rules={[{ required: true }]}>
            <Input placeholder="004 (국민) / 020 (우리) / ..." />
          </Form.Item>
          <Form.Item name="accountNo" label="계좌번호" rules={[{ required: true }]}>
            <Input placeholder="'-' 없이 입력" />
          </Form.Item>
          <Form.Item name="accountHolder" label="예금주명" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
