import { useEffect, useState } from 'react'
import {
  ResponsiveContainer, ComposedChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ReferenceLine, Legend,
} from 'recharts'
import { LineChart as LineIcon, Plus, Sparkles, AlertTriangle } from 'lucide-react'
import { PageHeader, Btn, Field, Modal, Empty, Card } from '../components/ui'
import StatusBadge from '../components/StatusBadge'
import { canWrite } from '../components/rbac'
import {
  getSpcCharts, getSpcSamples, getSpcChart, addSpcSample, getItems,
} from '../api/client'

const axisStyle = { fontSize: 11, fill: '#94a3b8' }
const tooltipStyle = { background: '#0f172a', border: '1px solid #26304a', borderRadius: 8, fontSize: 12, color: '#e2e8f0' }
const emptyForm = { chartCode: '', itemCode: '', characteristic: '', subgroupNo: 1, values: '' }

export default function Spc() {
  const [charts, setCharts] = useState<any[]>([])
  const [sel, setSel] = useState('')
  const [samples, setSamples] = useState<any[]>([])
  const [analysis, setAnalysis] = useState<any>(null)
  const [lsl, setLsl] = useState('')
  const [usl, setUsl] = useState('')
  const [editor, setEditor] = useState<any>(null)
  const [items, setItems] = useState<any[]>([])
  const writable = canWrite()

  const loadCharts = () => getSpcCharts().then(d => { const c = d || []; setCharts(c); if (!sel && c.length) setSel(c[0].chartCode) }).catch(() => setCharts([]))
  useEffect(() => { loadCharts(); getItems().then(d => setItems(d || [])).catch(() => {}) }, [])

  const loadChart = () => {
    if (!sel) return
    getSpcSamples({ chartCode: sel, limit: 50 }).then(d => setSamples(Array.isArray(d) ? d : [])).catch(() => setSamples([]))
    getSpcChart({ chartCode: sel, lsl: lsl === '' ? undefined : Number(lsl), usl: usl === '' ? undefined : Number(usl) })
      .then(setAnalysis).catch(() => setAnalysis(null))
  }
  useEffect(() => { loadChart() }, [sel])

  const openNew = () => setEditor({ ...emptyForm, chartCode: sel })
  const save = async () => {
    const values = editor.values.split(/[,\s]+/).map((v: string) => Number(v)).filter((v: number) => !isNaN(v))
    await addSpcSample({ chartCode: editor.chartCode, itemCode: editor.itemCode, characteristic: editor.characteristic, subgroupNo: Number(editor.subgroupNo), values })
    setEditor(null); loadChart()
  }

  // Xbar 차트 데이터
  const xbarRows = samples.map((s: any, i: number) => ({
    name: s.subgroupNo ?? i + 1,
    xbar: Number(s.mean ?? s.xbar ?? s.average ?? 0),
    range: Number(s.range ?? s.r ?? 0),
  }))
  const a = analysis || {}
  const violations: any[] = Array.isArray(a.violations) ? a.violations : []

  return (
    <div>
      <PageHeader title="SPC 관리도" subtitle="Xbar-R 관리한계 · Cp/Cpk 공정능력 · Western Electric 이상감지"
        actions={writable && sel && <Btn onClick={openNew}><Plus size={16} /> 샘플 추가</Btn>} />

      <div className="flex flex-wrap items-center gap-2 mb-5">
        <select className="inp w-56" value={sel} onChange={e => setSel(e.target.value)}>
          <option value="">관리도 선택</option>
          {charts.map((c: any) => <option key={c.chartCode || c.id} value={c.chartCode}>{c.chartCode} · {c.characteristic || c.itemCode}</option>)}
        </select>
        <input className="inp w-24" placeholder="LSL" value={lsl} onChange={e => setLsl(e.target.value)} />
        <input className="inp w-24" placeholder="USL" value={usl} onChange={e => setUsl(e.target.value)} />
        <Btn variant="ghost" onClick={loadChart}>분석</Btn>
      </div>

      {!sel ? <Empty msg="관리도를 선택하세요." /> : (
        <>
          {/* 공정능력 KPI */}
          <div className="grid grid-cols-2 lg:grid-cols-5 gap-3 mb-5">
            <Kpi label="X̄ (전체평균)" value={fmt(a.xbar)} />
            <Kpi label="R̄ (평균범위)" value={fmt(a.rbar)} />
            <Kpi label="Cp" value={fmt(a.cp)} color="text-sky-400" />
            <Kpi label="Cpk" value={fmt(a.cpk)} color="text-accent" />
            <div className="bg-card border border-edge rounded-xl p-4">
              <div className="text-xs text-slate-400">공정능력 등급</div>
              <div className="mt-2"><StatusBadge status={a.capabilityGrade || '-'} /></div>
            </div>
          </div>

          {a.anomaly && (
            <div className="bg-rose-500/10 border border-rose-500/40 text-rose-300 text-sm rounded-lg px-4 py-2.5 mb-4 flex items-center gap-2">
              <AlertTriangle size={16} /> 이상 패턴 감지됨 (Western Electric Rules){violations.length ? ` — 위반 ${violations.length}건` : ''}
            </div>
          )}

          <Card title="X̄ 관리도 (Xbar Chart)" icon={<LineIcon size={15} />} className="mb-4">
            {xbarRows.length === 0 ? <Empty msg="샘플이 없습니다." /> : (
              <ResponsiveContainer width="100%" height={280}>
                <ComposedChart data={xbarRows}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#26304a" />
                  <XAxis dataKey="name" tick={axisStyle} /><YAxis tick={axisStyle} domain={['auto', 'auto']} />
                  <Tooltip contentStyle={tooltipStyle} /><Legend wrapperStyle={{ fontSize: 11 }} />
                  {a.xbarUcl != null && <ReferenceLine y={Number(a.xbarUcl)} stroke="#ef4444" strokeDasharray="4 4" label={{ value: 'UCL', fontSize: 10, fill: '#ef4444', position: 'right' }} />}
                  {a.xbar != null && <ReferenceLine y={Number(a.xbar)} stroke="#3ddc97" label={{ value: 'CL', fontSize: 10, fill: '#3ddc97', position: 'right' }} />}
                  {a.xbarLcl != null && <ReferenceLine y={Number(a.xbarLcl)} stroke="#ef4444" strokeDasharray="4 4" label={{ value: 'LCL', fontSize: 10, fill: '#ef4444', position: 'right' }} />}
                  <Line type="monotone" dataKey="xbar" name="X̄" stroke="#00a0c8" strokeWidth={2} dot={{ r: 3 }} />
                </ComposedChart>
              </ResponsiveContainer>
            )}
          </Card>

          <Card title="R 관리도 (Range Chart)">
            {xbarRows.length === 0 ? <Empty msg="샘플이 없습니다." /> : (
              <ResponsiveContainer width="100%" height={240}>
                <ComposedChart data={xbarRows}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#26304a" />
                  <XAxis dataKey="name" tick={axisStyle} /><YAxis tick={axisStyle} domain={['auto', 'auto']} />
                  <Tooltip contentStyle={tooltipStyle} /><Legend wrapperStyle={{ fontSize: 11 }} />
                  {a.rUcl != null && <ReferenceLine y={Number(a.rUcl)} stroke="#ef4444" strokeDasharray="4 4" label={{ value: 'UCL', fontSize: 10, fill: '#ef4444', position: 'right' }} />}
                  {a.rbar != null && <ReferenceLine y={Number(a.rbar)} stroke="#3ddc97" label={{ value: 'R̄', fontSize: 10, fill: '#3ddc97', position: 'right' }} />}
                  {a.rLcl != null && <ReferenceLine y={Number(a.rLcl)} stroke="#ef4444" strokeDasharray="4 4" label={{ value: 'LCL', fontSize: 10, fill: '#ef4444', position: 'right' }} />}
                  <Line type="monotone" dataKey="range" name="R" stroke="#f59e0b" strokeWidth={2} dot={{ r: 3 }} />
                </ComposedChart>
              </ResponsiveContainer>
            )}
          </Card>
        </>
      )}

      {editor && (
        <Modal title="SPC 샘플 추가" onClose={() => setEditor(null)}>
          <p className="text-xs text-slate-400 mb-3">서브그룹 측정값을 입력하면 평균/범위가 자동 계산됩니다.</p>
          <div className="space-y-3">
            <div className="grid grid-cols-2 gap-3">
              <Field label="관리도 코드"><input className="inp" value={editor.chartCode} onChange={e => setEditor({ ...editor, chartCode: e.target.value })} /></Field>
              <Field label="서브그룹 번호"><input type="number" className="inp" value={editor.subgroupNo} onChange={e => setEditor({ ...editor, subgroupNo: e.target.value })} /></Field>
            </div>
            <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 className="inp" value={editor.characteristic} onChange={e => setEditor({ ...editor, characteristic: e.target.value })} /></Field>
            <Field label="측정값 (콤마/공백 구분)" hint="예: 10.1, 10.0, 9.9, 10.2, 10.0">
              <input className="inp" value={editor.values} onChange={e => setEditor({ ...editor, values: e.target.value })} />
            </Field>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setEditor(null)}>취소</Btn>
            <Btn onClick={save}><Sparkles size={14} /> 추가</Btn>
          </div>
        </Modal>
      )}
    </div>
  )
}

function Kpi({ label, value, color = 'text-slate-200' }: { label: string; value: string; color?: string }) {
  return (
    <div className="bg-card border border-edge rounded-xl p-4">
      <div className="text-xs text-slate-400">{label}</div>
      <div className={`text-2xl font-bold mt-1 ${color}`}>{value}</div>
    </div>
  )
}
function fmt(v: any) { return v == null ? '-' : Number(v).toFixed(3) }
