import { Button, Form, Input, NavBar, Picker, Toast } from 'antd-mobile';
import type { PickerColumn } from 'antd-mobile/es/components/picker';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { SettleMasterResp, withdrawApi } from '@/api/withdraw';

interface FormValues {
  settleMasterId?: number;
  amount?: string;
  bankCode?: string;
  accountNo?: string;
}

export default function WithdrawCreate() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [form] = Form.useForm<FormValues>();
  const [pickerVisible, setPickerVisible] = useState(false);
  const [pickedLabel, setPickedLabel] = useState<string>('');
  const [selectedId, setSelectedId] = useState<number | undefined>(undefined);

  const { data: settleMasters = [], isLoading } = useQuery({
    queryKey: ['mobile.me.settle-masters'],
    queryFn: () => withdrawApi.settleMasters(),
    retry: false,
  });

  const { data: balance } = useQuery({
    queryKey: ['mobile.me.withdrawable-balance', selectedId],
    queryFn: () => withdrawApi.withdrawableBalance(selectedId as number),
    enabled: selectedId != null,
    retry: false,
  });

  const pickerColumns: PickerColumn[] = useMemo(
    () => [
      settleMasters.map((s: SettleMasterResp) => ({
        label: `${s.settleMonth} · 실수령 ${fmt(s.netAmount)}원`,
        value: String(s.settleId),
      })),
    ],
    [settleMasters],
  );

  const create = useMutation({
    mutationFn: (req: { settleMasterId: number; amount: number; bankCode: string; accountNo: string }) =>
      withdrawApi.create(req),
    onSuccess: () => {
      Toast.show({ icon: 'success', content: '출금 신청이 접수되었습니다' });
      queryClient.invalidateQueries({ queryKey: ['mobile.me.withdraws'] });
      queryClient.invalidateQueries({ queryKey: ['mobile.me.summary'] });
      navigate('/withdraw', { replace: true });
    },
  });

  const onSubmit = (values: FormValues) => {
    if (!values.settleMasterId) {
      Toast.show({ icon: 'fail', content: '정산 마스터를 선택하세요' });
      return;
    }
    const amount = Number(values.amount);
    if (!amount || amount <= 0) {
      Toast.show({ icon: 'fail', content: '금액을 입력하세요' });
      return;
    }
    if (balance && amount > balance.remainingAmount) {
      Toast.show({ icon: 'fail', content: `출금 가능 잔액(${fmt(balance.remainingAmount)}원)을 초과합니다` });
      return;
    }
    create.mutate({
      settleMasterId: Number(values.settleMasterId),
      amount,
      bankCode: values.bankCode ?? '',
      accountNo: values.accountNo ?? '',
    });
  };

  return (
    <div className="page">
      <NavBar onBack={() => navigate(-1)}>출금 신청</NavBar>
      {balance && (
        <div
          style={{
            margin: '12px',
            padding: '12px 16px',
            background: '#e6f4ff',
            borderRadius: 8,
            fontSize: 14,
          }}
        >
          <div style={{ color: '#666' }}>출금 가능 잔액</div>
          <div style={{ fontSize: 22, fontWeight: 700, color: '#1677ff' }}>
            {fmt(balance.remainingAmount)}원
          </div>
          <div style={{ color: '#999', fontSize: 12, marginTop: 4 }}>
            실수령 {fmt(balance.netAmount)}원 · 신청중 {fmt(balance.usedAmount)}원
          </div>
        </div>
      )}
      <Form
        form={form}
        layout="horizontal"
        mode="card"
        onFinish={onSubmit}
        footer={
          <Button block type="submit" color="primary" loading={create.isPending} disabled={isLoading}>
            신청
          </Button>
        }
      >
        <Form.Item
          name="settleMasterId"
          label="정산 월"
          trigger="onConfirm"
          onClick={() => setPickerVisible(true)}
          rules={[{ required: true, message: '정산 마스터를 선택하세요' }]}
        >
          <div style={{ color: pickedLabel ? '#000' : '#bbb' }}>
            {pickedLabel || '선택하세요'}
          </div>
        </Form.Item>
        <Form.Item name="amount" label="금액" rules={[{ required: true, message: '금액을 입력하세요' }]}>
          <Input placeholder="예: 1500000" type="number" inputMode="numeric" />
        </Form.Item>
        <Form.Item name="bankCode" label="은행 코드" rules={[{ required: true, message: '은행 코드' }]}>
          <Input placeholder="예: 088" />
        </Form.Item>
        <Form.Item name="accountNo" label="계좌번호" rules={[{ required: true, message: '계좌번호' }]}>
          <Input placeholder="-없이 입력" />
        </Form.Item>
      </Form>

      <Picker
        columns={pickerColumns}
        visible={pickerVisible}
        onClose={() => setPickerVisible(false)}
        onConfirm={(val) => {
          const id = val[0] != null ? Number(val[0]) : undefined;
          form.setFieldValue('settleMasterId', id);
          setSelectedId(id);
          const picked = settleMasters.find((s) => String(s.settleId) === val[0]);
          if (picked) setPickedLabel(`${picked.settleMonth} · 실수령 ${fmt(picked.netAmount)}원`);
        }}
      />
    </div>
  );
}

function fmt(n?: number) {
  if (n == null) return '-';
  return n.toLocaleString();
}
