import { useMemo, useState } from 'react'
import Modal from '../../components/DraggableModal'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import dayjs, { type Dayjs } from 'dayjs'
import {
  Button,
  Card,
  Checkbox,
  DatePicker,
  Form,
  Input,
  Select,
  Space,
  Tabs,
  Upload,
  message } from 'antd'
import CareTable from '../../components/CareTable'
import {
  CloseOutlined,
  DownloadOutlined,
  EditOutlined,
  PaperClipOutlined,
  PlusSquareOutlined,
  ReloadOutlined,
  SearchOutlined } from '@ant-design/icons'
import client, { apiPrefix, unwrap, type ApiResponse } from '../../api/client'
import { options } from './homesShared'

const { RangePicker } = DatePicker

/** 원본 예약관리 타이틀 잎 아이콘 */
function LeafOutlined({ className }: { className?: string }) {
  return (
    <span className={className} role="img" aria-label="leaf">
      <svg viewBox="0 0 24 24" width="1em" height="1em" fill="currentColor" aria-hidden>
        <path d="M17 8C8 10 5.9 16.17 3.82 21.34l1.89.66.95-2.3c.10.0.1.1.34.01C19 20 22 3 22 3c-1 2-8 2.25-13 3.25S2 11.5 2 13.5s1.75 3.75 1.75 3.75C7 8 17 8 17 8z" />
      </svg>
    </span>
  )
}

const INTERNET_OPTS = ['인터넷', 'TV', '전화', '와이파이', '스마트홈', '기타']
const RENTAL_OPTS = ['정수기', '공기청정기', '비데', '매트리스', '가전', '기타']

type BookingRow = {
  id: number
  status?: string
  bookingDate?: string
  customerName?: string
  phone?: string
  internetProducts?: string
  rentalProducts?: string
  internetNote?: string
  rentalNote?: string
  zipcode?: string
  address?: string
  addressDetail?: string
  employee?: string
  receiveEmployee?: string
  memo?: string
  fileName?: string
}

type BookingResult = {
  total: number
  list: BookingRow[]
  counts?: Record<string, number>
  employees?: string[]
  internetOptions?: string[]
  rentalOptions?: string[]
}

const initial = { page: 0, size: 10, tab: 'ALL' } as Record<string, unknown>

const maskName = (name?: string) => {
  if (!name) return '-'
  if (name.length <= 1) return name
  if (name.length === 2) return `${name[0]}*`
  return `${name[0]}*${name.slice(2)}`
}

const maskPhone = (phone?: string) => {
  if (!phone) return '-'
  const digits = phone.replace(/\D/g, '')
  if (digits.length < 7) return phone
  if (digits.length === 10) return `${digits.slice(0, 3)}-****-${digits.slice(6)}`
  return `${digits.slice(0, 3)}-****-${digits.slice(-4)}`
}

const splitPhone = (phone?: string) => {
  const digits = (phone || '').replace(/\D/g, '')
  if (digits.length >= 10) {
    return {
      phone1: digits.slice(0, 3),
      phone2: digits.slice(3, digits.length - 4),
      phone3: digits.slice(-4) }
  }
  return { phone1: '010', phone2: '', phone3: '' }
}

const splitProducts = (v?: string) =>
  (v || '')
    .split(/[,，]/)
    .map((s) => s.trim())
    .filter(Boolean)

export default function BookingPage() {
  const [form] = Form.useForm()
  const [editForm] = Form.useForm()
  const qc = useQueryClient()
  const [filters, setFilters] = useState<Record<string, unknown>>(initial)
  const [selected, setSelected] = useState<number[]>([])
  const [editing, setEditing] = useState<BookingRow | null>(null)
  const [creating, setCreating] = useState(false)

  const query = useQuery({
    queryKey: ['homes-bookings', filters],
    queryFn: async () => {
      const { data } = await client.get<ApiResponse<BookingResult>>(`${apiPrefix()}/homes/bookings`, {
        params: {
          ...filters,
          status: filters.tab === 'ALL' ? undefined : filters.tab } })
      return unwrap(data)
    } })

  const members = useQuery({
    queryKey: ['homes/members-options'],
    queryFn: async () => {
      const { data } = await client.get<ApiResponse<{ list: { id: number; name?: string }[] }>>(`${apiPrefix()}/homes/members`, {
        params: { page: 0, size: 200 } })
      return unwrap(data)
    } })

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

  const staffOptions = useMemo(() => {
    const fromApi = query.data?.employees || []
    const fromMembers = (members.data?.list || []).map((m) => String(m.name || '')).filter(Boolean)
    return Array.from(new Set([...fromApi, ...fromMembers, '홍길동'])).map((v) => ({ value: v, label: v }))
  }, [query.data, members.data])

  const internetOptions = useMemo(
    () => options(query.data?.internetOptions?.length ? query.data.internetOptions : INTERNET_OPTS),
    [query.data?.internetOptions],
  )
  const rentalOptions = useMemo(
    () => options(query.data?.rentalOptions?.length ? query.data.rentalOptions : RENTAL_OPTS),
    [query.data?.rentalOptions],
  )

  const tabs = useMemo(
    () => [
      { key: 'ALL', label: `전체 ${query.data?.counts?.ALL ?? query.data?.total ?? 0}` },
      { key: '접수', label: `접수 ${query.data?.counts?.['접수'] ?? 0}` },
      { key: '완료', label: `완료 ${query.data?.counts?.['완료'] ?? 0}` },
      { key: '보류', label: `보류 ${query.data?.counts?.['보류'] ?? 0}` },
    ],
    [query.data],
  )

  const save = useMutation({
    mutationFn: async (values: Record<string, unknown>) => {
      const payload: Record<string, unknown> = {
        status: values.status || editing?.status || '접수',
        bookingDate: values.bookingDate ? dayjs(values.bookingDate as Dayjs).format('YYYY-MM-DD') : undefined,
        receiveEmployee: values.receiveEmployee,
        employee: values.receiveEmployee,
        customerName: values.customerName,
        phone1: values.phone1,
        phone2: values.phone2,
        phone3: values.phone3,
        zipcode: values.zipcode,
        address: values.address,
        addressDetail: values.addressDetail,
        internetProducts: values.internetProducts || [],
        rentalProducts: values.rentalProducts || [],
        internetNote: values.internetNote,
        rentalNote: values.rentalNote,
        memo: values.memo,
        fileName: values.fileName }
      if (editing) {
        const { data } = await client.put(`${apiPrefix()}/homes/bookings/${editing.id}`, payload)
        return unwrap(data as ApiResponse)
      }
      const { data } = await client.post(`${apiPrefix()}/homes/bookings`, payload)
      return unwrap(data as ApiResponse)
    },
    onSuccess: () => {
      message.success(editing ? '수정했습니다.' : '예약을 등록했습니다.')
      setCreating(false)
      setEditing(null)
      editForm.resetFields()
      refresh()
    },
    onError: (e: Error) => message.error(e.message) })

  const deleteMut = useMutation({
    mutationFn: async (ids: number[]) => {
      const { data } = await client.post(`${apiPrefix()}/homes/bookings/delete`, { ids })
      return unwrap(data as ApiResponse<{ deleted: number }>)
    },
    onSuccess: (data) => {
      message.success(`${data.deleted}건을 삭제했습니다.`)
      refresh()
    },
    onError: (e: Error) => message.error(e.message) })

  const setPreset = (from: Dayjs, to: Dayjs) => form.setFieldsValue({ dates: [from, to] })

  const onSearch = (values: Record<string, unknown>) => {
    const dates = values.dates as [Dayjs, Dayjs] | undefined
    setFilters({
      ...initial,
      receiveEmployee: values.receiveEmployee || undefined,
      internetProduct: values.internetProduct || undefined,
      rentalProduct: values.rentalProduct || undefined,
      phoneTail: values.phoneTail || undefined,
      q: values.q || undefined,
      dateFrom: dates?.[0]?.format('YYYY-MM-DD'),
      dateTo: dates?.[1]?.format('YYYY-MM-DD'),
      page: 0,
      size: values.size ?? filters.size ?? 10,
      tab: filters.tab })
  }

  const reset = () => {
    form.resetFields()
    form.setFieldsValue({ size: 10 })
    setFilters(initial)
  }

  const openCreate = () => {
    setEditing(null)
    setCreating(true)
    const defaultStaff = staffOptions[0]?.value || '홍길동'
    editForm.setFieldsValue({
      bookingDate: dayjs(),
      receiveEmployee: defaultStaff,
      customerName: undefined,
      phone1: '010',
      phone2: '',
      phone3: '',
      zipcode: undefined,
      address: undefined,
      addressDetail: undefined,
      internetProducts: [],
      rentalProducts: [],
      internetNote: undefined,
      rentalNote: undefined,
      memo: undefined,
      fileName: undefined,
      status: '접수' })
  }

  const openEdit = (row: BookingRow) => {
    setCreating(false)
    setEditing(row)
    const phones = splitPhone(row.phone)
    editForm.setFieldsValue({
      bookingDate: row.bookingDate ? dayjs(row.bookingDate) : dayjs(),
      receiveEmployee: row.receiveEmployee || row.employee,
      customerName: row.customerName,
      ...phones,
      zipcode: row.zipcode,
      address: row.address,
      addressDetail: row.addressDetail,
      internetProducts: splitProducts(row.internetProducts),
      rentalProducts: splitProducts(row.rentalProducts),
      internetNote: row.internetNote,
      rentalNote: row.rentalNote,
      memo: row.memo,
      fileName: row.fileName,
      status: row.status || '접수' })
  }

  const searchAddress = () => {
    message.info('주소검색(데모) — 직접 입력해 주세요.')
    editForm.setFieldsValue({
      zipcode: editForm.getFieldValue('zipcode') || '06236',
      address: editForm.getFieldValue('address') || '서울특별시 강남구' })
  }

  const download = async () => {
    try {
      const { data } = await client.get(`${apiPrefix()}/homes/bookings/export`, {
        params: { ...filters, status: filters.tab === 'ALL' ? undefined : filters.tab },
        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 columns = [
    {
      title: (
        <Checkbox
          checked={!!query.data?.list?.length && selected.length === query.data.list.length}
          indeterminate={selected.length > 0 && selected.length < (query.data?.list?.length || 0)}
          onChange={(e) => setSelected(e.target.checked ? (query.data?.list || []).map((r) => r.id) : [])}
        />
      ),
      width: 42,
      render: (_: unknown, row: BookingRow) => (
        <Checkbox
          checked={selected.includes(row.id)}
          onChange={(e) => setSelected((prev) => (e.target.checked ? [...prev, row.id] : prev.filter((id) => id !== row.id)))}
        />
      ) },
    {
      title: '접수일',
      dataIndex: 'bookingDate',
      width: 110,
      sorter: (a: BookingRow, b: BookingRow) => String(a.bookingDate || '').localeCompare(String(b.bookingDate || '')) },
    {
      title: '상태',
      dataIndex: 'status',
      width: 70,
      render: (v: string) => <span className={v === '접수' ? 'booking-status-open' : ''}>{v || '-'}</span> },
    {
      title: '고객명',
      dataIndex: 'customerName',
      width: 90,
      render: (v: string) => maskName(v) },
    {
      title: '연락처',
      dataIndex: 'phone',
      width: 130,
      render: (v: string) => maskPhone(v) },
    {
      title: '인터넷상품',
      dataIndex: 'internetProducts',
      width: 180,
      ellipsis: true,
      render: (v: string) => v || '-' },
    {
      title: '홈렌탈상품',
      dataIndex: 'rentalProducts',
      width: 180,
      ellipsis: true,
      render: (v: string) => v || '-' },
    {
      title: '접수직원',
      dataIndex: 'employee',
      width: 90,
      render: (_: string, row: BookingRow) => row.receiveEmployee || row.employee || '-' },
    {
      title: '관리',
      width: 64,
      fixed: 'right' as const,
      align: 'center' as const,
      render: (_: unknown, row: BookingRow) => (
        <Button
          size="small"
          type="primary"
          className="booking-manage-btn"
          icon={<EditOutlined />}
          onClick={() => openEdit(row)}
        />
      ) },
  ]

  const modalOpen = creating || Boolean(editing)

  return (
    <div className="stock-page booking-manage-page">
      <div className="stock-title">
        <div>
          <h2>
            <LeafOutlined className="product-title-icon" />
            예약관리
          </h2>
          <p>예약하시는 고객의 정보를 등록/관리하실 수 있습니다.</p>
        </div>
        <Space className="stock-title-actions" wrap>
          <Button
            disabled={!selected.length}
            loading={deleteMut.isPending}
            onClick={() => {
              if (!selected.length) {
                message.warning('삭제할 예약을 선택하세요.')
                return
              }
              deleteMut.mutate(selected)
            }}
          >
            삭제
          </Button>
          <Button className="booking-register-btn" type="primary" icon={<PlusSquareOutlined />} onClick={openCreate}>
            예약 등록
          </Button>
        </Space>
      </div>

      <Card className="stock-filter-card" size="small">
        <Form form={form} layout="inline" className="balance-filter" initialValues={{ size: 10 }} onFinish={onSearch}>
          <div className="stock-filter-row">
            <Form.Item name="dates">
              <RangePicker className="w-230" placeholder={['YYYY-MM-DD', 'YYYY-MM-DD']} />
            </Form.Item>
            <Space.Compact className="sheet-presets">
              <Button onClick={() => setPreset(dayjs(), dayjs())}>오늘</Button>
              <Button onClick={() => setPreset(dayjs().subtract(6, 'day'), dayjs())}>1주일</Button>
              <Button onClick={() => setPreset(dayjs().startOf('month'), dayjs().endOf('month'))}>당월</Button>
              <Button onClick={() => setPreset(dayjs().subtract(1, 'month').startOf('month'), dayjs().subtract(1, 'month').endOf('month'))}>전월</Button>
              <Button onClick={() => setPreset(dayjs().subtract(2, 'month').startOf('month'), dayjs().subtract(2, 'month').endOf('month'))}>전전월</Button>
            </Space.Compact>
            <Button className="sheet-clear" icon={<CloseOutlined />} onClick={() => form.setFieldValue('dates', undefined)} />
          </div>
          <div className="stock-filter-row">
            <Form.Item name="receiveEmployee">
              <Select allowClear showSearch placeholder="접수직원" className="w-120" options={staffOptions} optionFilterProp="label" />
            </Form.Item>
            <Form.Item name="internetProduct">
              <Select allowClear placeholder="인터넷상품" className="w-130" options={internetOptions} />
            </Form.Item>
            <Form.Item name="rentalProduct">
              <Select allowClear placeholder="홈렌탈상품" className="w-130" options={rentalOptions} />
            </Form.Item>
            <Form.Item name="phoneTail">
              <Input placeholder="연락처(뒷4자리)" className="w-140" maxLength={4} allowClear />
            </Form.Item>
            <Form.Item name="q">
              <Input placeholder="검색" className="w-160" allowClear />
            </Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>검색</Button>
            <Button icon={<ReloadOutlined />} onClick={reset}>초기화</Button>
            <Form.Item name="size" className="sheet-size">
              <Select
                className="w-150"
                options={[10, 15, 30, 50, 100].map((n) => ({ value: n, label: `목록 ${n}개씩 보기` }))}
                onChange={(size) => {
                  form.setFieldValue('size', size)
                  setFilters((v) => ({ ...v, size, page: 0 }))
                }}
              />
            </Form.Item>
          </div>
        </Form>
      </Card>

      <Card className="stock-table-card" size="small">
        <div className="stock-table-actions">
          <Tabs
            activeKey={String(filters.tab)}
            onChange={(tab) => setFilters((v) => ({ ...v, tab, page: 0 }))}
            items={tabs}
          />
          <Button type="link" icon={<DownloadOutlined />} onClick={download}>엑셀다운로드</Button>
        </div>
        <CareTable
          rowKey="id"
          size="small"
          loading={query.isLoading}
          dataSource={query.data?.list}
          columns={columns}
          scroll={{ x: 1100 }}
          pagination={{
            current: Number(filters.page) + 1,
            pageSize: Number(filters.size),
            total: query.data?.total,
            showSizeChanger: false,
            onChange: (page) => setFilters((v) => ({ ...v, page: page - 1 })) }}
          locale={{ emptyText: '등록된 자료가 없습니다.' }}
        />
      </Card>

      <Modal
        title={editing ? '예약 수정' : '예약 등록'}
        open={modalOpen}
        onCancel={() => { setCreating(false); setEditing(null) }}
        footer={null}
        destroyOnHidden
        width={640}
        className="booking-modal"
      >
        <Form
          form={editForm}
          layout="horizontal"
          labelCol={{ flex: '110px' }}
          wrapperCol={{ flex: 1 }}
          onFinish={(values) => save.mutate(values)}
          className="balance-edit-form"
        >
          <Form.Item name="bookingDate" label="접수일" rules={[{ required: true, message: '접수일을 선택하세요' }]}>
            <DatePicker className="full-width" />
          </Form.Item>
          <Form.Item name="receiveEmployee" label="접수직원" rules={[{ required: true, message: '접수직원을 선택하세요' }]}>
            <Select options={staffOptions} showSearch optionFilterProp="label" />
          </Form.Item>
          <Form.Item name="customerName" label="고객명" rules={[{ required: true, message: '고객명을 입력하세요' }]}>
            <Input />
          </Form.Item>
          <Form.Item label="연락처" required>
            <Space.Compact>
              <Form.Item name="phone1" noStyle rules={[{ required: true, message: '연락처를 입력하세요' }]}>
                <Input style={{ width: 70 }} maxLength={3} />
              </Form.Item>
              <Form.Item name="phone2" noStyle rules={[{ required: true, message: '연락처를 입력하세요' }]}>
                <Input style={{ width: 80 }} maxLength={4} />
              </Form.Item>
              <Form.Item name="phone3" noStyle rules={[{ required: true, message: '연락처를 입력하세요' }]}>
                <Input style={{ width: 80 }} maxLength={4} />
              </Form.Item>
            </Space.Compact>
          </Form.Item>
          <Form.Item label="주소">
            <div className="booking-address-row">
              <Button onClick={searchAddress}>주소검색</Button>
              <Form.Item name="zipcode" noStyle>
                <Input className="booking-zip" placeholder="우편번호" />
              </Form.Item>
              <Form.Item name="address" noStyle>
                <Input className="booking-addr" placeholder="기본주소" />
              </Form.Item>
            </div>
            <Form.Item name="addressDetail" noStyle>
              <Input className="booking-addr-detail" placeholder="상세주소" />
            </Form.Item>
          </Form.Item>
          <Form.Item name="internetProducts" label="인터넷상품">
            <Checkbox.Group options={INTERNET_OPTS} className="booking-check-group" />
          </Form.Item>
          <Form.Item name="internetNote" label=" " colon={false}>
            <Input placeholder="희망하시는 상품명 및 수량이 있으신 경우 입력해주세요." />
          </Form.Item>
          <Form.Item name="rentalProducts" label="홈렌탈상품">
            <Checkbox.Group options={RENTAL_OPTS} className="booking-check-group" />
          </Form.Item>
          <Form.Item name="rentalNote" label=" " colon={false}>
            <Input placeholder="희망하시는 상품명 및 수량이 있으신 경우 입력해주세요." />
          </Form.Item>
          <Form.Item name="memo" label="비고" extra="최대 1,000자">
            <Input.TextArea rows={4} maxLength={1000} showCount />
          </Form.Item>
          <Form.Item label="파일첨부">
            <Form.Item name="fileName" noStyle>
              <Input type="hidden" />
            </Form.Item>
            <Upload
              beforeUpload={(file) => {
                if (file.size > 20 * 1024 * 1024) {
                  message.error('최대 20M까지 첨부할 수 있습니다.')
                  return Upload.LIST_IGNORE
                }
                editForm.setFieldValue('fileName', file.name)
                message.success(`${file.name} 선택됨 (데모)`)
                return false
              }}
              maxCount={1}
              showUploadList={false}
            >
              <Button icon={<PaperClipOutlined />}>파일 선택</Button>
            </Upload>
            <div className="booking-file-hint">* 다량의 파일은 압축해서 올려주십시요. (최대 20M)</div>
            <Form.Item shouldUpdate={(prev, cur) => prev.fileName !== cur.fileName} noStyle>
              {() => {
                const name = editForm.getFieldValue('fileName')
                return name ? <div className="booking-file-name">{name}</div> : null
              }}
            </Form.Item>
          </Form.Item>
          <div className="booking-modal-footer">
            <div className="booking-modal-note">* 고객명, 연락처는 고객관리에도 동시등록됩니다.</div>
            <Space>
              <Button className="booking-submit-btn" type="primary" htmlType="submit" loading={save.isPending}>
                {editing ? '수정합니다' : '등록'}
              </Button>
              <Button onClick={() => { setCreating(false); setEditing(null) }}>취소</Button>
            </Space>
          </div>
        </Form>
      </Modal>
    </div>
  )
}
