import { useEffect, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import dayjs from 'dayjs'
import {
  Button,
  Checkbox,
  DatePicker,
  Input,
  Select,
  Space,
  message,
} from 'antd'
import Modal from './DraggableModal'
import PrgSection from './PrgSection'
import ReceptionProgressReadOnly from './ReceptionProgressReadOnly'
import client, { apiPrefix, unwrap, type ApiResponse } from '../api/client'

type Props = {
  open: boolean
  receptionId: number | null
  onClose: () => void
  onChanged?: () => void
  onEdit?: (id: number) => void
  onCopyLine?: (ispId: number) => void
}

type FormState = {
  postIt: string
  postAdd: string
  status: string
  adminOnly: boolean
  contractNumber: string
  installSchedule: string
  customerLoginId: string
  newTel: string
  multiLine: boolean
  addPayer: boolean
  record: boolean
  progressLog: string
  adminMemo: string
  openDate: string
  cancelDate: string
  giftStatus: string
  giftPlace: string
  giftProgressLog: string
  giftRequested: string
  giftSended: string
  changeOrderDate: boolean
  orderDate: string
}

const EMPTY: FormState = {
  postIt: '',
  postAdd: '',
  status: '',
  adminOnly: false,
  contractNumber: '',
  installSchedule: '',
  customerLoginId: '',
  newTel: '',
  multiLine: false,
  addPayer: false,
  record: false,
  progressLog: '',
  adminMemo: '',
  openDate: '',
  cancelDate: '',
  giftStatus: '',
  giftPlace: '',
  giftProgressLog: '',
  giftRequested: '',
  giftSended: '',
  changeOrderDate: false,
  orderDate: '',
}

function d10(v?: string | null) {
  return v ? String(v).replace('T', ' ').substring(0, 10) : ''
}
function dt16(v?: string | null) {
  return v ? String(v).replace('T', ' ').substring(0, 16) : ''
}

export default function ReceptionProgressModal({
  open,
  receptionId,
  onClose,
  onChanged,
  onEdit,
  onCopyLine,
}: Props) {
  const qc = useQueryClient()
  const [f, setF] = useState<FormState>(EMPTY)
  const [recreateIsp, setRecreateIsp] = useState<number | undefined>()

  const detailQuery = useQuery({
    queryKey: ['reception-progress', receptionId],
    queryFn: async () => {
      const { data } = await client.get<ApiResponse<Record<string, unknown>>>(
        `${apiPrefix()}/homes/receptions/${receptionId}`,
      )
      return unwrap(data) as Record<string, any>
    },
    enabled: open && receptionId != null,
  })

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

  const data = detailQuery.data
  const reception = data?.reception || data
  const progressStatuses: string[] = data?.progressStatuses || []
  const giftStatuses: string[] = data?.giftStatuses || []
  const progressLogs: any[] = data?.progressLogs || data?.logs || []
  const giftLogs: any[] = data?.giftProgressLogs || []

  useEffect(() => {
    if (!data || !reception) return
    const gift = data.gift || {}
    const customer = data.customer || {}
    setF({
      postIt: customer.postIt ?? reception.postIt ?? '',
      postAdd: customer.postAdd ?? reception.postAdd ?? '',
      status: '',
      adminOnly: false,
      contractNumber: reception.contractNumber ?? '',
      installSchedule: reception.installSchedule ?? '',
      customerLoginId: reception.customerLoginId ?? '',
      newTel: reception.newTel ?? '',
      multiLine: !!reception.multiLine,
      addPayer: !!reception.addPayer,
      record: !!reception.record,
      progressLog: '',
      adminMemo: data.etc?.adminMemo ?? reception.adminMemo ?? '',
      openDate: d10(reception.openDate),
      cancelDate: d10(reception.cancelDate),
      giftStatus: '',
      giftPlace: gift.place ?? reception.giftPlace ?? '',
      giftProgressLog: '',
      giftRequested: d10(gift.requested ?? reception.giftRequested),
      giftSended: d10(gift.sended ?? reception.giftSended),
      changeOrderDate: false,
      orderDate: d10(reception.orderDate),
    })
  }, [data]) // eslint-disable-line react-hooks/exhaustive-deps

  const set = (patch: Partial<FormState>) => setF((p) => ({ ...p, ...patch }))

  const saveMut = useMutation({
    mutationFn: async (closeAfter: boolean) => {
      const payload: Record<string, unknown> = {
        postIt: f.postIt,
        postAdd: f.postAdd,
        contractNumber: f.contractNumber,
        installSchedule: f.installSchedule,
        customerLoginId: f.customerLoginId,
        newTel: f.newTel,
        multiLine: f.multiLine,
        addPayer: f.addPayer,
        record: f.record,
        adminMemo: f.adminMemo,
        openDate: f.openDate || null,
        cancelDate: f.cancelDate || null,
        giftPlace: f.giftPlace,
        giftRequested: f.giftRequested || null,
        giftSended: f.giftSended || null,
        adminOnly: f.adminOnly,
        memo: f.progressLog,
        giftProgressLog: f.giftProgressLog,
        changeOrderDate: f.changeOrderDate,
        orderDate: f.changeOrderDate && f.orderDate ? `${f.orderDate} 00:00:00` : undefined,
      }
      if (f.status) payload.status = f.status
      if (f.giftStatus) payload.giftStatus = f.giftStatus
      const { data: res } = await client.post(
        `${apiPrefix()}/homes/receptions/${receptionId}/progress`,
        payload,
      )
      return { body: unwrap(res), closeAfter }
    },
    onSuccess: ({ closeAfter }) => {
      message.success('저장했습니다.')
      qc.invalidateQueries({ queryKey: ['reception-progress', receptionId] })
      qc.invalidateQueries({ queryKey: ['receptions'] })
      onChanged?.()
      if (closeAfter) onClose()
      else {
        setF((p) => ({ ...p, status: '', giftStatus: '', progressLog: '', giftProgressLog: '', adminOnly: false }))
        detailQuery.refetch()
      }
    },
    onError: () => message.error('저장에 실패했습니다.'),
  })

  const deleteMut = useMutation({
    mutationFn: async () => {
      const { data: res } = await client.delete(`${apiPrefix()}/homes/receptions/${receptionId}`)
      return unwrap(res)
    },
    onSuccess: () => {
      message.success('삭제했습니다.')
      qc.invalidateQueries({ queryKey: ['receptions'] })
      onChanged?.()
      onClose()
    },
    onError: () => message.error('삭제에 실패했습니다.'),
  })

  const delProgressLog = async (logId: number) => {
    try {
      await client.delete(`${apiPrefix()}/homes/receptions/progress-log/${logId}`)
      detailQuery.refetch()
      message.success('로그를 삭제했습니다.')
    } catch {
      message.error('로그 삭제에 실패했습니다.')
    }
  }

  const delGiftLog = async (logId: number) => {
    try {
      await client.delete(`${apiPrefix()}/homes/receptions/gift-progress-log/${logId}`)
      detailQuery.refetch()
      message.success('사은품 로그를 삭제했습니다.')
    } catch {
      message.error('로그 삭제에 실패했습니다.')
    }
  }

  const titleWarn = reception?.progressStatus === '9.취소' || reception?.detailProgress?.includes?.('주의')
  const title = receptionId
    ? `${titleWarn ? '⚠ 주의 요망 ' : ''}업무 진행 내역 — 접수 #${receptionId}`
    : '업무 진행 내역'

  return (
    <Modal
      title={title}
      open={open}
      onCancel={onClose}
      footer={null}
      destroyOnHidden
      width="96%"
      style={{ maxWidth: 900 }}
      className="reception-progress-modal order-progress-modal"
      styles={{ body: { maxHeight: 'calc(92vh - 56px)', overflowY: 'auto', padding: '12px 14px 16px' } }}
    >
      {detailQuery.isLoading || !data ? (
        <div style={{ padding: 12 }}>로딩 중...</div>
      ) : (
        <div className="prg-body">
          <ReceptionProgressReadOnly data={data} />

          <PrgSection title="업무 진행 내역">
            <table className="prg-table">
              <tbody>
                <tr>
                  <th>접수자</th>
                  <td colSpan={3}>
                    <div className="prg-inline">
                      <Input readOnly value={data.employeeName || reception?.counselor || ''} style={{ width: 200 }} />
                      <label className="prg-chk">
                        <Checkbox checked={f.adminOnly} onChange={(e) => set({ adminOnly: e.target.checked })} />
                        관리자 전용로그
                      </label>
                      <span className="prg-note-i">(관리자만 보이고 영업점은 보이지 않습니다.)</span>
                    </div>
                  </td>
                </tr>
                <tr>
                  <th>현재진행상황</th>
                  <td colSpan={3}>
                    <Input readOnly value={reception?.progressStatus || ''} style={{ width: 200 }} />
                  </td>
                </tr>
                <tr>
                  <th>포스트잇</th>
                  <td colSpan={3}>
                    <Input value={f.postIt} onChange={(e) => set({ postIt: e.target.value })} />
                  </td>
                </tr>
                <tr>
                  <th>추가메모</th>
                  <td colSpan={3}>
                    <Input value={f.postAdd} onChange={(e) => set({ postAdd: e.target.value })} />
                  </td>
                </tr>
                <tr>
                  <th>진행상황</th>
                  <td colSpan={3}>
                    <div className="prg-inline">
                      <Select
                        allowClear
                        placeholder="진행상황 선택"
                        style={{ minWidth: 180 }}
                        value={f.status || undefined}
                        onChange={(v) => set({ status: v || '' })}
                        options={progressStatuses.map((s) => ({ value: s, label: s }))}
                      />
                      <Button size="small" loading={saveMut.isPending} onClick={() => saveMut.mutate(false)}>
                        적 용
                      </Button>
                    </div>
                    <span className="prg-note">적용 버튼은 창을 닫지 않고 현재 설정을 저장합니다.</span>
                  </td>
                </tr>
                <tr>
                  <th>계약번호</th>
                  <td>
                    <Input value={f.contractNumber} onChange={(e) => set({ contractNumber: e.target.value })} />
                  </td>
                  <th>설치일정</th>
                  <td>
                    <Input value={f.installSchedule} onChange={(e) => set({ installSchedule: e.target.value })} />
                  </td>
                </tr>
                <tr>
                  <th>고객아이디</th>
                  <td>
                    <Input value={f.customerLoginId} onChange={(e) => set({ customerLoginId: e.target.value })} />
                  </td>
                  <th>신규전화번호</th>
                  <td>
                    <Input value={f.newTel} onChange={(e) => set({ newTel: e.target.value })} />
                  </td>
                </tr>
                <tr>
                  <th>접수유형</th>
                  <td colSpan={3}>
                    <div className="prg-inline">
                      <label className="prg-chk">
                        <Checkbox checked={f.multiLine} onChange={(e) => set({ multiLine: e.target.checked })} /> 다회선
                      </label>
                      <label className="prg-chk">
                        <Checkbox checked={f.addPayer} onChange={(e) => set({ addPayer: e.target.checked })} /> 납입자추가
                      </label>
                      <label className="prg-chk">
                        <Checkbox checked={f.record} onChange={(e) => set({ record: e.target.checked })} /> 녹취
                      </label>
                    </div>
                  </td>
                </tr>
                <tr>
                  <th>업무진행메모(LOG)</th>
                  <td colSpan={3}>
                    <Input.TextArea rows={4} value={f.progressLog} onChange={(e) => set({ progressLog: e.target.value })} />
                  </td>
                </tr>
                <tr>
                  <th>관리자메모</th>
                  <td colSpan={3}>
                    <Input.TextArea rows={3} value={f.adminMemo} onChange={(e) => set({ adminMemo: e.target.value })} />
                  </td>
                </tr>
                <tr>
                  <th>접수일자</th>
                  <td colSpan={3}>
                    <div className="prg-inline">
                      <DatePicker
                        value={f.orderDate ? dayjs(f.orderDate) : null}
                        onChange={(d) => set({ orderDate: d ? d.format('YYYY-MM-DD') : '' })}
                      />
                      <label className="prg-chk">
                        <Checkbox checked={f.changeOrderDate} onChange={(e) => set({ changeOrderDate: e.target.checked })} />
                        접수일자 변경
                      </label>
                    </div>
                  </td>
                </tr>
                <tr>
                  <th>개통일자</th>
                  <td>
                    <DatePicker
                      className="full-width"
                      style={{ width: '100%' }}
                      value={f.openDate ? dayjs(f.openDate) : null}
                      onChange={(d) => set({ openDate: d ? d.format('YYYY-MM-DD') : '' })}
                    />
                  </td>
                  <th>해지일자</th>
                  <td>
                    <DatePicker
                      className="full-width"
                      style={{ width: '100%' }}
                      value={f.cancelDate ? dayjs(f.cancelDate) : null}
                      onChange={(d) => set({ cancelDate: d ? d.format('YYYY-MM-DD') : '' })}
                    />
                  </td>
                </tr>
              </tbody>
            </table>
          </PrgSection>

          <PrgSection title="업무 진행 현황">
            <table className="prg-grid">
              <thead>
                <tr>
                  <th style={{ width: 150 }}>날짜</th>
                  <th style={{ width: 100 }}>진행상태</th>
                  <th style={{ width: 100 }}>담당자</th>
                  <th>내용</th>
                  <th style={{ width: 60 }}>삭제</th>
                </tr>
              </thead>
              <tbody>
                {progressLogs.map((l) => (
                  <tr key={l.id}>
                    <td className="center">{dt16(l.loggedAt || l.createdAt)}</td>
                    <td className="center">{l.status}</td>
                    <td className="center">{l.authorName || l.writer}</td>
                    <td>{l.adminOnly ? '[관리자] ' : ''}{l.memo}</td>
                    <td className="center">
                      <Button danger size="small" onClick={() => delProgressLog(l.id)}>삭제</Button>
                    </td>
                  </tr>
                ))}
                {progressLogs.length === 0 && (
                  <tr><td colSpan={5} className="muted" style={{ textAlign: 'center' }}>진행 내역이 없습니다.</td></tr>
                )}
              </tbody>
            </table>
          </PrgSection>

          <PrgSection title="사은품 진행 내역">
            <table className="prg-table">
              <tbody>
                <tr>
                  <th>사은품현재상황</th>
                  <td>
                    <Input readOnly value={data.gift?.status || reception?.giftStatus || ''} />
                  </td>
                  <th>사은품진행상황</th>
                  <td>
                    <Select
                      allowClear
                      placeholder="사은품 진행상황 선택"
                      style={{ width: '100%' }}
                      value={f.giftStatus || undefined}
                      onChange={(v) => set({ giftStatus: v || '' })}
                      options={giftStatuses.map((s) => ({ value: s, label: s }))}
                    />
                  </td>
                </tr>
                <tr>
                  <th>사은품 지급처</th>
                  <td>
                    <Select
                      allowClear
                      style={{ width: '100%' }}
                      value={f.giftPlace || undefined}
                      onChange={(v) => set({ giftPlace: v || '' })}
                      options={[
                        { value: 'b01', label: '본사요청' },
                        { value: 'b02', label: '자체발송' },
                        { value: '본사', label: '본사' },
                        { value: '영업점', label: '영업점' },
                      ]}
                    />
                  </td>
                  <th>지급요청/완료</th>
                  <td>
                    <Space>
                      <DatePicker
                        placeholder="요청일"
                        value={f.giftRequested ? dayjs(f.giftRequested) : null}
                        onChange={(d) => set({ giftRequested: d ? d.format('YYYY-MM-DD') : '' })}
                      />
                      <DatePicker
                        placeholder="완료일"
                        value={f.giftSended ? dayjs(f.giftSended) : null}
                        onChange={(d) => set({ giftSended: d ? d.format('YYYY-MM-DD') : '' })}
                      />
                    </Space>
                  </td>
                </tr>
                <tr>
                  <th>사은품진행메모</th>
                  <td colSpan={3}>
                    <Input.TextArea rows={3} value={f.giftProgressLog} onChange={(e) => set({ giftProgressLog: e.target.value })} />
                  </td>
                </tr>
              </tbody>
            </table>
          </PrgSection>

          <PrgSection title="사은품 진행 현황">
            <table className="prg-grid">
              <thead>
                <tr>
                  <th style={{ width: 150 }}>날짜</th>
                  <th style={{ width: 150 }}>사은품진행상태</th>
                  <th style={{ width: 100 }}>담당자</th>
                  <th>내용</th>
                  <th style={{ width: 60 }}>삭제</th>
                </tr>
              </thead>
              <tbody>
                {giftLogs.map((l) => (
                  <tr key={l.id}>
                    <td className="center">{dt16(l.loggedAt || l.createdAt)}</td>
                    <td className="center">{l.status}</td>
                    <td className="center">{l.authorName || l.writer}</td>
                    <td>{l.memo}</td>
                    <td className="center">
                      <Button danger size="small" onClick={() => delGiftLog(l.id)}>삭제</Button>
                    </td>
                  </tr>
                ))}
                {giftLogs.length === 0 && (
                  <tr><td colSpan={5} className="muted" style={{ textAlign: 'center' }}>사은품 진행 내역이 없습니다.</td></tr>
                )}
              </tbody>
            </table>
          </PrgSection>

          <div className="prg-foot">
            <div className="prg-foot-row">
              <Button type="primary" loading={saveMut.isPending} onClick={() => saveMut.mutate(true)}>
                등록
              </Button>
              <Button onClick={() => receptionId && onEdit?.(receptionId)}>수정</Button>
              <Button
                danger
                loading={deleteMut.isPending}
                onClick={() => {
                  if (window.confirm('이 접수를 삭제하시겠습니까?')) deleteMut.mutate()
                }}
              >
                삭제
              </Button>
              <Button onClick={onClose}>닫기</Button>
            </div>
            <div className="prg-foot-row">
              <Select
                allowClear
                placeholder="추가 회선 선택"
                style={{ minWidth: 220 }}
                value={recreateIsp}
                onChange={(v) => setRecreateIsp(v)}
                options={(ispQuery.data || []).map((i) => ({ value: i.id, label: i.name }))}
              />
              <Button
                onClick={() => {
                  if (!recreateIsp) {
                    message.warning('추가 회선 통신사를 선택하세요.')
                    return
                  }
                  onCopyLine?.(recreateIsp)
                }}
              >
                추가 회선 등록
              </Button>
            </div>
          </div>
        </div>
      )}
    </Modal>
  )
}
