import { useEffect, useState } from 'react'
import { Warehouse, Plus, Trash2, MapPin } from 'lucide-react'
import { PageHeader, Btn, Field, Modal, Empty, Card } from '../components/ui'
import { canManage } from '../components/rbac'
import {
  getWarehouses, createWarehouse, updateWarehouse, deleteWarehouse,
  getLocations, createLocation, deleteLocation,
} from '../api/client'

const emptyWh = { warehouseCode: '', warehouseName: '', address: '', remark: '' }

export default function Warehouses() {
  const [list, setList] = useState<any[]>([])
  const [sel, setSel] = useState<any>(null)
  const [locations, setLocations] = useState<any[]>([])
  const [editor, setEditor] = useState<any>(null)
  const [locForm, setLocForm] = useState<any>(null)
  const manageable = canManage()

  const load = () => getWarehouses().then(d => setList(d || [])).catch(() => setList([]))
  useEffect(() => { load() }, [])

  const selectWh = async (w: any) => { setSel(w); setLocations(await getLocations(w.warehouseCode).catch(() => []) || []) }

  const openNew = () => setEditor({ ...emptyWh, _new: true })
  const save = async () => {
    const { _new, id, ...payload } = editor
    if (_new) await createWarehouse(payload); else await updateWarehouse(id, payload)
    setEditor(null); load()
  }
  const remove = async (id: number) => { if (!window.confirm('삭제하시겠습니까?')) return; await deleteWarehouse(id); load(); if (sel?.id === id) { setSel(null); setLocations([]) } }

  const openLoc = () => setLocForm({ warehouseCode: sel.warehouseCode, locationCode: '', locationName: '', binType: 'SHELF' })
  const saveLoc = async () => { await createLocation(locForm); setLocForm(null); selectWh(sel) }
  const removeLoc = async (id: number) => { if (!window.confirm('로케이션 삭제?')) return; await deleteLocation(id); selectWh(sel) }

  return (
    <div>
      <PageHeader title="창고 / 로케이션" subtitle="창고 · 로케이션(bin) 관리"
        actions={manageable && <Btn onClick={openNew}><Plus size={16} /> 창고</Btn>} />

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <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-right px-4">작업</th></tr>
            </thead>
            <tbody>
              {list.map(w => (
                <tr key={w.id} className={`border-t border-edge/50 cursor-pointer ${sel?.id === w.id ? 'bg-panel/60' : 'hover:bg-panel/30'}`} onClick={() => selectWh(w)}>
                  <td className="py-3 px-4 font-medium flex items-center gap-1.5"><Warehouse size={14} className="text-brand" />{w.warehouseCode}</td>
                  <td className="text-slate-300">{w.warehouseName}</td>
                  <td className="text-slate-400 text-xs truncate max-w-[160px]">{w.address || '-'}</td>
                  <td className="px-4" onClick={e => e.stopPropagation()}>
                    {manageable && <div className="flex items-center justify-end gap-2">
                      <button onClick={() => setEditor({ ...w, _new: false })} className="text-xs text-slate-400 hover:text-brand">편집</button>
                      <button onClick={() => remove(w.id)} className="text-rose-400 hover:text-rose-300"><Trash2 size={14} /></button>
                    </div>}
                  </td>
                </tr>
              ))}
              {list.length === 0 && <Empty colSpan={4} msg="창고가 없습니다." />}
            </tbody>
          </table>
        </div>

        <Card title={sel ? `로케이션 — ${sel.warehouseName}` : '로케이션 (창고 선택)'} icon={<MapPin size={15} />}>
          {!sel ? <p className="text-slate-500 text-sm py-6 text-center">왼쪽에서 창고를 선택하세요.</p> : (
            <>
              {manageable && <div className="mb-3"><Btn size="sm" variant="ghost" onClick={openLoc}><Plus size={13} /> 로케이션 추가</Btn></div>}
              <div className="space-y-1.5 max-h-[420px] overflow-auto">
                {locations.map((l: any) => (
                  <div key={l.id} className="flex items-center justify-between bg-panel border border-edge rounded p-2 text-sm">
                    <span className="flex items-center gap-1.5"><MapPin size={12} className="text-brand" /><span className="font-mono text-xs">{l.locationCode}</span> <span className="text-slate-400">{l.locationName || ''}</span></span>
                    <span className="flex items-center gap-2">
                      <span className="text-[11px] text-slate-500">{l.binType || ''}</span>
                      {manageable && <button onClick={() => removeLoc(l.id)} className="text-rose-400 hover:text-rose-300"><Trash2 size={12} /></button>}
                    </span>
                  </div>
                ))}
                {locations.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">
            <div className="grid grid-cols-2 gap-3">
              <Field label="코드"><input className="inp" value={editor.warehouseCode} onChange={e => setEditor({ ...editor, warehouseCode: e.target.value })} disabled={!editor._new} /></Field>
              <Field label="창고명"><input className="inp" value={editor.warehouseName} onChange={e => setEditor({ ...editor, warehouseName: e.target.value })} /></Field>
            </div>
            <Field label="주소"><input className="inp" value={editor.address} onChange={e => setEditor({ ...editor, address: e.target.value })} /></Field>
            <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>
      )}

      {locForm && (
        <Modal title="로케이션 추가" onClose={() => setLocForm(null)}>
          <div className="space-y-3">
            <Field label="로케이션 코드"><input className="inp" value={locForm.locationCode} onChange={e => setLocForm({ ...locForm, locationCode: e.target.value })} /></Field>
            <Field label="로케이션명"><input className="inp" value={locForm.locationName} onChange={e => setLocForm({ ...locForm, locationName: e.target.value })} /></Field>
            <Field label="유형">
              <select className="inp" value={locForm.binType} onChange={e => setLocForm({ ...locForm, binType: e.target.value })}>
                {['SHELF', 'RACK', 'FLOOR', 'PALLET', 'BIN'].map(t => <option key={t}>{t}</option>)}
              </select>
            </Field>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setLocForm(null)}>취소</Btn>
            <Btn onClick={saveLoc}>추가</Btn>
          </div>
        </Modal>
      )}
    </div>
  )
}
