import { useEffect, useMemo, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import dayjs from 'dayjs'
import {
  Button,
  Checkbox,
  DatePicker,
  Form,
  Input,
  InputNumber,
  Radio,
  Select,
  message,
} from 'antd'
import Modal from './DraggableModal'
import {
  FormBlock,
  FormField,
  FormGrid,
  FormGroup,
  FormSection,
} from './OrderFormLayout'
import client, { apiPrefix, unwrap, type ApiResponse } from '../api/client'
import { options } from '../pages/care/homesShared'

type Isp = { id: number; name: string; telecom: string; isSktb?: boolean }
type Named = { id: number; name: string; type?: string }

type Props = {
  open: boolean
  isp: Isp | null
  counselorOptions?: string[]
  branchOptions?: string[]
  onCancel: () => void
  onSuccess: () => void
}

const PRODUCT_TYPES = [
  { value: 'e01', label: '인터넷' },
  { value: 'e02', label: '전화' },
  { value: 'e03', label: 'TV' },
  { value: 'e04', label: '렌탈' },
]

const GIFT_TYPES = [
  { value: 'a01', label: '없음' },
  { value: 'a02', label: '현금' },
  { value: 'a03', label: '상품' },
  { value: 'a04', label: '현금+상품' },
]

const BANKS = [
  '국민은행', '우리은행', '신한은행', '하나은행', '기업은행', '농협',
  'SC제일', '카카오뱅크', '토스뱅크', '새마을금고', '우체국', '기타',
]

const CARD_COMPANIES = [
  '삼성카드', '신한카드', '현대카드', 'KB국민카드', '롯데카드',
  '우리카드', '하나카드', 'BC카드', 'NH농협카드', '기타',
]

const CARD_YEARS = Array.from({ length: 31 }, (_, i) => String(i).padStart(2, '0'))
const CARD_MONTHS = Array.from({ length: 12 }, (_, i) => String(i + 1).padStart(2, '0'))

const DISCOUNTS = [
  { value: 'none', label: '해당없음' },
  { value: '국가유공자', label: '국가유공자(30% 할인)' },
  { value: '장애인', label: '장애인(30% 할인)' },
]

export default function ReceptionApplyModal({
  open,
  isp,
  counselorOptions = [],
  branchOptions = [],
  onCancel,
  onSuccess,
}: Props) {
  const [form] = Form.useForm()
  const [saving, setSaving] = useState(false)
  const [createFiles, setCreateFiles] = useState<Record<string, File | null>>({})
  const ispId = isp?.id
  const staffPermission = localStorage.getItem('staffPermission') || ''
  const isAdmin = ['대표', '총괄', '팀장', '개발자'].includes(staffPermission)

  const productsQuery = useQuery({
    queryKey: ['reception-isp-products', ispId],
    queryFn: async () => {
      const { data } = await client.get<ApiResponse<Named[]>>(`${apiPrefix()}/homes/reception-isps/${ispId}/products`)
      return unwrap(data)
    },
    enabled: open && ispId != null,
  })

  const agreementsQuery = useQuery({
    queryKey: ['reception-isp-agreements', ispId],
    queryFn: async () => {
      const { data } = await client.get<ApiResponse<Named[]>>(`${apiPrefix()}/homes/reception-isps/${ispId}/agreements`)
      return unwrap(data)
    },
    enabled: open && ispId != null,
  })

  const customerType = Form.useWatch('customerType', form) || 'public'
  const paymentMethod = Form.useWatch('paymentMethod', form) || 'transfer'
  const productType = Form.useWatch('productType', form)
  const giftType = Form.useWatch('giftType', form) || 'a01'
  const isIssueDate = Form.useWatch('isIssueDate', form) ?? '1'
  const sameCustomerToPayment = Form.useWatch('sameCustomerToPayment', form)
  const sameCustomerToGift = Form.useWatch('sameCustomerToGift', form)
  const samePaymentToGift = Form.useWatch('samePaymentToGift', form)
  const watchName = Form.useWatch('name', form)
  const watchSsid = Form.useWatch('ssid', form)
  const watchPhone = Form.useWatch('phone', form)
  const watchTel = Form.useWatch('tel', form)
  const watchBank = Form.useWatch('bank', form)
  const watchAccountNumber = Form.useWatch('accountNumber', form)
  const watchPaymentName = Form.useWatch('paymentName', form)
  const watchPaymentSsid = Form.useWatch('paymentSsid', form)

  const filteredProducts = useMemo(() => {
    const list = productsQuery.data || []
    if (!productType) return list
    return list.filter((p) => !p.type || p.type === productType)
  }, [productsQuery.data, productType])

  const giftCash = giftType === 'a02' || giftType === 'a04'
  const giftGoods = giftType === 'a03' || giftType === 'a04'

  const branchEmployeeOptions = useMemo(() => {
    const counselors = counselorOptions.length ? counselorOptions : ['홍길동', '김상담', '이상담', '정상담']
    const branches = branchOptions.length ? branchOptions : ['강남점', '서초점', '송파점']
    const out: { value: string; label: string }[] = []
    for (const b of branches) {
      for (const c of counselors) {
        out.push({ value: `${b}|${c}`, label: `[${b}] ${c}` })
      }
    }
    return out
  }, [counselorOptions, branchOptions])

  useEffect(() => {
    if (!open || !isp) return
    setCreateFiles({})
    const rental = isp.telecom === 'SK매직' || isp.telecom === 'LG렌탈'
    const firstOpt = branchEmployeeOptions[0]?.value
    form.setFieldsValue({
      branchEmployee: firstOpt,
      customerType: 'public',
      paymentMethod: 'transfer',
      productType: rental ? 'e04' : 'e01',
      productId: undefined,
      agreementId: undefined,
      price: rental ? 120000 : 80000,
      installDate: dayjs(),
      discount: 'none',
      giftType: 'a01',
      giftPlace: 'b01',
      giftDate: dayjs(),
      cashAmount: 0,
      goods: '',
      goodsPrice: 0,
      name: '',
      postIt: '',
      postAdd: '',
      ssid: '',
      isIssueDate: '1',
      issueDate: undefined,
      driversLicenseNumber: '',
      phone: '',
      tel: '',
      email: '',
      zipcode: '',
      address: '',
      addressDetail: '',
      blName: '',
      blNumber: '',
      blCorpNumber: '',
      blType: '',
      blItem: '',
      blZipcode: '',
      blAddress: '',
      blAddressDetail: '',
      paymentName: '',
      paymentSsid: '',
      paymentTel: '',
      bank: undefined,
      accountNumber: '',
      cardCompany: undefined,
      cardYear: undefined,
      cardMonth: undefined,
      cardNumber: '',
      giftBank: undefined,
      giftAccountNumber: '',
      giftAccountName: '',
      giftSsid: '',
      sameCustomerToPayment: false,
      sameCustomerToGift: false,
      samePaymentToGift: false,
      memo: '',
    })
  }, [open, isp, form, branchEmployeeOptions])

  useEffect(() => {
    if (!sameCustomerToPayment) return
    form.setFieldsValue({
      paymentName: watchName,
      paymentSsid: watchSsid,
      paymentTel: watchPhone || watchTel,
    })
  }, [sameCustomerToPayment, watchName, watchSsid, watchPhone, watchTel, form])

  useEffect(() => {
    if (!sameCustomerToGift) return
    form.setFieldsValue({
      giftAccountName: watchName,
      giftSsid: watchSsid,
    })
  }, [sameCustomerToGift, watchName, watchSsid, form])

  useEffect(() => {
    if (!samePaymentToGift) return
    form.setFieldsValue({
      giftBank: watchBank,
      giftAccountNumber: watchAccountNumber,
      giftAccountName: watchPaymentName || watchName,
      giftSsid: watchPaymentSsid || watchSsid,
    })
  }, [samePaymentToGift, watchBank, watchAccountNumber, watchPaymentName, watchPaymentSsid, watchName, watchSsid, form])

  const searchAddress = (prefix: '' | 'bl') => {
    message.info('주소검색(데모) — 직접 입력해 주세요.')
    if (prefix === 'bl') {
      form.setFieldsValue({
        blZipcode: form.getFieldValue('blZipcode') || '06236',
        blAddress: form.getFieldValue('blAddress') || '서울특별시 강남구 테헤란로',
      })
    } else {
      form.setFieldsValue({
        zipcode: form.getFieldValue('zipcode') || '06236',
        address: form.getFieldValue('address') || '서울특별시 강남구 테헤란로',
      })
    }
  }

  const handleFinish = async (values: Record<string, unknown>) => {
    if (!isp) return
    setSaving(true)
    try {
      const be = String(values.branchEmployee || '')
      const [branch, counselor] = be.includes('|') ? be.split('|') : [values.branch, values.counselor]
      const addrParts = [values.zipcode, values.address, values.addressDetail].filter(Boolean)
      const fullAddress = addrParts.join(' ')
      const memoExtra: string[] = []
      if (values.postAdd) memoExtra.push(`추가메모: ${values.postAdd}`)
      if (values.email) memoExtra.push(`이메일: ${values.email}`)
      if (values.tel) memoExtra.push(`일반전화: ${values.tel}`)
      if (values.paymentName) memoExtra.push(`납입자: ${values.paymentName}`)
      if (values.bank) memoExtra.push(`은행: ${values.bank} ${values.accountNumber || ''}`)
      if (values.cardCompany) memoExtra.push(`카드: ${values.cardCompany} ${values.cardNumber || ''}`)
      if (values.memo) memoExtra.push(String(values.memo))

      const { data } = await client.post<ApiResponse<{ id: number }>>(`${apiPrefix()}/homes/receptions/apply`, {
        ispId: isp.id,
        counselor: counselor || counselorOptions[0] || '홍길동',
        branch: branch || branchOptions[0] || '',
        memo: memoExtra.join('\n'),
        customer: {
          type: values.customerType,
          name: values.name,
          phone: values.phone,
          tel: values.tel,
          ssid: values.ssid,
          email: values.email,
          postIt: values.postIt,
          postAdd: values.postAdd,
          zipcode: values.zipcode,
          address: fullAddress || values.address,
          addressDetail: values.addressDetail,
          issueDate: values.issueDate ? dayjs(values.issueDate as dayjs.Dayjs).format('YYYY-MM-DD') : undefined,
          driversLicenseNumber: values.driversLicenseNumber,
          blName: values.blName,
          blNumber: values.blNumber,
        },
        payment: {
          method: values.paymentMethod,
          name: values.paymentName,
          ssid: values.paymentSsid,
          tel: values.paymentTel,
          bank: values.bank,
          accountNumber: values.accountNumber,
          cardCompany: values.cardCompany,
          cardYear: values.cardYear,
          cardMonth: values.cardMonth,
          cardNumber: values.cardNumber,
        },
        product: {
          productType: values.productType,
          productId: values.productId,
          agreementId: values.agreementId,
          price: values.price,
          installDate: values.installDate ? dayjs(values.installDate as dayjs.Dayjs).format('YYYY-MM-DD') : undefined,
          discount: values.discount === 'none' ? '' : values.discount,
        },
        gift: {
          type: values.giftType,
          place: values.giftPlace,
          cashAmount: values.cashAmount,
          goods: values.goods,
          goodsPrice: values.goodsPrice,
          giftDate: values.giftDate ? dayjs(values.giftDate as dayjs.Dayjs).format('YYYY-MM-DD') : undefined,
          accountBank: values.giftBank,
          accountNumber: values.giftAccountNumber,
          accountName: values.giftAccountName,
          ssid: values.giftSsid,
        },
      })
      const created = unwrap(data) as { id: number }
      await uploadCreateAttachments(created.id)
      message.success(`[${isp.name}] 신규신청을 등록했습니다.`)
      onSuccess()
    } catch {
      message.error('신규신청 등록에 실패했습니다.')
    } finally {
      setSaving(false)
    }
  }

  const uploadCreateAttachments = async (receptionId: number) => {
    for (const slot of [1, 2, 3, 4, 5] as const) {
      const file = createFiles[`file${slot}`]
      if (!file) continue
      const fd = new FormData()
      fd.append('file', file)
      await client.post(`${apiPrefix()}/homes/receptions/${receptionId}/file/${slot}`, fd)
    }
    if (isAdmin) {
      for (const slot of [1, 2, 3] as const) {
        const file = createFiles[`adminFile${slot}`]
        if (!file) continue
        const fd = new FormData()
        fd.append('file', file)
        await client.post(`${apiPrefix()}/homes/receptions/${receptionId}/admin-file/${slot}`, fd)
      }
    }
  }

  const buildMemoAuto = () => {
    const v = form.getFieldsValue()
    const giftLabel = GIFT_TYPES.find((g) => g.value === v.giftType)?.label || ''
    const productLabel = PRODUCT_TYPES.find((p) => p.value === v.productType)?.label || ''
    const productName = (productsQuery.data || []).find((p) => p.id === v.productId)?.name || ''
    const agreementName = (agreementsQuery.data || []).find((a) => a.id === v.agreementId)?.name || ''
    let content = ''
    content += `◈ 고객명 : ${v.name || ''}\n`
    content += `◈ 연락처 : ${v.phone || ''}\n`
    content += `◈ 상품 : ${productLabel} / ${productName}\n`
    content += `◈ 약정 : ${agreementName}\n`
    content += `◈ 사은품 : ${giftLabel}`
    if (v.giftType && v.giftType !== 'a01') {
      const parts: string[] = []
      if (v.giftType === 'a02' || v.giftType === 'a04') parts.push(`현금(${v.cashAmount || 0})`)
      if (v.giftType === 'a03' || v.giftType === 'a04') parts.push(`${v.goods || ''}(${v.goodsPrice || 0})`)
      if (parts.length) content += ` / ${parts.join(', ')}`
    }
    content += '\n'
    content += `◈ 납입자 : ${v.paymentName || ''}\n`
    content += `◈ 주소 : ${[v.zipcode, v.address, v.addressDetail].filter(Boolean).join(' ')}\n`
    return content
  }

  const issueLabel = customerType === 'foreigner' ? '외국인등록증 발급일자' : '주민등록증 발급일자'
  const ssidLabel = customerType === 'foreigner' ? '외국인등록번호' : '주민등록번호'
  const addrLabel = customerType === 'foreigner' ? '설치주소' : '주소'

  const addrStack = (prefix: '' | 'bl') => (
    <div className="of-addr-stack">
      <div className="of-addr-zip">
        <Form.Item name={prefix ? 'blZipcode' : 'zipcode'} noStyle>
          <Input placeholder="우편번호" style={{ width: 120 }} />
        </Form.Item>
        <Button type="default" onClick={() => searchAddress(prefix)}>주소검색</Button>
      </div>
      <Form.Item name={prefix ? 'blAddress' : 'address'} noStyle>
        <Input placeholder="주소" />
      </Form.Item>
      <Form.Item name={prefix ? 'blAddressDetail' : 'addressDetail'} noStyle>
        <Input placeholder="상세주소" />
      </Form.Item>
    </div>
  )

  return (
    <Modal
      title={isp ? `신규가입 신청 - ${isp.name}` : '신규가입 신청'}
      open={open}
      onCancel={onCancel}
      footer={null}
      destroyOnHidden
      width="96%"
      style={{ maxWidth: 1040 }}
      className="reception-apply-modal order-form-modal"
      styles={{ body: { maxHeight: 'calc(92vh - 56px)', overflowY: 'auto' } }}
    >
      <Form form={form} layout="vertical" className="order-form-embedded-inner order-form-page reception-apply-form" onFinish={handleFinish}>
        <FormSection title="기본 정보">
          <FormGrid>
            <FormField label="영업점" full>
              <Form.Item name="branchEmployee" noStyle rules={[{ required: true, message: '영업점을 선택하세요' }]}>
                <Select
                  showSearch
                  optionFilterProp="label"
                  options={branchEmployeeOptions}
                  placeholder="--- 영업점 선택 ---"
                />
              </Form.Item>
            </FormField>
            <FormField label="통신사" full>
              <Input value={isp ? `[${isp.telecom}] ${isp.name}` : ''} disabled />
            </FormField>
            <FormField label="인증 링크" full>
              <p className="of-muted" style={{ padding: 0, border: 'none', margin: 0 }}>등록된 인증 링크가 없습니다.</p>
            </FormField>
          </FormGrid>
        </FormSection>

        <FormSection title="고객정보">
          <FormGrid cols={1}>
            <FormField label="고객유형" full>
              <Form.Item name="customerType" noStyle>
                <Radio.Group className="of-antd-choice-row" style={{ padding: 0, border: 'none' }}>
                  <Radio value="public">개인</Radio>
                  <Radio value="company">사업자</Radio>
                  <Radio value="foreigner">외국인</Radio>
                </Radio.Group>
              </Form.Item>
            </FormField>
          </FormGrid>

          {customerType === 'company' ? (
            <FormGrid>
              <FormField label="사업장명">
                <Form.Item name="name" noStyle rules={[{ required: true, message: '사업장명을 입력하세요' }]}>
                  <Input />
                </Form.Item>
              </FormField>
              <FormField label="대표자명">
                <Form.Item name="blName" noStyle><Input /></Form.Item>
              </FormField>
              <FormField label="사업자등록번호">
                <Form.Item name="blNumber" noStyle><Input /></Form.Item>
              </FormField>
              <FormField label="법인등록번호">
                <Form.Item name="blCorpNumber" noStyle><Input /></Form.Item>
              </FormField>
              <FormField label="업태">
                <Form.Item name="blType" noStyle><Input /></Form.Item>
              </FormField>
              <FormField label="종목">
                <Form.Item name="blItem" noStyle><Input /></Form.Item>
              </FormField>
              <FormField label="포스트잇">
                <Form.Item name="postIt" noStyle><Input /></Form.Item>
              </FormField>
              <FormField label="추가메모">
                <Form.Item name="postAdd" noStyle><Input /></Form.Item>
              </FormField>
              <FormField label="사업장주소" full>{addrStack('bl')}</FormField>
              <FormField label="휴대폰">
                <Form.Item name="phone" noStyle rules={[{ required: true, message: '휴대폰을 입력하세요' }]}>
                  <Input placeholder="010-0000-0000" />
                </Form.Item>
              </FormField>
              <FormField label="일반전화">
                <Form.Item name="tel" noStyle><Input /></Form.Item>
              </FormField>
              <FormField label="이메일" full>
                <Form.Item name="email" noStyle><Input type="email" /></Form.Item>
              </FormField>
              <FormField label="주소" full>{addrStack('')}</FormField>
            </FormGrid>
          ) : (
            <FormGrid>
              <FormField label="고객명">
                <Form.Item name="name" noStyle rules={[{ required: true, message: '고객명을 입력하세요' }]}>
                  <Input />
                </Form.Item>
              </FormField>
              <FormField label="포스트잇">
                <Form.Item name="postIt" noStyle><Input /></Form.Item>
              </FormField>
              <FormField label="추가메모" full>
                <Form.Item name="postAdd" noStyle><Input /></Form.Item>
              </FormField>
              <FormField label={ssidLabel} hint="예) 140101-*******">
                <Form.Item name="ssid" noStyle>
                  <Input placeholder="예) 140101-*******" />
                </Form.Item>
              </FormField>
              <FormField label={isIssueDate === '1' ? issueLabel : '운전면허번호'}>
                <div className="order-form-inline">
                  <Form.Item name="isIssueDate" noStyle>
                    <Select
                      style={{ minWidth: 140, flex: '0 0 auto' }}
                      options={[
                        { value: '1', label: issueLabel },
                        { value: '0', label: '운전면허번호' },
                      ]}
                    />
                  </Form.Item>
                  {isIssueDate === '1' ? (
                    <Form.Item name="issueDate" noStyle>
                      <DatePicker className="full-width" style={{ flex: 1 }} />
                    </Form.Item>
                  ) : (
                    <Form.Item name="driversLicenseNumber" noStyle>
                      <Input placeholder="예) 대구 00-123456-00" style={{ flex: 1 }} />
                    </Form.Item>
                  )}
                </div>
              </FormField>
              <FormField label="휴대폰">
                <Form.Item name="phone" noStyle rules={[{ required: true, message: '휴대폰을 입력하세요' }]}>
                  <Input placeholder="010-0000-0000" />
                </Form.Item>
              </FormField>
              <FormField label="일반전화">
                <Form.Item name="tel" noStyle><Input /></Form.Item>
              </FormField>
              <FormField label="이메일" full>
                <Form.Item name="email" noStyle><Input type="email" /></Form.Item>
              </FormField>
              <FormField label={addrLabel} full>{addrStack('')}</FormField>
            </FormGrid>
          )}
        </FormSection>

        <FormSection title="결제납입정보">
          <FormGrid cols={1}>
            <FormField label="납부방식" full>
              <Form.Item name="paymentMethod" noStyle>
                <Radio.Group className="of-antd-choice-row" style={{ padding: 0, border: 'none' }}>
                  <Radio value="transfer">자동이체</Radio>
                  <Radio value="card">신용카드</Radio>
                  <Radio value="paper">지로청구</Radio>
                  <Radio value="telephone">전화번호요금통합</Radio>
                </Radio.Group>
              </Form.Item>
            </FormField>
          </FormGrid>

          {(paymentMethod === 'transfer' || paymentMethod === 'card') && (
            <FormGrid>
              <FormField label="납입자">
                <div className="order-form-inline">
                  <Form.Item name="paymentName" noStyle>
                    <Input style={{ flex: 1 }} />
                  </Form.Item>
                  <Form.Item name="sameCustomerToPayment" valuePropName="checked" noStyle>
                    <Checkbox>고객정보와 동일</Checkbox>
                  </Form.Item>
                </div>
              </FormField>
              <FormField label="주민등록번호">
                <Form.Item name="paymentSsid" noStyle><Input /></Form.Item>
              </FormField>
              <FormField label="전화번호" full>
                <Form.Item name="paymentTel" noStyle><Input /></Form.Item>
              </FormField>
              {paymentMethod === 'transfer' ? (
                <>
                  <FormField label="은행">
                    <Form.Item name="bank" noStyle>
                      <Select allowClear placeholder="--- 은행선택 ---" options={options(BANKS)} />
                    </Form.Item>
                  </FormField>
                  <FormField label="계좌번호">
                    <Form.Item name="accountNumber" noStyle><Input /></Form.Item>
                  </FormField>
                </>
              ) : (
                <>
                  <FormField label="카드">
                    <div className="order-form-inline">
                      <Form.Item name="cardCompany" noStyle>
                        <Select allowClear placeholder="카드사" options={options(CARD_COMPANIES)} style={{ minWidth: 110 }} />
                      </Form.Item>
                      <Form.Item name="cardYear" noStyle>
                        <Select allowClear placeholder="YY" options={CARD_YEARS.map((y) => ({ value: y, label: y }))} style={{ width: 72 }} />
                      </Form.Item>
                      <span>년</span>
                      <Form.Item name="cardMonth" noStyle>
                        <Select allowClear placeholder="MM" options={CARD_MONTHS.map((m) => ({ value: m, label: m }))} style={{ width: 72 }} />
                      </Form.Item>
                      <span>월</span>
                    </div>
                  </FormField>
                  <FormField label="카드번호">
                    <Form.Item name="cardNumber" noStyle><Input /></Form.Item>
                  </FormField>
                </>
              )}
            </FormGrid>
          )}
        </FormSection>

        <FormSection title="상품 정보">
          <FormBlock>
            <FormGrid>
              <FormField label="상품종류">
                <Form.Item name="productType" noStyle rules={[{ required: true }]}>
                  <Select
                    options={PRODUCT_TYPES}
                    onChange={() => form.setFieldValue('productId', undefined)}
                  />
                </Form.Item>
              </FormField>
              <FormField label="상품">
                <Form.Item name="productId" noStyle rules={[{ required: true, message: '상품을 선택하세요' }]}>
                  <Select
                    loading={productsQuery.isLoading}
                    options={(filteredProducts || []).map((p) => ({ value: p.id, label: p.name }))}
                    placeholder="선택"
                  />
                </Form.Item>
              </FormField>
              <FormField label="약정">
                <Form.Item name="agreementId" noStyle>
                  <Select
                    allowClear
                    loading={agreementsQuery.isLoading}
                    options={(agreementsQuery.data || []).map((a) => ({ value: a.id, label: a.name }))}
                    placeholder="선택"
                  />
                </Form.Item>
              </FormField>
              <FormField label="월사용요금">
                <Form.Item name="price" noStyle>
                  <InputNumber className="full-width" min={0} controls={false} style={{ width: '100%' }} />
                </Form.Item>
              </FormField>
              <FormField label="설치희망일자" full>
                <Form.Item name="installDate" noStyle>
                  <DatePicker className="full-width" style={{ width: '100%' }} />
                </Form.Item>
              </FormField>
              <FormField label="할인혜택" full>
                <Form.Item name="discount" noStyle>
                  <Radio.Group className="of-antd-choice-row">
                    {DISCOUNTS.map((d) => (
                      <Radio key={d.value} value={d.value}>{d.label}</Radio>
                    ))}
                  </Radio.Group>
                </Form.Item>
              </FormField>
            </FormGrid>

            <FormGroup label="상품별 사은품">
              <FormGrid>
                <FormField label="사은품종류">
                  <Form.Item name="giftType" noStyle>
                    <Select options={GIFT_TYPES} />
                  </Form.Item>
                </FormField>
                <FormField label="현금금액">
                  <Form.Item name="cashAmount" noStyle>
                    <InputNumber className="full-width" min={0} controls={false} disabled={!giftCash} style={{ width: '100%' }} />
                  </Form.Item>
                </FormField>
                <FormField label="물품명">
                  <Form.Item name="goods" noStyle>
                    <Input disabled={!giftGoods} />
                  </Form.Item>
                </FormField>
                <FormField label="물품금액">
                  <Form.Item name="goodsPrice" noStyle>
                    <InputNumber className="full-width" min={0} controls={false} disabled={!giftGoods} style={{ width: '100%' }} />
                  </Form.Item>
                </FormField>
              </FormGrid>
            </FormGroup>
          </FormBlock>
        </FormSection>

        <FormSection title="사은품 정보">
          <FormGrid>
            <FormField label="지급예정일자">
              <Form.Item name="giftDate" noStyle>
                <DatePicker className="full-width" style={{ width: '100%' }} />
              </Form.Item>
            </FormField>
            <FormField label="사은품지급처">
              <Form.Item name="giftPlace" noStyle>
                <Radio.Group className="of-antd-choice-row">
                  <Radio value="b01">본사요청</Radio>
                  <Radio value="b02">자체발송</Radio>
                </Radio.Group>
              </Form.Item>
            </FormField>
            <FormField label="결제은행">
              <div className="order-form-inline">
                <Form.Item name="giftBank" noStyle>
                  <Select allowClear placeholder="--- 은행선택 ---" options={options(BANKS)} style={{ flex: 1 }} />
                </Form.Item>
                <Form.Item name="samePaymentToGift" valuePropName="checked" noStyle>
                  <Checkbox>결제정보와 동일</Checkbox>
                </Form.Item>
              </div>
            </FormField>
            <FormField label="계좌번호">
              <Form.Item name="giftAccountNumber" noStyle><Input /></Form.Item>
            </FormField>
            <FormField label="예금주명">
              <div className="order-form-inline">
                <Form.Item name="giftAccountName" noStyle>
                  <Input style={{ flex: 1 }} />
                </Form.Item>
                <Form.Item name="sameCustomerToGift" valuePropName="checked" noStyle>
                  <Checkbox>고객정보와 동일</Checkbox>
                </Form.Item>
              </div>
            </FormField>
            <FormField label="주민등록번호">
              <Form.Item name="giftSsid" noStyle><Input /></Form.Item>
            </FormField>
          </FormGrid>
        </FormSection>

        <FormSection title="기타 정보">
          <FormGrid cols={1}>
            <FormField label="기타사항" full>
              <div className="of-toolbar-inline">
                <button
                  type="button"
                  className="ghost sm"
                  onClick={() => form.setFieldsValue({ memo: `${form.getFieldValue('memo') || ''}${buildMemoAuto()}` })}
                >
                  기타사항 자동입력
                </button>
                <button type="button" className="ghost sm" onClick={() => form.setFieldsValue({ memo: '' })}>
                  기타사항 삭제
                </button>
              </div>
              <Form.Item name="memo" noStyle>
                <Input.TextArea rows={6} />
              </Form.Item>
            </FormField>
            {[1, 2, 3, 4, 5].map((slot) => (
              <FormField key={slot} label={`첨부파일${slot}`} full>
                <div className="order-form-inline">
                  <input
                    type="file"
                    onChange={(e) => {
                      const f = e.target.files?.[0] || null
                      setCreateFiles((prev) => ({ ...prev, [`file${slot}`]: f }))
                    }}
                  />
                  {createFiles[`file${slot}`] ? (
                    <span className="muted">{createFiles[`file${slot}`]?.name}</span>
                  ) : null}
                </div>
              </FormField>
            ))}
            {isAdmin
              ? [1, 2, 3].map((slot) => (
                  <FormField key={`a${slot}`} label={`관리자 첨부파일${slot}`} full>
                    <div className="order-form-inline">
                      <input
                        type="file"
                        onChange={(e) => {
                          const f = e.target.files?.[0] || null
                          setCreateFiles((prev) => ({ ...prev, [`adminFile${slot}`]: f }))
                        }}
                      />
                      {createFiles[`adminFile${slot}`] ? (
                        <span className="muted">{createFiles[`adminFile${slot}`]?.name}</span>
                      ) : null}
                    </div>
                  </FormField>
                ))
              : null}
          </FormGrid>
        </FormSection>

        <div className="order-form-actions">
          <Button type="primary" htmlType="submit" loading={saving} className="pending-submit-btn">
            등록
          </Button>
          <Button onClick={onCancel}>취소</Button>
        </div>
      </Form>
    </Modal>
  )
}
