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,
  Tooltip,
  message } from 'antd'
import CareTable from '../../components/CareTable'
import SubjectSettingsModal from '../../components/SubjectSettingsModal'
import {
  ClockCircleOutlined,
  CloseOutlined,
  DownloadOutlined,
  EditOutlined,
  MailOutlined,
  PlusSquareOutlined,
  ReloadOutlined,
  SearchOutlined,
  SettingOutlined } from '@ant-design/icons'
import client, { apiPrefix, unwrap, type ApiResponse } from '../../api/client'
import { options } from './homesShared'

const { RangePicker } = DatePicker

type PendingRow = {
  id: number
  status?: string
  pendingDate?: string
  pendingType?: string
  contents?: string
  customerName?: string
  phone?: string
  receiveEmployee?: string
  processDate?: string
  processEmployee?: string
  memo?: string
  pendingTime?: string
}

type PendingResult = {
  total: number
  list: PendingRow[]
  counts?: Record<string, number>
  types?: string[]
  statuses?: string[]
  receiveEmployees?: string[]
  processEmployees?: 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: '' }
}

export default function PendingPage() {
  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<PendingRow | null>(null)
  const [creating, setCreating] = useState(false)
  const [typeOpen, setTypeOpen] = useState(false)

  const query = useQuery({
    queryKey: ['homes-pendings', filters],
    queryFn: async () => {
      const { data } = await client.get<ApiResponse<PendingResult>>(`${apiPrefix()}/homes/pendings`, {
        params: {
          ...filters,
          pendingType: 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-pendings'] })
    setSelected([])
  }

  const staffOptions = useMemo(() => {
    const fromApi = [
      ...(query.data?.receiveEmployees || []),
      ...(query.data?.processEmployees || []),
    ]
    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 typeOptions = useMemo(() => {
    const fromApi = query.data?.types || ['일반', '약속1', '약속2']
    return fromApi.map((v) => ({ value: v, label: v }))
  }, [query.data?.types])

  const tabs = useMemo(() => {
    const types = query.data?.types || ['일반', '약속1', '약속2']
    return [
      { key: 'ALL', label: `전체 ${query.data?.counts?.ALL ?? query.data?.total ?? 0}` },
      ...types.map((t) => ({ key: t, label: `${t} ${query.data?.counts?.[t] ?? 0}` })),
    ]
  }, [query.data])

  const save = useMutation({
    mutationFn: async (values: Record<string, unknown>) => {
      const phone = [values.phone1, values.phone2, values.phone3]
        .map((v) => String(v || '').replace(/\D/g, ''))
        .filter(Boolean)
        .join('-')
      const payload: Record<string, unknown> = {
        receiveEmployee: values.receiveEmployee,
        employee: values.receiveEmployee,
        pendingDate: values.pendingDate ? dayjs(values.pendingDate as Dayjs).format('YYYY-MM-DD') : undefined,
        pendingType: values.pendingType,
        contents: values.contents,
        customerName: values.customerName,
        phone: phone || undefined,
        memo: values.memo,
        status: values.status || (editing?.status ?? '접수') }
      if (editing) {
        const { data } = await client.put(`${apiPrefix()}/homes/pendings/${editing.id}`, payload)
        return unwrap(data as ApiResponse)
      }
      const { data } = await client.post(`${apiPrefix()}/homes/pendings`, 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 processMut = useMutation({
    mutationFn: async (ids: number[]) => {
      const { data } = await client.post(`${apiPrefix()}/homes/pendings/process`, { ids })
      return unwrap(data as ApiResponse<{ updated: number }>)
    },
    onSuccess: (data) => {
      message.success(`${data.updated}건을 처리했습니다.`)
      refresh()
    },
    onError: (e: Error) => message.error(e.message) })

  const saveTypes = useMutation({
    mutationFn: async (types: string[]) => {
      const { data } = await client.put(`${apiPrefix()}/homes/pendings/types`, { types })
      return unwrap(data as ApiResponse<{ types: string[] }>)
    },
    onSuccess: () => {
      message.success('과목을 저장했습니다.')
      setTypeOpen(false)
      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,
      status: values.status || undefined,
      receiveEmployee: values.receiveEmployee || undefined,
      processEmployee: values.processEmployee || undefined,
      phoneTail: values.phoneTail || 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({
      receiveEmployee: defaultStaff,
      pendingDate: undefined,
      pendingType: typeOptions[0]?.value || '일반',
      contents: undefined,
      customerName: undefined,
      phone1: '010',
      phone2: '',
      phone3: '',
      memo: undefined,
      status: '접수' })
  }

  const openEdit = (row: PendingRow) => {
    setCreating(false)
    setEditing(row)
    const phones = splitPhone(row.phone)
    editForm.setFieldsValue({
      receiveEmployee: row.receiveEmployee,
      pendingDate: row.pendingDate ? dayjs(row.pendingDate) : undefined,
      pendingType: row.pendingType,
      contents: row.contents,
      customerName: row.customerName,
      ...phones,
      memo: row.memo,
      status: row.status || '접수' })
  }

  const download = async () => {
    try {
      const { data } = await client.get(`${apiPrefix()}/homes/pendings/export`, {
        params: { ...filters, pendingType: 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 openTypeSettings = () => setTypeOpen(true)

  const typeItems = query.data?.types || ['일반', '약속1', '약속2']

  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: PendingRow) => (
        <Checkbox
          checked={selected.includes(row.id)}
          onChange={(e) => setSelected((prev) => (e.target.checked ? [...prev, row.id] : prev.filter((id) => id !== row.id)))}
        />
      ) },
    {
      title: '상태',
      dataIndex: 'status',
      width: 70,
      render: (v: string) => <span className={v === '접수' ? 'pending-status-open' : ''}>{v || '-'}</span> },
    {
      title: '일자',
      dataIndex: 'pendingDate',
      width: 100,
      sorter: (a: PendingRow, b: PendingRow) => String(a.pendingDate || '').localeCompare(String(b.pendingDate || '')) },
    { title: '과목', dataIndex: 'pendingType', width: 80 },
    { title: '내용', dataIndex: 'contents', width: 160, ellipsis: true },
    {
      title: '고객명',
      dataIndex: 'customerName',
      width: 90,
      render: (v: string) => maskName(v) },
    {
      title: '연락처',
      dataIndex: 'phone',
      width: 120,
      render: (v: string) => maskPhone(v) },
    { title: '접수직원', dataIndex: 'receiveEmployee', width: 90 },
    {
      title: '처리일',
      dataIndex: 'processDate',
      width: 100,
      sorter: (a: PendingRow, b: PendingRow) => String(a.processDate || '').localeCompare(String(b.processDate || '')),
      render: (v: string) => v || '-' },
    {
      title: '처리직원',
      dataIndex: 'processEmployee',
      width: 90,
      render: (v: string) => v || '-' },
    {
      title: '비고',
      dataIndex: 'memo',
      width: 54,
      align: 'center' as const,
      render: (v: string) => (v ? <Tooltip title={v}><MailOutlined className="memo-icon" /></Tooltip> : '-') },
    {
      title: '관리',
      width: 72,
      fixed: 'right' as const,
      align: 'center' as const,
      render: (_: unknown, row: PendingRow) => (
        <Button
          size="small"
          type="primary"
          className="pending-manage-btn"
          icon={<EditOutlined />}
          onClick={() => openEdit(row)}
        />
      ) },
  ]

  const modalOpen = creating || Boolean(editing)

  return (
    <div className="stock-page pending-manage-page">
      <div className="stock-title">
        <div>
          <h2>
            <ClockCircleOutlined className="product-title-icon" />
            일정관리
          </h2>
          <p>일정관리와 관련된 모든 업무를 관리하실 수 있습니다.</p>
        </div>
        <Space className="stock-title-actions" wrap>
          <Button
            disabled={!selected.length}
            loading={processMut.isPending}
            onClick={() => {
              if (!selected.length) {
                message.warning('처리할 약속을 선택하세요.')
                return
              }
              processMut.mutate(selected)
            }}
          >
            일정처리
          </Button>
          <Button className="pending-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().add(1, 'month').startOf('month'), dayjs().add(1, 'month').endOf('month'))}>익월</Button>
              <Button onClick={() => setPreset(dayjs().add(2, 'month').startOf('month'), dayjs().add(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="status">
              <Select allowClear placeholder="상태" className="w-110" options={options(['접수', '해결', '보류', '취소'])} />
            </Form.Item>
            <Form.Item name="receiveEmployee">
              <Select allowClear showSearch placeholder="접수직원" className="w-120" options={staffOptions} optionFilterProp="label" />
            </Form.Item>
            <Form.Item name="processEmployee">
              <Select allowClear showSearch placeholder="처리직원" className="w-120" options={staffOptions} optionFilterProp="label" />
            </Form.Item>
            <Form.Item name="phoneTail">
              <Input placeholder="연락처(뒷4자리)" className="w-140" maxLength={4} 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}
          />
          <Space>
            <Button type="link" icon={<SettingOutlined />} onClick={openTypeSettings}>과목설정</Button>
            <Button type="link" icon={<DownloadOutlined />} onClick={download}>엑셀다운로드</Button>
          </Space>
        </div>
        <CareTable
          rowKey="id"
          size="small"
          loading={query.isLoading}
          dataSource={query.data?.list}
          columns={columns}
          scroll={{ x: 1200 }}
          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={560}
        className="pending-modal"
      >
        <Form
          form={editForm}
          layout="horizontal"
          labelCol={{ flex: '100px' }}
          wrapperCol={{ flex: 1 }}
          onFinish={(values) => save.mutate(values)}
          className="balance-edit-form"
        >
          <Form.Item name="receiveEmployee" label="접수직원" rules={[{ required: true, message: '접수직원을 선택하세요' }]}>
            <Select options={staffOptions} showSearch optionFilterProp="label" />
          </Form.Item>
          <Form.Item name="pendingDate" label="일자" rules={[{ required: true, message: '예정일을 선택해주세요.' }]}>
            <DatePicker className="full-width" placeholder="예정일을 선택해주세요." />
          </Form.Item>
          <Form.Item label="과목" required>
            <Space.Compact className="full-width">
              <Form.Item name="pendingType" noStyle rules={[{ required: true, message: '과목을 선택하세요' }]}>
                <Select options={typeOptions} style={{ width: '100%' }} />
              </Form.Item>
              <Button icon={<SettingOutlined />} onClick={openTypeSettings}>설정</Button>
            </Space.Compact>
          </Form.Item>
          <Form.Item name="contents" label="내용" rules={[{ required: true, message: '내용을 입력하세요' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="customerName" label="고객명">
            <Input />
          </Form.Item>
          <Form.Item label="연락처">
            <Space.Compact>
              <Form.Item name="phone1" noStyle><Input style={{ width: 70 }} maxLength={3} /></Form.Item>
              <Form.Item name="phone2" noStyle><Input style={{ width: 80 }} maxLength={4} /></Form.Item>
              <Form.Item name="phone3" noStyle><Input style={{ width: 80 }} maxLength={4} /></Form.Item>
            </Space.Compact>
          </Form.Item>
          <Form.Item name="memo" label="비고" extra="최대 1,000자">
            <Input.TextArea rows={4} maxLength={1000} showCount />
          </Form.Item>
          <div className="balance-modal-footer">
            <Button className="pending-submit-btn" type="primary" htmlType="submit" loading={save.isPending}>
              {editing ? '수정합니다' : '등록'}
            </Button>
            <Button onClick={() => { setCreating(false); setEditing(null) }}>취소</Button>
          </div>
        </Form>
      </Modal>

      <SubjectSettingsModal
        open={typeOpen}
        items={typeItems}
        saving={saveTypes.isPending}
        submitClassName="pending-submit-btn"
        onCancel={() => setTypeOpen(false)}
        onSave={(types) => saveTypes.mutate(types)}
      />
    </div>
  )
}
