import { useMemo, useState } from 'react'
import Modal from '../../components/DraggableModal'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import dayjs from 'dayjs'
import {
  Button,
  Checkbox,
  DatePicker,
  Dropdown,
  Form,
  Input,
  Select,
  message,
} from 'antd'
import ReceptionApplyModal from '../../components/ReceptionApplyModal'
import ReceptionBulkModal from '../../components/ReceptionBulkModal'
import ReceptionProgressModal from '../../components/ReceptionProgressModal'
import { DownOutlined } from '@ant-design/icons'
import client, { apiPrefix, unwrap, type ApiResponse } from '../../api/client'
import { options } from './homesShared'

type ReceptionRow = {
  id: number
  orderDate?: string
  today?: boolean
  counselor?: string
  employeeName?: string
  branch?: string
  branchOfficeName?: string
  branchGroup?: string
  branchGroupName?: string
  carrier?: string
  ispName?: string
  giftCategory?: string
  giftType?: string
  productCategory?: string
  productType?: string
  productName?: string
  customerName?: string
  phone?: string
  region?: string
  sido?: string
  progressStatus?: string
  status?: string
  settleStatus?: string
  centerStatus?: string
  centerName?: string
  openDate?: string
  opened?: string
  cancelDate?: string
  canceled?: string
  giftDate?: string
  giftSended?: string
  giftStatus?: string
  giftPlace?: string
  giftAmount?: number
  agreementName?: string
  contractNumber?: string
  identifyNumber?: string
  postIt?: string
  postAdd?: string
  amount?: number
}

type ReceptionResult = {
  total: number
  list: ReceptionRow[]
  progressStatuses?: string[]
  settleStatuses?: string[]
  giftStatuses?: string[]
  carriers?: string[]
  branches?: string[]
  counselors?: string[]
  processors?: string[]
  regions?: string[]
  giftCategories?: string[]
  productCategories?: string[]
}

const SIDO_LIST = [
  '서울', '경기', '인천', '강원', '충북', '충남', '대전', '전북', '전남', '광주',
  '경북', '대구', '경남', '울산', '부산', '제주',
]

const GIFT_PLACE_LABEL: Record<string, string> = {
  b01: '본사요청',
  b02: '자체발송',
  본사: '본사발송',
  영업점: '영업점발송',
}

const initialFilters = () => ({
  page: 0,
  size: 50,
  orderDateStart: dayjs().startOf('month').format('YYYY-MM-DD'),
  orderDateEnd: dayjs().format('YYYY-MM-DD'),
  sorting: 'order_date',
  postIt: '',
  agreementName: '',
  customerSsid: '',
  customerEmail: '',
  customerName: '',
  customerPhone: '',
  contractNumber: '',
  productName: '',
  ispName: '',
  branchEmployee: '',
  branchName: '',
  giftType: undefined as string | undefined,
  productType: undefined as string | undefined,
  progressStatus: undefined as string | undefined,
  giftStatus: undefined as string | undefined,
  giftPlace: undefined as string | undefined,
  customerSido: undefined as string | undefined,
  carrier: undefined as string | undefined,
  branch: undefined as string | undefined,
  settleStatus: undefined as string | undefined,
  opended: undefined as string | undefined,
  giftSended: undefined as string | undefined,
})

const num = (n?: number | null) => (n == null ? '' : Number(n).toLocaleString())

const giftPlaceLabel = (v?: string) => {
  if (!v) return ''
  return GIFT_PLACE_LABEL[v] || v
}

const splitDt = (v?: string) => {
  if (!v) return ['', '']
  const s = String(v).replace('T', ' ')
  const [d, t] = s.split(' ')
  return [d || '', (t || '').substring(0, 8)]
}

export default function ReceptionListPage() {
  const [editForm] = Form.useForm()
  const qc = useQueryClient()
  const [draft, setDraft] = useState(initialFilters)
  const [filters, setFilters] = useState(initialFilters)
  const [selected, setSelected] = useState<number[]>([])
  const [detail, setDetail] = useState<ReceptionRow | null>(null)
  const [creating, setCreating] = useState(false)
  const [bulkOpen, setBulkOpen] = useState(false)
  const [progressId, setProgressId] = useState<number | null>(null)
  const [applyIsp, setApplyIsp] = useState<{ id: number; name: string; telecom: string; isSktb?: boolean } | null>(null)

  const ispQuery = useQuery({
    queryKey: ['homes-reception-isps'],
    queryFn: async () => {
      const { data } = await client.get<ApiResponse<{ id: number; name: string; telecom: string; isSktb?: boolean }[]>>(
        `${apiPrefix()}/homes/reception-isps`,
      )
      return unwrap(data)
    },
  })

  const query = useQuery({
    queryKey: ['homes-receptions', filters],
    queryFn: async () => {
      const { data } = await client.get<ApiResponse<ReceptionResult>>(`${apiPrefix()}/homes/receptions`, {
        params: {
          page: filters.page,
          size: filters.size,
          orderDateStart: filters.orderDateStart || undefined,
          orderDateEnd: filters.orderDateEnd || undefined,
          sorting: filters.sorting,
          postIt: filters.postIt || undefined,
          agreementName: filters.agreementName || undefined,
          customerSsid: filters.customerSsid || undefined,
          customerEmail: filters.customerEmail || undefined,
          customerName: filters.customerName || undefined,
          customerPhone: filters.customerPhone || undefined,
          contractNumber: filters.contractNumber || undefined,
          productName: filters.productName || undefined,
          ispName: filters.ispName || undefined,
          branchEmployee: filters.branchEmployee || undefined,
          branchName: filters.branchName || undefined,
          giftType: filters.giftType || undefined,
          productType: filters.productType || undefined,
          progressStatus: filters.progressStatus || undefined,
          giftStatus: filters.giftStatus || undefined,
          giftPlace: filters.giftPlace || undefined,
          customerSido: filters.customerSido || undefined,
          carrier: filters.carrier || undefined,
          branch: filters.branch || undefined,
          settleStatus: filters.settleStatus || undefined,
          opended: filters.opended || undefined,
          giftSended: filters.giftSended || undefined,
        },
      })
      return unwrap(data)
    },
  })

  const refresh = () => {
    qc.invalidateQueries({ queryKey: ['homes-receptions'] })
    setSelected([])
  }

  const progressStatuses = query.data?.progressStatuses || []
  const settleStatuses = query.data?.settleStatuses || []
  const giftStatuses = query.data?.giftStatuses || []
  const list = query.data?.list || []

  const setD = (patch: Partial<ReturnType<typeof initialFilters>>) => setDraft((p) => ({ ...p, ...patch }))
  const applyF = (patch: Partial<ReturnType<typeof initialFilters>>) => {
    const next = { ...draft, ...patch, page: 0 }
    setDraft(next)
    setFilters(next)
  }

  const search = () => setFilters({ ...draft, page: 0 })
  const reset = () => {
    const next = initialFilters()
    setDraft(next)
    setFilters(next)
    setSelected([])
  }

  const quick = (key: string) => {
    const today = dayjs()
    let start = today
    let end = today
    switch (key) {
      case 'today':
        break
      case 'yesterday':
        start = today.subtract(1, 'day')
        end = start
        break
      case 'thisWeek':
        start = today.startOf('week')
        break
      case 'lastWeek':
        start = today.subtract(1, 'week').startOf('week')
        end = today.subtract(1, 'week').endOf('week')
        break
      case 'thisMonth':
        start = today.startOf('month')
        break
      case 'lastMonth':
        start = today.subtract(1, 'month').startOf('month')
        end = today.subtract(1, 'month').endOf('month')
        break
      case 'thisYear':
        start = today.startOf('year')
        break
      case 'lastYear':
        start = today.subtract(1, 'year').startOf('year')
        end = today.subtract(1, 'year').endOf('year')
        break
      default:
        break
    }
    applyF({
      orderDateStart: start.format('YYYY-MM-DD'),
      orderDateEnd: end.format('YYYY-MM-DD'),
    })
  }

  const saveMut = useMutation({
    mutationFn: async (payload: Record<string, unknown>) => {
      if (detail?.id && !creating) {
        const { data } = await client.put(`${apiPrefix()}/homes/receptions/${detail.id}`, payload)
        return unwrap(data)
      }
      const { data } = await client.post(`${apiPrefix()}/homes/receptions`, payload)
      return unwrap(data)
    },
    onSuccess: () => {
      message.success(creating ? '등록했습니다.' : '수정했습니다.')
      setCreating(false)
      setDetail(null)
      refresh()
    },
    onError: () => message.error('저장에 실패했습니다.'),
  })

  const deleteMut = useMutation({
    mutationFn: async (ids: number[]) => {
      const { data } = await client.post(`${apiPrefix()}/homes/receptions/delete`, { ids })
      return unwrap(data)
    },
    onSuccess: () => {
      message.success('삭제했습니다.')
      refresh()
    },
    onError: () => message.error('삭제에 실패했습니다.'),
  })

  const openEditFromProgress = async (id: number) => {
    try {
      const { data } = await client.get<ApiResponse<ReceptionRow>>(`${apiPrefix()}/homes/receptions/${id}`)
      const full = unwrap(data) as ReceptionRow
      setProgressId(null)
      setCreating(false)
      setDetail(full)
      editForm.setFieldsValue({
        ...full,
        orderDate: full.orderDate ? dayjs(full.orderDate) : undefined,
        openDate: full.openDate || full.opened ? dayjs(full.openDate || full.opened) : undefined,
        giftDate: full.giftDate ? dayjs(full.giftDate) : undefined,
      })
    } catch {
      message.error('상세 조회에 실패했습니다.')
    }
  }

  const downloadExcel = async () => {
    try {
      const { data } = await client.get(`${apiPrefix()}/homes/receptions/excel`, {
        params: { ...filters, page: undefined, size: undefined },
        responseType: 'blob',
      })
      const url = URL.createObjectURL(data)
      const a = document.createElement('a')
      a.href = url
      a.download = '접수리스트.csv'
      a.click()
      URL.revokeObjectURL(url)
    } catch {
      message.error('엑셀 다운로드에 실패했습니다.')
    }
  }

  const allChecked = list.length > 0 && selected.length === list.length
  const toggleAll = (checked: boolean) => setSelected(checked ? list.map((r) => r.id) : [])

  const productTypeLabel = (row: ReceptionRow) => {
    const t = row.productType
    if (t === 'e01') return '인터넷'
    if (t === 'e02') return '전화'
    if (t === 'e03') return 'TV'
    if (t === 'e04') return '렌탈'
    return row.productCategory || '-'
  }

  const rows = useMemo(() => list, [list])

  return (
    <div className="reception-order-page stock-page">
      <div className="stock-title">
        <div>
          <h2>접수관리 - 접수리스트</h2>
          <p>접수 내역을 조회하고 업무 진행을 관리합니다.</p>
        </div>
        <div className="stock-title-actions">
          <Dropdown
            trigger={['click']}
            dropdownRender={() => (
              <div className="reception-apply-dropdown">
                <div className="reception-apply-dropdown-title">신규신청</div>
                <ul className="reception-apply-dropdown-list">
                  {(ispQuery.data || []).map((isp) => (
                    <li key={isp.id}>
                      <button type="button" onClick={() => setApplyIsp(isp)}>{isp.name}</button>
                    </li>
                  ))}
                  {!ispQuery.data?.length && !ispQuery.isLoading ? (
                    <li className="reception-apply-dropdown-empty">등록된 통신사가 없습니다.</li>
                  ) : null}
                </ul>
              </div>
            )}
          >
            <Button type="primary">신규신청 <DownOutlined /></Button>
          </Dropdown>
          <Button
            disabled={!selected.length}
            onClick={() => {
              if (!selected.length) {
                message.warning('대상 접수를 선택하세요.')
                return
              }
              setBulkOpen(true)
            }}
          >
            일괄진행
          </Button>
          <Button
            danger
            disabled={!selected.length}
            onClick={() => {
              if (window.confirm(`${selected.length}건을 삭제하시겠습니까?`)) deleteMut.mutate(selected)
            }}
          >
            선택삭제
          </Button>
        </div>
      </div>

      <div className="toolbar order-top-buttons">
        <Button type="primary" onClick={search}>검색</Button>
        <Button onClick={reset}>검색 초기화</Button>
        <Button onClick={downloadExcel}>Excel 다운로드</Button>
        <Button onClick={downloadExcel}>사은품 Excel 다운로드</Button>
      </div>

      <div className="order-filter">
        <div className="order-date-row">
          <DatePicker
            value={draft.orderDateStart ? dayjs(draft.orderDateStart) : null}
            onChange={(d) => setD({ orderDateStart: d ? d.format('YYYY-MM-DD') : '' })}
          />
          <span>~</span>
          <DatePicker
            value={draft.orderDateEnd ? dayjs(draft.orderDateEnd) : null}
            onChange={(d) => setD({ orderDateEnd: d ? d.format('YYYY-MM-DD') : '' })}
          />
          <div className="quick">
            {(['today', 'yesterday', 'thisWeek', 'lastWeek', 'thisMonth', 'lastMonth', 'thisYear', 'lastYear'] as const).map((k) => (
              <button key={k} type="button" className="ghost sm" onClick={() => quick(k)}>
                {{
                  today: '금일',
                  yesterday: '전일',
                  thisWeek: '금주',
                  lastWeek: '전주',
                  thisMonth: '금월',
                  lastMonth: '전월',
                  thisYear: '금년',
                  lastYear: '전년',
                }[k]}
              </button>
            ))}
          </div>
          <label className="muted" style={{ fontSize: 12 }}>
            한 페이지당 갯수
            <input
              type="number"
              style={{ width: 56, display: 'inline-block', marginLeft: 4 }}
              value={draft.size}
              onChange={(e) => setD({ size: Number(e.target.value) || 50 })}
            />
          </label>
          <span className="order-result muted">검색 결과: 총 {(query.data?.total ?? 0).toLocaleString()} 건</span>
        </div>

        <div className="order-search-fields">
          <Select
            allowClear
            className="ff"
            placeholder="사은품"
            value={draft.giftType}
            onChange={(v) => setD({ giftType: v })}
            options={options(query.data?.giftCategories || ['상품권', '가전', '캐시백', '없음'])}
          />
          <input className="ff-i" placeholder="포스트잇" value={draft.postIt} onChange={(e) => setD({ postIt: e.target.value })} />
          <input className="ff-i" placeholder="약정" value={draft.agreementName} onChange={(e) => setD({ agreementName: e.target.value })} />
          <input className="ff-i" placeholder="주민번호" value={draft.customerSsid} onChange={(e) => setD({ customerSsid: e.target.value })} />
          <input className="ff-i" placeholder="이메일" value={draft.customerEmail} onChange={(e) => setD({ customerEmail: e.target.value })} />
          <label className="ff-d">
            개통일자
            <DatePicker
              value={draft.opended ? dayjs(draft.opended) : null}
              onChange={(d) => setD({ opended: d ? d.format('YYYY-MM-DD') : undefined })}
            />
          </label>
          <input className="ff-i" placeholder="담당자명" value={draft.branchEmployee} onChange={(e) => setD({ branchEmployee: e.target.value })} />
          <label className="ff-d">
            사은품일자
            <DatePicker
              value={draft.giftSended ? dayjs(draft.giftSended) : null}
              onChange={(d) => setD({ giftSended: d ? d.format('YYYY-MM-DD') : undefined })}
            />
          </label>
          <input className="ff-i" placeholder="영업점명" value={draft.branchName} onChange={(e) => setD({ branchName: e.target.value })} />
          <input className="ff-i" placeholder="통신사명" value={draft.ispName} onChange={(e) => setD({ ispName: e.target.value })} />
          <input className="ff-i" placeholder="상품명" value={draft.productName} onChange={(e) => setD({ productName: e.target.value })} />
        </div>
      </div>

      <div className="order-table-wrap">
        <table className="order-list">
          <thead>
            <tr>
              <th className="col-chk">
                <Checkbox checked={allChecked} onChange={(e) => toggleAll(e.target.checked)} />
              </th>
              <th className="col-id">접수번호</th>
              <th className="col-date">접수일</th>
              <th className="col-center">입력처</th>
              <th className="col-branch">그룹<br />영업점</th>
              <th className="col-isp">통신사</th>
              <th className="col-ptype">사은품종류<br />상품종류</th>
              <th className="col-product">상품명</th>
              <th className="col-customer">고객명<br /><span className="fs11">(포스트잇)</span></th>
              <th className="col-region">약정<br />지역</th>
              <th className="col-idnum">주민번호<br />연락처</th>
              <th className="col-status">담당자명<br />진행현황</th>
              <th className="col-contract">개통번호<br />개통일자</th>
              <th className="col-giftplace">지급처<br />지급날짜</th>
              <th className="col-gift">사은품현황<br /><span className="fs11">금액</span></th>
              <th className="col-cstatus">입력처<br />진행현황</th>
            </tr>
            <tr className="order-col-filter">
              <th className="col-chk">&nbsp;</th>
              <th className="col-id">&nbsp;</th>
              <th className="col-date">
                <select value={draft.sorting} onChange={(e) => applyF({ sorting: e.target.value })}>
                  <option value="order_date">접수일</option>
                  <option value="opended">개통일</option>
                </select>
              </th>
              <th className="col-center">
                <Select
                  allowClear
                  size="small"
                  placeholder="입력처"
                  value={draft.settleStatus}
                  onChange={(v) => applyF({ settleStatus: v })}
                  options={options(settleStatuses)}
                  style={{ width: '100%' }}
                />
              </th>
              <th className="col-branch">
                <Select
                  allowClear
                  size="small"
                  placeholder="영업점"
                  value={draft.branch}
                  onChange={(v) => applyF({ branch: v })}
                  options={options(query.data?.branches || [])}
                  style={{ width: '100%' }}
                />
              </th>
              <th className="col-isp">
                <Select
                  allowClear
                  size="small"
                  placeholder="통신사"
                  value={draft.carrier}
                  onChange={(v) => applyF({ carrier: v })}
                  options={options(query.data?.carriers || [])}
                  style={{ width: '100%' }}
                />
              </th>
              <th className="col-ptype">
                <Select
                  allowClear
                  size="small"
                  placeholder="상품종류"
                  value={draft.productType}
                  onChange={(v) => applyF({ productType: v })}
                  options={options(query.data?.productCategories || ['인터넷', '전화', 'TV', '렌탈'])}
                  style={{ width: '100%' }}
                />
              </th>
              <th className="col-product">&nbsp;</th>
              <th className="col-customer">
                <input
                  placeholder="고객명"
                  value={draft.customerName}
                  onChange={(e) => setD({ customerName: e.target.value })}
                  onKeyDown={(e) => e.key === 'Enter' && search()}
                />
              </th>
              <th className="col-region">
                <Select
                  allowClear
                  size="small"
                  placeholder="지역"
                  value={draft.customerSido}
                  onChange={(v) => applyF({ customerSido: v })}
                  options={options(SIDO_LIST)}
                  style={{ width: '100%' }}
                />
              </th>
              <th className="col-idnum">
                <input
                  placeholder="연락처"
                  value={draft.customerPhone}
                  onChange={(e) => setD({ customerPhone: e.target.value })}
                  onKeyDown={(e) => e.key === 'Enter' && search()}
                />
              </th>
              <th className="col-status">
                <Select
                  allowClear
                  size="small"
                  placeholder="진행현황"
                  value={draft.progressStatus}
                  onChange={(v) => applyF({ progressStatus: v })}
                  options={options(progressStatuses)}
                  style={{ width: '100%' }}
                />
              </th>
              <th className="col-contract">
                <input
                  placeholder="개통번호"
                  value={draft.contractNumber}
                  onChange={(e) => setD({ contractNumber: e.target.value })}
                  onKeyDown={(e) => e.key === 'Enter' && search()}
                />
              </th>
              <th className="col-giftplace">
                <Select
                  allowClear
                  size="small"
                  placeholder="지급처"
                  value={draft.giftPlace}
                  onChange={(v) => applyF({ giftPlace: v })}
                  options={[
                    { value: 'b01', label: '본사요청' },
                    { value: 'b02', label: '자체발송' },
                    { value: '본사', label: '본사' },
                    { value: '영업점', label: '영업점' },
                  ]}
                  style={{ width: '100%' }}
                />
              </th>
              <th className="col-gift">
                <Select
                  allowClear
                  size="small"
                  placeholder="사은품진행"
                  value={draft.giftStatus}
                  onChange={(v) => applyF({ giftStatus: v })}
                  options={options(giftStatuses)}
                  style={{ width: '100%' }}
                />
              </th>
              <th className="col-cstatus">&nbsp;</th>
            </tr>
          </thead>
          <tbody>
            {query.isLoading && (
              <tr><td colSpan={16} className="muted" style={{ textAlign: 'center', padding: 24 }}>불러오는 중...</td></tr>
            )}
            {!query.isLoading && rows.length === 0 && (
              <tr><td colSpan={16} className="muted" style={{ textAlign: 'center', padding: 24 }}>검색 결과가 없습니다.</td></tr>
            )}
            {rows.map((o, idx) => {
              const rowNum = Number(filters.page) * Number(filters.size) + idx + 1
              const [od, ot] = splitDt(o.orderDate)
              const giftAmt = o.giftAmount ?? null
              return (
                <tr key={o.id} onClick={() => setProgressId(o.id)}>
                  <td className="col-chk" onClick={(e) => e.stopPropagation()}>
                    <Checkbox
                      checked={selected.includes(o.id)}
                      onChange={(e) => setSelected((prev) => (e.target.checked ? [...prev, o.id] : prev.filter((id) => id !== o.id)))}
                    />
                  </td>
                  <td className="col-id">
                    <p>{o.id.toLocaleString()}</p>
                    <p className="c-blue fs11">({rowNum})</p>
                  </td>
                  <td className="col-date" style={o.today ? { color: 'royalblue' } : undefined}>
                    <p>{od}</p>
                    <p className="fs11">{ot}</p>
                  </td>
                  <td className="col-center">
                    <p>{o.centerName || '본사'}</p>
                  </td>
                  <td className="col-branch">
                    <p className="c-green">{o.branchGroupName || o.branchGroup || ''}</p>
                    <p>{o.branchOfficeName || o.branch || ''}</p>
                  </td>
                  <td className="col-isp">{o.ispName || o.carrier || '-'}</td>
                  <td className="col-ptype">
                    <p className="c-name">{o.giftType || o.giftCategory || '-'}</p>
                    <p>{productTypeLabel(o)}</p>
                  </td>
                  <td className="col-product">{o.productName || '-'}</td>
                  <td className="col-customer">
                    <p>{o.customerName || '-'}</p>
                    {o.postIt ? <p className="c-name fs11">({o.postIt})</p> : null}
                    {o.postAdd ? <p className="c-name fs11">({o.postAdd})</p> : null}
                  </td>
                  <td className="col-region">
                    <p className="c-name">{o.agreementName || '-'}</p>
                    <p>{o.sido || o.region || ''}</p>
                  </td>
                  <td className="col-idnum">
                    <p className="c-name fs11">{o.identifyNumber || ''}</p>
                    <p className="fs11">{o.phone || ''}</p>
                  </td>
                  <td className="col-status floating-cell">
                    <p className="c-green">{o.employeeName || o.counselor || ''}</p>
                    <p><span className="badge">{o.status || o.progressStatus || ''}</span></p>
                    <div className="floating-layer">
                      <p>개통일: {o.opened || o.openDate || '-'}</p>
                      <p>해지일: {o.canceled || '-'}</p>
                      <p>정산상태: {o.settleStatus || o.centerStatus || '-'}</p>
                    </div>
                  </td>
                  <td className="col-contract">
                    <p className="c-blue">{o.contractNumber || ''}</p>
                    <p className="fs11">{o.opened || o.openDate || ''}</p>
                  </td>
                  <td className="col-giftplace">
                    <p>{giftPlaceLabel(o.giftPlace)}</p>
                    <p className="fs11">{o.giftSended || o.giftDate || ''}</p>
                  </td>
                  <td className="col-gift">
                    <p><span className="badge">{o.giftStatus || ''}</span></p>
                    <p>{num(giftAmt)}</p>
                  </td>
                  <td className="col-cstatus floating-cell">
                    {o.centerStatus || o.settleStatus || ''}
                    <div className="floating-layer right">
                      <p>정산상태: {o.settleStatus || '-'}</p>
                      <p>개통일: {o.opened || o.openDate || '-'}</p>
                      <p>해지일: {o.canceled || o.cancelDate || '-'}</p>
                    </div>
                  </td>
                </tr>
              )
            })}
          </tbody>
        </table>
      </div>

      <div className="order-pager">
        <Button
          disabled={Number(filters.page) <= 0}
          onClick={() => setFilters((p) => ({ ...p, page: Math.max(0, Number(p.page) - 1) }))}
        >
          이전
        </Button>
        <span className="muted">
          {Number(filters.page) + 1} / {Math.max(1, Math.ceil((query.data?.total || 0) / Number(filters.size || 50)))}
        </span>
        <Button
          disabled={(Number(filters.page) + 1) * Number(filters.size) >= (query.data?.total || 0)}
          onClick={() => setFilters((p) => ({ ...p, page: Number(p.page) + 1 }))}
        >
          다음
        </Button>
      </div>

      <Modal
        title={creating ? '접수등록' : `접수수정 #${detail?.id || ''}`}
        open={creating || Boolean(detail)}
        onCancel={() => { setCreating(false); setDetail(null) }}
        footer={null}
        destroyOnHidden
        width={720}
      >
        <Form
          form={editForm}
          layout="vertical"
          onFinish={(values) => {
            saveMut.mutate({
              ...values,
              orderDate: values.orderDate ? dayjs(values.orderDate).format('YYYY-MM-DD HH:mm:ss') : undefined,
              openDate: values.openDate ? dayjs(values.openDate).format('YYYY-MM-DD') : undefined,
              giftDate: values.giftDate ? dayjs(values.giftDate).format('YYYY-MM-DD') : undefined,
            })
          }}
        >
          <div className="reception-form-grid">
            <Form.Item name="orderDate" label="접수일" rules={[{ required: true }]}>
              <DatePicker showTime className="full-width" />
            </Form.Item>
            <Form.Item name="counselor" label="상담자" rules={[{ required: true }]}>
              <Input />
            </Form.Item>
            <Form.Item name="branch" label="지점"><Input /></Form.Item>
            <Form.Item name="carrier" label="통신사">
              <Select options={options(query.data?.carriers || ['KT', 'SKB', 'LGU+', 'SKT'])} />
            </Form.Item>
            <Form.Item name="productName" label="상품명" rules={[{ required: true }]}><Input /></Form.Item>
            <Form.Item name="customerName" label="고객명" rules={[{ required: true }]}><Input /></Form.Item>
            <Form.Item name="phone" label="연락처"><Input /></Form.Item>
            <Form.Item name="progressStatus" label="진행상황">
              <Select options={options(progressStatuses)} />
            </Form.Item>
            <Form.Item name="settleStatus" label="정산상태">
              <Select options={options(settleStatuses)} />
            </Form.Item>
            <Form.Item name="giftStatus" label="사은품진행">
              <Select options={options(giftStatuses)} />
            </Form.Item>
          </div>
          <div className="balance-modal-footer">
            <Button type="primary" htmlType="submit" loading={saveMut.isPending}>저장</Button>
            <Button onClick={() => { setCreating(false); setDetail(null) }}>취소</Button>
          </div>
        </Form>
      </Modal>

      <ReceptionBulkModal
        open={bulkOpen}
        selectedIds={selected}
        progressStatuses={progressStatuses}
        giftStatuses={giftStatuses}
        centerOptions={
          Array.from(new Set([
            ...(query.data?.processors || []),
            ...(query.data?.counselors || []),
            '본사',
          ].filter(Boolean)))
        }
        onCancel={() => setBulkOpen(false)}
        onSuccess={() => {
          setBulkOpen(false)
          refresh()
        }}
      />

      <ReceptionApplyModal
        open={Boolean(applyIsp)}
        isp={applyIsp}
        counselorOptions={query.data?.counselors || []}
        branchOptions={query.data?.branches || []}
        onCancel={() => setApplyIsp(null)}
        onSuccess={() => { setApplyIsp(null); refresh() }}
      />

      <ReceptionProgressModal
        open={progressId != null}
        receptionId={progressId}
        onClose={() => setProgressId(null)}
        onChanged={refresh}
        onEdit={openEditFromProgress}
        onCopyLine={(ispId) => {
          const isp = (ispQuery.data || []).find((i) => i.id === ispId)
          if (!isp) {
            message.warning('통신사를 찾을 수 없습니다.')
            return
          }
          setProgressId(null)
          setApplyIsp(isp)
        }}
      />
    </div>
  )
}
