import { useEffect, useState } from 'react'
import { Gauge, Plus, Wrench, Power } from 'lucide-react'
import Chart from '../components/Chart'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Field, Modal, Empty, Card } from '../components/ui'
import { canWrite, canManage } from '../components/rbac'
import {
  getOees, createOee, getDowntimePareto, getEquipment, setEquipmentRunStatus,
} from '../api/client'

const emptyForm = { equipmentCode: '', plannedTime: 480, runTime: 0, idealCycleTime: 1, totalCount: 0, goodCount: 0, recordDate: '' }
const RUN_STATES = ['RUN', 'IDLE', 'DOWN', 'MAINT']

function toChart(raw: any, name: string) {
  if (!raw) return undefined
  if (raw.labels && raw.series) return raw
  if (Array.isArray(raw)) return { labels: raw.map((r: any) => r.label || r.code || r.downtimeCode || r.name), series: [{ name, data: raw.map((r: any) => Number(r.value ?? r.minutes ?? r.count ?? 0)) }] }
  return undefined
}
function oeePct(o: any) {
  const v = o.oeePercent ?? (o.oee != null ? o.oee * 100 : null)
  return v != null ? Number(v).toFixed(1) : '-'
}

export default function Oee() {
  const [list, setList] = useState<any[]>([])
  const [equipment, setEquipment] = useState<any[]>([])
  const [pareto, setPareto] = useState<any>(null)
  const [eqCode, setEqCode] = useState('')
  const [editor, setEditor] = useState<any>(null)
  const writable = canWrite()
  const manageable = canManage()

  const load = () => {
    getOees({ equipmentCode: eqCode, limit: 50 }).then(d => setList(d || [])).catch(() => setList([]))
    getEquipment().then(d => setEquipment(d || [])).catch(() => {})
    getDowntimePareto(30).then(setPareto).catch(() => {})
  }
  useEffect(() => { load() }, [])

  const openNew = () => setEditor({ ...emptyForm })
  const save = async () => { await createOee(editor); setEditor(null); load() }
  const setRun = async (id: number, runStatus: string) => { await setEquipmentRunStatus(id, runStatus); load() }

  return (
    <div>
      <PageHeader title="설비 / OEE" subtitle="가동률 × 성능 × 품질 = OEE · 비가동 코드 분석"
        actions={writable && <Btn onClick={openNew}><Plus size={16} /> OEE 기록</Btn>} />

      {/* 설비 가동 현황 */}
      <Card title="설비 가동 현황" icon={<Wrench size={15} />} className="mb-5">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          {equipment.map((eq: any) => (
            <div key={eq.id} className="bg-panel border border-edge rounded-lg p-3">
              <div className="flex items-center justify-between mb-1.5">
                <span className="text-sm font-medium">{eq.equipmentName || eq.equipmentCode}</span>
                <StatusBadge status={eq.runStatus || eq.status} />
              </div>
              {manageable && (
                <select className="inp text-xs" value={eq.runStatus || 'IDLE'} onChange={e => setRun(eq.id, e.target.value)}>
                  {RUN_STATES.map(s => <option key={s} value={s}>{s}</option>)}
                </select>
              )}
            </div>
          ))}
          {equipment.length === 0 && <p className="text-slate-500 text-sm col-span-4 text-center py-4">설비가 없습니다.</p>}
        </div>
      </Card>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-6">
        <Card title="비가동 파레토 (30일)" icon={<Power size={15} />}><Chart type="BAR" data={toChart(pareto, '비가동(분)')} /></Card>
        <Card title="OEE 추이" icon={<Gauge size={15} />}>
          <Chart type="LINE" data={{ labels: list.slice(0, 12).reverse().map((o: any) => o.recordDate || o.equipmentCode), series: [{ name: 'OEE%', data: list.slice(0, 12).reverse().map((o: any) => Number(o.oeePercent ?? (o.oee != null ? o.oee * 100 : 0))) }] }} />
        </Card>
      </div>

      <div className="flex items-center gap-2 mb-4">
        <select className="inp w-52" value={eqCode} onChange={e => setEqCode(e.target.value)}>
          <option value="">전체 설비</option>
          {equipment.map((eq: any) => <option key={eq.id} value={eq.equipmentCode}>{eq.equipmentName || eq.equipmentCode}</option>)}
        </select>
        <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-right">가동률</th><th className="text-right">성능</th><th className="text-right">품질</th><th className="text-right px-4">OEE</th></tr>
          </thead>
          <tbody>
            {list.map((o: any) => (
              <tr key={o.id} className="border-t border-edge/50">
                <td className="py-3 px-4 font-medium">{o.equipmentCode}</td>
                <td className="text-slate-400 text-xs">{o.recordDate || '-'}</td>
                <td className="text-right text-slate-300">{o.availability != null ? (o.availability * 100).toFixed(0) + '%' : '-'}</td>
                <td className="text-right text-slate-300">{o.performance != null ? (o.performance * 100).toFixed(0) + '%' : '-'}</td>
                <td className="text-right text-slate-300">{o.quality != null ? (o.quality * 100).toFixed(0) + '%' : '-'}</td>
                <td className="text-right px-4 font-bold text-accent">{oeePct(o)}%</td>
              </tr>
            ))}
            {list.length === 0 && <Empty colSpan={6} msg="OEE 기록이 없습니다." />}
          </tbody>
        </table>
      </div>

      {editor && (
        <Modal title="OEE 기록" onClose={() => setEditor(null)}>
          <div className="space-y-3">
            <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>
            <Field label="기록 일자"><input type="date" className="inp" value={editor.recordDate} onChange={e => setEditor({ ...editor, recordDate: e.target.value })} /></Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="계획 가동시간(분)"><input type="number" className="inp" value={editor.plannedTime} onChange={e => setEditor({ ...editor, plannedTime: Number(e.target.value) })} /></Field>
              <Field label="실제 가동시간(분)"><input type="number" className="inp" value={editor.runTime} onChange={e => setEditor({ ...editor, runTime: Number(e.target.value) })} /></Field>
            </div>
            <div className="grid grid-cols-3 gap-3">
              <Field label="이상 사이클(분)"><input type="number" step="0.01" className="inp" value={editor.idealCycleTime} onChange={e => setEditor({ ...editor, idealCycleTime: Number(e.target.value) })} /></Field>
              <Field label="총 생산수"><input type="number" className="inp" value={editor.totalCount} onChange={e => setEditor({ ...editor, totalCount: Number(e.target.value) })} /></Field>
              <Field label="양품수"><input type="number" className="inp" value={editor.goodCount} onChange={e => setEditor({ ...editor, goodCount: Number(e.target.value) })} /></Field>
            </div>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setEditor(null)}>취소</Btn>
            <Btn onClick={save}>저장</Btn>
          </div>
        </Modal>
      )}
    </div>
  )
}
