'use client'

import { useState, useMemo } from'react'
import { Plus, Pencil, Trash2, Check, X } from'lucide-react'
import { createClient } from'@/lib/supabase/client'
import type { AssessmentMainCategory, AssessmentSubCategory } from'@/lib/assessment-types'

interface Props {
 mainCats: AssessmentMainCategory[]
 subCats: AssessmentSubCategory[]
 questions: { sub_category_id: string }[]
 onRefresh: () => void
}

const inputCls ='rounded-lg border border-border text-[12px] text-foreground px-2.5 bg-card focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary'

// ── inline edit row for main categories ──────────────────────────────────────

function MainCatRow({ cat, onRefresh }: { cat: AssessmentMainCategory; onRefresh: () => void }) {
 const [editing, setEditing] = useState(false)
 const [label, setLabel] = useState(cat.label)
 const [order, setOrder] = useState(String(cat.sort_order))
 const [saving, setSaving] = useState(false)
 const [error, setError] = useState('')
 const supabase = useMemo(() => createClient(), [])

 async function save() {
 if (!label.trim()) { setError('Label ist erforderlich'); return }
 setSaving(true)
 const { error: err } = await supabase
 .from('assessment_main_categories')
 .update({ label: label.trim(), sort_order: parseInt(order, 10) || cat.sort_order })
 .eq('id', cat.id)
 setSaving(false)
 if (err) { setError(err.message) } else { setEditing(false); onRefresh() }
 }

 function cancel() { setLabel(cat.label); setOrder(String(cat.sort_order)); setEditing(false); setError('') }

 async function toggleActive() {
 await supabase.from('assessment_main_categories').update({ is_active: !cat.is_active }).eq('id', cat.id)
 onRefresh()
 }

 return (
 <tr className={`border-b border-[#F0F4F8] hover:bg-[#FAFBFC] ${!cat.is_active ?'opacity-60':''}`}>
 <td className="px-4 py-2.5 font-mono text-[11px] text-muted-foreground w-20">{cat.code}</td>
 <td className="px-4 py-2.5">
 {editing ? (
 <input value={label} onChange={(e) => setLabel(e.target.value)} className={`${inputCls} h-7 w-full`} autoFocus />
 ) : (
 <span className={`text-[12px] font-medium ${cat.is_active ?'text-foreground':'text-muted-foreground line-through'}`}>{cat.label}</span>
 )}
 {error && <p className="text-[10px] text-red-500 mt-0.5">{error}</p>}
 </td>
 <td className="px-4 py-2.5 w-24">
 {editing ? (
 <input type="number"value={order} onChange={(e) => setOrder(e.target.value)} className={`${inputCls} h-7 w-16`} />
 ) : (
 <span className="text-[12px] text-muted-foreground">{cat.sort_order}</span>
 )}
 </td>
 <td className="px-4 py-2.5 w-24 text-center">
 <button
 onClick={toggleActive}
 className={`text-[10px] font-medium px-2 py-0.5 rounded-full cursor-pointer transition-colors ${
 cat.is_active ?'bg-[#F0FDF4] text-success hover:bg-[#DCFCE7]':'bg-background text-muted-foreground hover:bg-border'
 }`}
 >
 {cat.is_active ?'Aktiv':'Inaktiv'}
 </button>
 </td>
 <td className="px-4 py-2.5 w-20 text-right">
 {editing ? (
 <div className="flex gap-1 justify-end">
 <button onClick={save} disabled={saving} className="w-7 h-7 flex items-center justify-center rounded bg-primary text-white hover:bg-primary-dark disabled:opacity-50">
 <Check size={13} />
 </button>
 <button onClick={cancel} className="w-7 h-7 flex items-center justify-center rounded border border-border text-muted-foreground hover:bg-background">
 <X size={13} />
 </button>
 </div>
 ) : (
 <button onClick={() => setEditing(true)} className="w-7 h-7 flex items-center justify-center rounded hover:bg-secondary text-muted-foreground ml-auto">
 <Pencil size={13} />
 </button>
 )}
 </td>
 </tr>
 )
}

// ── sub-category row ──────────────────────────────────────────────────────────

function SubCatRow({ cat, mainCats, questionCount, onRefresh }: {
 cat: AssessmentSubCategory
 mainCats: AssessmentMainCategory[]
 questionCount: number
 onRefresh: () => void
}) {
 const [editing, setEditing] = useState(false)
 const [label, setLabel] = useState(cat.label)
 const [order, setOrder] = useState(String(cat.sort_order))
 const [mainId, setMainId] = useState(cat.main_category_id)
 const supabase = useMemo(() => createClient(), [])
 const [saving, setSaving] = useState(false)
 const [deleting, setDeleting] = useState(false)
 const [confirmDel, setConfirmDel] = useState(false)
 const [error, setError] = useState('')

 const mainCat = mainCats.find((m) => m.id === cat.main_category_id)

 async function save() {
 if (!label.trim()) { setError('Label ist erforderlich'); return }
 setSaving(true)
 const { error: err } = await supabase
 .from('assessment_sub_categories')
 .update({ label: label.trim(), sort_order: parseInt(order, 10) || cat.sort_order, main_category_id: mainId })
 .eq('id', cat.id)
 setSaving(false)
 if (err) { setError(err.message) } else { setEditing(false); onRefresh() }
 }

 async function del() {
 setDeleting(true)
 const { error: err } = await supabase.from('assessment_sub_categories').delete().eq('id', cat.id)
 setDeleting(false)
 if (err) { setError(err.message); setConfirmDel(false) } else { onRefresh() }
 }

 function cancel() { setLabel(cat.label); setOrder(String(cat.sort_order)); setMainId(cat.main_category_id); setEditing(false); setError('') }

 return (
 <tr className="border-b border-[#F0F4F8] hover:bg-[#FAFBFC]">
 <td className="px-4 py-2.5 font-mono text-[11px] text-muted-foreground w-24">{cat.code}</td>
 <td className="px-4 py-2.5">
 {editing ? (
 <input value={label} onChange={(e) => setLabel(e.target.value)} className={`${inputCls} h-7 w-full`} autoFocus />
 ) : (
 <span className="text-[12px] font-medium text-foreground">{cat.label}</span>
 )}
 {error && <p className="text-[10px] text-red-500 mt-0.5">{error}</p>}
 </td>
 <td className="px-4 py-2.5 w-36">
 {editing ? (
 <select
 value={mainId}
 onChange={(e) => setMainId(e.target.value)}
 className="h-7 rounded border border-border text-[11px] px-1.5 bg-card focus:outline-none focus:border-primary"
 >
 {mainCats.map((m) => <option key={m.id} value={m.id}>{m.code}</option>)}
 </select>
 ) : (
 <span className="font-mono text-[11px] text-muted-foreground">{mainCat?.code}</span>
 )}
 </td>
 <td className="px-4 py-2.5 w-20">
 {editing ? (
 <input type="number"value={order} onChange={(e) => setOrder(e.target.value)} className={`${inputCls} h-7 w-16`} />
 ) : (
 <span className="text-[12px] text-muted-foreground">{cat.sort_order}</span>
 )}
 </td>
 <td className="px-4 py-2.5 w-20 text-center">
 <span className="text-[11px] text-muted-foreground">{questionCount}</span>
 </td>
 <td className="px-4 py-2.5 w-32 text-right">
 {editing ? (
 <div className="flex gap-1 justify-end">
 <button onClick={save} disabled={saving} className="w-7 h-7 flex items-center justify-center rounded bg-primary text-white hover:bg-primary-dark disabled:opacity-50">
 <Check size={13} />
 </button>
 <button onClick={cancel} className="w-7 h-7 flex items-center justify-center rounded border border-border text-muted-foreground hover:bg-background">
 <X size={13} />
 </button>
 </div>
 ) : confirmDel ? (
 <div className="flex gap-1 justify-end">
 <button onClick={del} disabled={deleting} className="h-6 px-2 text-[10px] font-medium rounded bg-red-600 text-white hover:bg-red-700 disabled:opacity-50">
 {deleting ?'…':'Löschen'}
 </button>
 <button onClick={() => setConfirmDel(false)} className="h-6 px-2 text-[10px] font-medium rounded border border-border text-muted-foreground hover:bg-background">
 Nein
 </button>
 </div>
 ) : (
 <div className="flex gap-1 justify-end">
 <button onClick={() => setEditing(true)} className="w-7 h-7 flex items-center justify-center rounded hover:bg-secondary text-muted-foreground">
 <Pencil size={13} />
 </button>
 <button
 onClick={() => questionCount > 0 ? setError(`Kann nicht gelöscht werden: ${questionCount} Fragen referenzieren diese Unterkategorie.`) : setConfirmDel(true)}
 className="w-7 h-7 flex items-center justify-center rounded hover:bg-red-50 text-red-400 disabled:opacity-30"
 >
 <Trash2 size={13} />
 </button>
 </div>
 )}
 </td>
 </tr>
 )
}

// ── Add main-category modal ───────────────────────────────────────────────────

function AddMainModal({ onClose, onSaved }: { onClose: () => void; onSaved: () => void }) {
 const [code, setCode] = useState('')
 const [label, setLabel] = useState('')
 const [order, setOrder] = useState('99')
 const [saving, setSaving] = useState(false)
 const [error, setError] = useState('')
 const supabase = useMemo(() => createClient(), [])

 async function save() {
 if (!code.trim()) { setError('Code ist erforderlich'); return }
 if (!label.trim()) { setError('Label ist erforderlich'); return }
 setSaving(true)
 const { error: err } = await supabase.from('assessment_main_categories').insert({
 code: code.trim().toUpperCase(),
 label: label.trim(),
 sort_order: parseInt(order, 10) || 99,
 })
 setSaving(false)
 if (err) { setError(err.message) } else { onSaved() }
 }

 return (
 <div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4"onClick={(e) => e.target === e.currentTarget && onClose()}>
 <div className="bg-card text-foreground rounded-xl w-full max-w-sm">
 <div className="flex items-center justify-between px-5 py-4 border-b border-border">
 <h3 className="font-semibold text-[14px] text-foreground">Neue Hauptkategorie</h3>
 <button onClick={onClose} className="w-7 h-7 flex items-center justify-center rounded hover:bg-background text-muted-foreground"><X size={15} /></button>
 </div>
 <div className="px-5 py-4 space-y-3">
 {error && <p className="text-[11px] text-red-600 bg-red-50 rounded px-2.5 py-1.5 border border-red-200">{error}</p>}
 <div className="grid grid-cols-2 gap-3">
 <div>
 <label className="block text-[11px] font-medium text-muted-foreground mb-1">Code *</label>
 <input value={code} onChange={(e) => setCode(e.target.value)} placeholder="z.B. DEV"className={`${inputCls} h-9 w-full`} autoFocus />
 </div>
 <div>
 <label className="block text-[11px] font-medium text-muted-foreground mb-1">Reihenfolge</label>
 <input type="number"value={order} onChange={(e) => setOrder(e.target.value)} className={`${inputCls} h-9 w-full`} />
 </div>
 </div>
 <div>
 <label className="block text-[11px] font-medium text-muted-foreground mb-1">Label *</label>
 <input value={label} onChange={(e) => setLabel(e.target.value)} placeholder="z.B. Development"className={`${inputCls} h-9 w-full`} />
 </div>
 </div>
 <div className="flex justify-end gap-2 px-5 pb-4">
 <button onClick={onClose} className="h-9 px-4 text-[13px] font-medium rounded border border-border text-foreground hover:bg-background">Abbrechen</button>
 <button onClick={save} disabled={saving} className="h-9 px-4 text-[13px] font-medium rounded bg-primary text-white hover:bg-primary-dark disabled:opacity-50">
 {saving ?'Speichere…':'Anlegen'}
 </button>
 </div>
 </div>
 </div>
 )
}

// ── Add sub-category modal ────────────────────────────────────────────────────

function AddSubModal({ mainCats, onClose, onSaved }: { mainCats: AssessmentMainCategory[]; onClose: () => void; onSaved: () => void }) {
 const [code, setCode] = useState('')
 const [label, setLabel] = useState('')
 const [mainId, setMainId] = useState(mainCats[0]?.id ??'')
 const [order, setOrder] = useState('99')
 const [saving, setSaving] = useState(false)
 const [error, setError] = useState('')
 const supabase = useMemo(() => createClient(), [])

 async function save() {
 if (!code.trim()) { setError('Code ist erforderlich'); return }
 if (!label.trim()) { setError('Label ist erforderlich'); return }
 if (!mainId) { setError('Hauptkategorie ist erforderlich'); return }
 setSaving(true)
 const { error: err } = await supabase.from('assessment_sub_categories').insert({
 code: code.trim().toUpperCase(),
 label: label.trim(),
 main_category_id: mainId,
 sort_order: parseInt(order, 10) || 99,
 })
 setSaving(false)
 if (err) { setError(err.message) } else { onSaved() }
 }

 return (
 <div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4"onClick={(e) => e.target === e.currentTarget && onClose()}>
 <div className="bg-card text-foreground rounded-xl w-full max-w-sm">
 <div className="flex items-center justify-between px-5 py-4 border-b border-border">
 <h3 className="font-semibold text-[14px] text-foreground">Neue Unterkategorie</h3>
 <button onClick={onClose} className="w-7 h-7 flex items-center justify-center rounded hover:bg-background text-muted-foreground"><X size={15} /></button>
 </div>
 <div className="px-5 py-4 space-y-3">
 {error && <p className="text-[11px] text-red-600 bg-red-50 rounded px-2.5 py-1.5 border border-red-200">{error}</p>}
 <div className="grid grid-cols-2 gap-3">
 <div>
 <label className="block text-[11px] font-medium text-muted-foreground mb-1">Code *</label>
 <input value={code} onChange={(e) => setCode(e.target.value)} placeholder="z.B. DEV.4"className={`${inputCls} h-9 w-full`} autoFocus />
 </div>
 <div>
 <label className="block text-[11px] font-medium text-muted-foreground mb-1">Reihenfolge</label>
 <input type="number"value={order} onChange={(e) => setOrder(e.target.value)} className={`${inputCls} h-9 w-full`} />
 </div>
 </div>
 <div>
 <label className="block text-[11px] font-medium text-muted-foreground mb-1">Label *</label>
 <input value={label} onChange={(e) => setLabel(e.target.value)} placeholder="z.B. Development Process"className={`${inputCls} h-9 w-full`} />
 </div>
 <div>
 <label className="block text-[11px] font-medium text-muted-foreground mb-1">Hauptkategorie *</label>
 <select value={mainId} onChange={(e) => setMainId(e.target.value)} className="w-full h-9 rounded-lg border border-border text-[12px] px-2.5 bg-card focus:outline-none focus:border-primary">
 {mainCats.map((m) => <option key={m.id} value={m.id}>{m.code} — {m.label}</option>)}
 </select>
 </div>
 </div>
 <div className="flex justify-end gap-2 px-5 pb-4">
 <button onClick={onClose} className="h-9 px-4 text-[13px] font-medium rounded border border-border text-foreground hover:bg-background">Abbrechen</button>
 <button onClick={save} disabled={saving} className="h-9 px-4 text-[13px] font-medium rounded bg-primary text-white hover:bg-primary-dark disabled:opacity-50">
 {saving ?'Speichere…':'Anlegen'}
 </button>
 </div>
 </div>
 </div>
 )
}

// ── main component ────────────────────────────────────────────────────────────

export default function CategoriesTab({ mainCats, subCats, questions, onRefresh }: Props) {
 const [addMainOpen, setAddMainOpen] = useState(false)
 const [addSubOpen, setAddSubOpen] = useState(false)

 const questionCountBySub = new Map<string, number>()
 for (const q of questions) {
 questionCountBySub.set(q.sub_category_id, (questionCountBySub.get(q.sub_category_id) ?? 0) + 1)
 }

 const subCatsWithMain = subCats.sort((a, b) => {
 const mA = mainCats.findIndex((m) => m.id === a.main_category_id)
 const mB = mainCats.findIndex((m) => m.id === b.main_category_id)
 return mA - mB || a.sort_order - b.sort_order
 })

 return (
 <div className="space-y-6">

 {/* Main categories */}
 <div className="bg-card rounded-xl border border-border overflow-hidden">
 <div className="px-5 py-4 border-b border-border flex items-center justify-between">
 <div>
 <h2 className="text-[13px] font-semibold text-foreground">Hauptkategorien</h2>
 <p className="text-[11px] text-muted-foreground mt-0.5">Code ist fest (keine Umbenennung). Label und Reihenfolge sind bearbeitbar.</p>
 </div>
 <button
 onClick={() => setAddMainOpen(true)}
 className="flex items-center gap-1.5 h-8 px-3 rounded-lg bg-primary text-white text-[12px] font-medium hover:bg-primary-dark transition-colors"
 >
 <Plus size={13} />
 Neue Hauptkategorie
 </button>
 </div>
 <table className="w-full text-[12px]">
 <thead>
 <tr className="border-b border-border bg-background">
 <th className="text-left px-4 py-2.5 font-semibold text-muted-foreground w-20">Code</th>
 <th className="text-left px-4 py-2.5 font-semibold text-muted-foreground">Label</th>
 <th className="text-left px-4 py-2.5 font-semibold text-muted-foreground w-24">Reihenfolge</th>
 <th className="text-center px-4 py-2.5 font-semibold text-muted-foreground w-24">Status</th>
 <th className="text-right px-4 py-2.5 font-semibold text-muted-foreground w-20">Aktion</th>
 </tr>
 </thead>
 <tbody>
 {mainCats.map((m) => (
 <MainCatRow key={m.id} cat={m} onRefresh={onRefresh} />
 ))}
 </tbody>
 </table>
 </div>

 {/* Sub-categories */}
 <div className="bg-card rounded-xl border border-border overflow-hidden">
 <div className="px-5 py-4 border-b border-border flex items-center justify-between">
 <div>
 <h2 className="text-[13px] font-semibold text-foreground">Unterkategorien</h2>
 <p className="text-[11px] text-muted-foreground mt-0.5">Unterkategorien mit Fragen können nicht gelöscht werden.</p>
 </div>
 <button
 onClick={() => setAddSubOpen(true)}
 className="flex items-center gap-1.5 h-8 px-3 rounded-lg bg-primary text-white text-[12px] font-medium hover:bg-primary-dark transition-colors"
 >
 <Plus size={13} />
 Neue Unterkategorie
 </button>
 </div>
 <table className="w-full text-[12px]">
 <thead>
 <tr className="border-b border-border bg-background">
 <th className="text-left px-4 py-2.5 font-semibold text-muted-foreground w-24">Code</th>
 <th className="text-left px-4 py-2.5 font-semibold text-muted-foreground">Label</th>
 <th className="text-left px-4 py-2.5 font-semibold text-muted-foreground w-36">Hauptkat.</th>
 <th className="text-left px-4 py-2.5 font-semibold text-muted-foreground w-20">Reihenf.</th>
 <th className="text-center px-4 py-2.5 font-semibold text-muted-foreground w-20">Fragen</th>
 <th className="text-right px-4 py-2.5 font-semibold text-muted-foreground w-32">Aktionen</th>
 </tr>
 </thead>
 <tbody>
 {subCatsWithMain.map((s) => (
 <SubCatRow
 key={s.id}
 cat={s}
 mainCats={mainCats}
 questionCount={questionCountBySub.get(s.id) ?? 0}
 onRefresh={onRefresh}
 />
 ))}
 </tbody>
 </table>
 </div>

 {addMainOpen && (
 <AddMainModal
 onClose={() => setAddMainOpen(false)}
 onSaved={() => { setAddMainOpen(false); onRefresh() }}
 />
 )}

 {addSubOpen && (
 <AddSubModal
 mainCats={mainCats}
 onClose={() => setAddSubOpen(false)}
 onSaved={() => { setAddSubOpen(false); onRefresh() }}
 />
 )}
 </div>
 )
}
