import { useEffect, useState } from 'react'
import {
  Wrench, Plus, Trash2, Play, Pause, CheckCircle2, XCircle, UserCog, ClipboardEdit,
} from 'lucide-react'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Field, Modal, Empty, Card } from '../components/ui'
import { canWrite, canManage } from '../components/rbac'
import {
  getJobs, getJobBoard, getJobWorkload, createJob, updateJob, assignJob,
  transitionJob, reportJob, deleteJob, getWorkers, getEquipment, getWorkOrders,
} from '../api/client'

const STATUSES = ['', 'ASSIGNED', 'STARTED', 'PAUSED', 'DONE', 'CANCELLED']
const emptyForm = {
  workorderId: '', opSeq: 1, processCode: '', workerId: '', equipmentCode: '',
  assignedQty: 0, plannedStart: '', plannedEnd: '', remark: '',
}

export default function Jobs() {
  const [list, setList] = useState<any[]>([])
  const [board, setBoard] = useState<any>(null)
  const [workload, setWorkload] = useState<any[]>([])
  const [status, setStatus] = useState('')
  const [woNo, setWoNo] = useState('')
  const [editor, setEditor] = useState<any>(null)
  const [assignModal, setAssignModal] = useState<any>(null)
  const [workers, setWorkers] = useState<any[]>([])
  const [equipment, setEquipment] = useState<any[]>([])
  const [workorders, setWorkorders] = useState<any[]>([])
  const writable = canWrite()
  const manageable = canManage()

  const load = () => {
    getJobs({ status, woNo }).then(d => setList(d || [])).catch(() => setList([]))
    getJobBoard().then(setBoard).catch(() => {})
    getJobWorkload().then(d => setWorkload(Array.isArray(d) ? d : [])).catch(() => {})
  }
  useEffect(() => { load() }, [status])
  useEffect(() => {
    getWorkers().then(d => setWorkers(d || [])).catch(() => {})
    getEquipment().then(d => setEquipment(d || [])).catch(() => {})
    getWorkOrders().then(d => setWorkorders(d || [])).catch(() => {})
  }, [])

  const openNew = () => setEditor({ ...emptyForm, _new: true })
  const save = async () => {
    const { _new, id, ...payload } = editor
    if (_new) await createJob(payload); else await updateJob(id, payload)
    setEditor(null); load()
  }
  const remove = async (id: number) => { if (!window.confirm('삭제하시겠습니까?')) return; await deleteJob(id); load() }
  const doTransition = async (id: number, action: string) => { await transitionJob(id, action); load() }
  const doReport = async (j: any) => {
    const v = window.prompt(`'${j.jobNo}' 완료 수량 (현재 ${j.doneQty}/${j.assignedQty})`, String(j.assignedQty - j.doneQty))
    if (v == null) return
    await reportJob(j.id, Number(v)); load()
  }
  const doAssign = async () => {
    await assignJob(assignModal.id, { workerId: assignModal.workerId || undefined, equipmentCode: assignModal.equipmentCode || undefined })
    setAssignModal(null); load()
  }

  const boardCols: { key: string; label: string }[] = [
    { key: 'ASSIGNED', label: '배정' }, { key: 'STARTED', label: '진행' },
    { key: 'PAUSED', label: '일시정지' }, { key: 'DONE', label: '완료' },
  ]
  const boardCount = (k: string) => board?.[k] ?? board?.[k.toLowerCase()] ?? 0

  return (
    <div>
      <PageHeader title="작업관리 ★" subtitle="작업/작업자/설비 배정 · 작업 할당 · 진행 상태 전이 · 작업 이력"
        actions={writable && <Btn onClick={openNew}><Plus size={16} /> 작업 생성</Btn>} />

      {/* 작업 현황 보드 */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-5">
        {boardCols.map(c => (
          <div key={c.key} className="bg-card border border-edge rounded-xl p-4 text-center">
            <div className="text-xs text-slate-400">{c.label}</div>
            <div className="text-2xl font-bold mt-1 text-brand">{boardCount(c.key).toLocaleString()}</div>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-5 mb-5">
        {/* 작업 목록 */}
        <div className="lg:col-span-3">
          <div className="flex flex-wrap items-center gap-2 mb-3">
            <select className="inp w-36" value={status} onChange={e => setStatus(e.target.value)}>
              {STATUSES.map(t => <option key={t} value={t}>{t || '전체 상태'}</option>)}
            </select>
            <input value={woNo} onChange={e => setWoNo(e.target.value)} onKeyDown={e => e.key === 'Enter' && load()} placeholder="작업지시번호" className="inp w-44" />
            <Btn variant="ghost" onClick={load}>검색</Btn>
          </div>
          <div className="bg-card border border-edge rounded-xl overflow-hidden">
            <table className="w-full text-sm">
              <thead className="text-slate-500 text-xs bg-panel">
                <tr>
                  <th className="text-left py-3 px-4">작업번호</th><th className="text-left">작업지시</th>
                  <th className="text-left">공정</th><th className="text-left">작업자</th><th className="text-left">설비</th>
                  <th className="text-right">수량</th><th className="text-left">상태</th><th className="text-right px-4">작업</th>
                </tr>
              </thead>
              <tbody>
                {list.map(j => (
                  <tr key={j.id} className="border-t border-edge/50">
                    <td className="py-3 px-4 font-medium flex items-center gap-1.5"><Wrench size={14} className="text-brand" />{j.jobNo}</td>
                    <td className="text-slate-400 text-xs">{j.woNo}<div className="text-slate-500">{j.itemName || j.itemCode}</div></td>
                    <td className="text-slate-300 text-xs">{j.processName || j.processCode}</td>
                    <td className="text-slate-400 text-xs">{j.workerId || '-'}</td>
                    <td className="text-slate-400 text-xs">{j.equipmentCode || '-'}</td>
                    <td className="text-right text-slate-300">{j.doneQty}/{j.assignedQty}</td>
                    <td><StatusBadge status={j.status} /></td>
                    <td className="px-4">
                      <div className="flex items-center justify-end gap-2">
                        {writable && j.status === 'ASSIGNED' && <button onClick={() => doTransition(j.id, 'START')} title="시작" className="text-emerald-400 hover:text-emerald-300"><Play size={15} /></button>}
                        {writable && j.status === 'STARTED' && <button onClick={() => doTransition(j.id, 'PAUSE')} title="일시정지" className="text-amber-400 hover:text-amber-300"><Pause size={15} /></button>}
                        {writable && j.status === 'PAUSED' && <button onClick={() => doTransition(j.id, 'RESUME')} title="재개" className="text-emerald-400 hover:text-emerald-300"><Play size={15} /></button>}
                        {writable && (j.status === 'STARTED' || j.status === 'PAUSED') && <button onClick={() => doReport(j)} title="실적 보고" className="text-sky-400 hover:text-sky-300"><ClipboardEdit size={15} /></button>}
                        {writable && (j.status === 'STARTED' || j.status === 'PAUSED') && <button onClick={() => doTransition(j.id, 'DONE')} title="완료" className="text-emerald-400 hover:text-emerald-300"><CheckCircle2 size={15} /></button>}
                        {writable && j.status !== 'DONE' && j.status !== 'CANCELLED' && <button onClick={() => setAssignModal({ id: j.id, workerId: j.workerId || '', equipmentCode: j.equipmentCode || '' })} title="배정" className="text-slate-400 hover:text-brand"><UserCog size={15} /></button>}
                        {writable && j.status !== 'DONE' && j.status !== 'CANCELLED' && <button onClick={() => doTransition(j.id, 'CANCEL')} title="취소" className="text-rose-400 hover:text-rose-300"><XCircle size={15} /></button>}
                        {manageable && (j.status === 'ASSIGNED' || j.status === 'CANCELLED') && <button onClick={() => remove(j.id)} title="삭제" className="text-rose-400 hover:text-rose-300"><Trash2 size={15} /></button>}
                      </div>
                    </td>
                  </tr>
                ))}
                {list.length === 0 && <Empty colSpan={8} msg="작업이 없습니다." />}
              </tbody>
            </table>
          </div>
        </div>

        {/* 작업자 부하 */}
        <Card title="작업자별 부하">
          <div className="space-y-2 max-h-[420px] overflow-auto">
            {workload.map((w: any, i: number) => (
              <div key={i} className="bg-panel border border-edge rounded p-2.5">
                <div className="text-sm font-medium">{w.workerName || w.displayName || w.workerId}</div>
                <div className="text-[11px] text-slate-400 mt-0.5">진행 {w.activeJobs ?? w.inprogressJobs ?? 0}건 · 잔여 {Number(w.remainingQty ?? w.remaining ?? 0).toLocaleString()}</div>
              </div>
            ))}
            {workload.length === 0 && <p className="text-slate-500 text-xs py-4 text-center">부하 데이터 없음</p>}
          </div>
        </Card>
      </div>

      {editor && (
        <Modal title={editor._new ? '작업 생성' : '작업 수정'} onClose={() => setEditor(null)}>
          <div className="space-y-3">
            <Field label="작업지시">
              <select className="inp" value={editor.workorderId} onChange={e => setEditor({ ...editor, workorderId: e.target.value })}>
                <option value="">선택</option>
                {workorders.map((w: any) => <option key={w.id} value={w.id}>{w.woNo} · {w.itemName || w.itemCode}</option>)}
              </select>
            </Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="공정순서 (opSeq)"><input type="number" className="inp" value={editor.opSeq} onChange={e => setEditor({ ...editor, opSeq: Number(e.target.value) })} /></Field>
              <Field label="공정코드"><input className="inp" value={editor.processCode} onChange={e => setEditor({ ...editor, processCode: e.target.value })} /></Field>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <Field label="작업자">
                <select className="inp" value={editor.workerId} onChange={e => setEditor({ ...editor, workerId: e.target.value })}>
                  <option value="">미배정</option>
                  {workers.map((w: any) => <option key={w.id} value={w.id}>{w.displayName || w.username}</option>)}
                </select>
              </Field>
              <Field label="설비">
                <select className="inp" value={editor.equipmentCode} onChange={e => setEditor({ ...editor, equipmentCode: e.target.value })}>
                  <option value="">미배정</option>
                  {equipment.map((eq: any) => <option key={eq.id} value={eq.equipmentCode}>{eq.equipmentName || eq.equipmentCode}</option>)}
                </select>
              </Field>
            </div>
            <Field label="배정 수량"><input type="number" className="inp" value={editor.assignedQty} onChange={e => setEditor({ ...editor, assignedQty: Number(e.target.value) })} /></Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="계획 시작"><input type="datetime-local" className="inp" value={editor.plannedStart} onChange={e => setEditor({ ...editor, plannedStart: e.target.value })} /></Field>
              <Field label="계획 종료"><input type="datetime-local" className="inp" value={editor.plannedEnd} onChange={e => setEditor({ ...editor, plannedEnd: e.target.value })} /></Field>
            </div>
            <Field label="비고"><input className="inp" value={editor.remark} onChange={e => setEditor({ ...editor, remark: e.target.value })} /></Field>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setEditor(null)}>취소</Btn>
            <Btn onClick={save}>저장</Btn>
          </div>
        </Modal>
      )}

      {assignModal && (
        <Modal title="작업자/설비 배정" onClose={() => setAssignModal(null)}>
          <div className="space-y-3">
            <Field label="작업자">
              <select className="inp" value={assignModal.workerId} onChange={e => setAssignModal({ ...assignModal, workerId: e.target.value })}>
                <option value="">미배정</option>
                {workers.map((w: any) => <option key={w.id} value={w.id}>{w.displayName || w.username}</option>)}
              </select>
            </Field>
            <Field label="설비">
              <select className="inp" value={assignModal.equipmentCode} onChange={e => setAssignModal({ ...assignModal, equipmentCode: e.target.value })}>
                <option value="">미배정</option>
                {equipment.map((eq: any) => <option key={eq.id} value={eq.equipmentCode}>{eq.equipmentName || eq.equipmentCode}</option>)}
              </select>
            </Field>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setAssignModal(null)}>취소</Btn>
            <Btn onClick={doAssign}>배정</Btn>
          </div>
        </Modal>
      )}
    </div>
  )
}
