import { useEffect, useState } from 'react'
import { CalendarRange, Plus, Trash2 } 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 {
  getPlans, createPlan, updatePlan, transitionPlan, deletePlan, getItems,
} from '../api/client'

const STATUSES = ['', 'DRAFT', 'CONFIRMED', 'INPROGRESS', 'DONE', 'CANCELLED']
const emptyForm = { itemCode: '', planQty: 0, startDate: '', endDate: '', remark: '' }

const ACTIONS: Record<string, { action: string; label: string }[]> = {
  DRAFT: [{ action: 'CONFIRM', label: '확정' }, { action: 'CANCEL', label: '취소' }],
  CONFIRMED: [{ action: 'START', label: '착수' }, { action: 'CANCEL', label: '취소' }],
  INPROGRESS: [{ action: 'COMPLETE', label: '완료' }],
}

// 간단 간트(타임라인 바)
function ganttBar(p: any, min: number, max: number) {
  const s = p.startDate ? new Date(p.startDate).getTime() : min
  const e = p.endDate ? new Date(p.endDate).getTime() : max
  const span = Math.max(1, max - min)
  const left = ((s - min) / span) * 100
  const width = Math.max(2, ((e - s) / span) * 100)
  return { left: `${Math.max(0, left)}%`, width: `${Math.min(100, width)}%` }
}

export default function ProductionPlan() {
  const [list, setList] = useState<any[]>([])
  const [status, setStatus] = useState('')
  const [editor, setEditor] = useState<any>(null)
  const [items, setItems] = useState<any[]>([])
  const writable = canWrite()
  const manageable = canManage()

  const load = () => getPlans({ status }).then(d => setList(d || [])).catch(() => setList([]))
  useEffect(() => { load() }, [status])
  useEffect(() => { getItems({ itemType: 'PRODUCT' }).then(d => setItems(d || [])).catch(() => {}) }, [])

  const openNew = () => setEditor({ ...emptyForm, _new: true })
  const save = async () => {
    const { _new, id, ...payload } = editor
    if (_new) await createPlan(payload); else await updatePlan(id, payload)
    setEditor(null); load()
  }
  const remove = async (id: number) => { if (!window.confirm('삭제하시겠습니까?')) return; await deletePlan(id); load() }
  const act = async (id: number, action: string) => { await transitionPlan(id, action); load() }

  const dates = list.flatMap(p => [p.startDate, p.endDate]).filter(Boolean).map(d => new Date(d).getTime())
  const min = dates.length ? Math.min(...dates) : Date.now()
  const max = dates.length ? Math.max(...dates) : Date.now() + 86400000

  return (
    <div>
      <PageHeader title="생산계획" subtitle="생산 일정 계획 · 간트 타임라인"
        actions={writable && <Btn onClick={openNew}><Plus size={16} /> 생산계획</Btn>} />

      <div className="flex items-center gap-2 mb-4">
        <select className="inp w-36" value={status} onChange={e => setStatus(e.target.value)}>
          {STATUSES.map(t => <option key={t} value={t}>{t || '전체 상태'}</option>)}
        </select>
      </div>

      {/* 간트 */}
      <Card title="생산 일정 (간트)" icon={<CalendarRange size={15} />} className="mb-5">
        <div className="space-y-2">
          {list.map(p => {
            const g = ganttBar(p, min, max)
            return (
              <div key={p.id} className="flex items-center gap-3">
                <div className="w-40 text-xs text-slate-300 truncate">{p.itemName || p.itemCode}</div>
                <div className="flex-1 relative h-5 bg-ink rounded">
                  <div className="absolute h-5 rounded bg-brand/60 border border-brand text-[10px] text-white flex items-center px-1 overflow-hidden" style={g}>
                    {Number(p.planQty || 0).toLocaleString()}
                  </div>
                </div>
                <StatusBadge status={p.status} />
              </div>
            )
          })}
          {list.length === 0 && <p className="text-slate-500 text-sm py-4 text-center">생산계획이 없습니다.</p>}
        </div>
      </Card>

      <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-right">계획수량</th><th className="text-left">시작</th><th className="text-left">종료</th><th className="text-left">상태</th><th className="text-right px-4">작업</th></tr>
          </thead>
          <tbody>
            {list.map(p => (
              <tr key={p.id} className="border-t border-edge/50">
                <td className="py-3 px-4 font-medium">{p.itemName || p.itemCode}</td>
                <td className="text-right text-slate-300">{Number(p.planQty || 0).toLocaleString()}</td>
                <td className="text-slate-400 text-xs">{p.startDate || '-'}</td>
                <td className="text-slate-400 text-xs">{p.endDate || '-'}</td>
                <td><StatusBadge status={p.status} /></td>
                <td className="px-4">
                  <div className="flex items-center justify-end gap-2">
                    {writable && (ACTIONS[p.status] || []).map(a => <button key={a.action} onClick={() => act(p.id, a.action)} className="text-xs text-brand hover:underline">{a.label}</button>)}
                    {writable && p.status === 'DRAFT' && <button onClick={() => setEditor({ ...p, _new: false })} className="text-xs text-slate-400 hover:text-brand">편집</button>}
                    {manageable && <button onClick={() => remove(p.id)} className="text-rose-400 hover:text-rose-300"><Trash2 size={14} /></button>}
                  </div>
                </td>
              </tr>
            ))}
            {list.length === 0 && <Empty colSpan={6} msg="생산계획이 없습니다." />}
          </tbody>
        </table>
      </div>

      {editor && (
        <Modal title={editor._new ? '생산계획 작성' : '생산계획 편집'} onClose={() => setEditor(null)}>
          <div className="space-y-3">
            <Field label="품목(제품)">
              <select className="inp" value={editor.itemCode} onChange={e => setEditor({ ...editor, itemCode: e.target.value })}>
                <option value="">선택</option>
                {items.map((it: any) => <option key={it.id} value={it.itemCode}>{it.itemName} ({it.itemCode})</option>)}
              </select>
            </Field>
            <Field label="계획 수량"><input type="number" className="inp" value={editor.planQty} onChange={e => setEditor({ ...editor, planQty: Number(e.target.value) })} /></Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="시작일"><input type="date" className="inp" value={editor.startDate || ''} onChange={e => setEditor({ ...editor, startDate: e.target.value })} /></Field>
              <Field label="종료일"><input type="date" className="inp" value={editor.endDate || ''} onChange={e => setEditor({ ...editor, endDate: 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>
      )}
    </div>
  )
}
