'use client'

import { useState, useMemo } from'react'
import { Plus, Search, ArrowUpDown, ArrowUp, ArrowDown } from'lucide-react'
import type { QuestionWithCategories, AssessmentMainCategory, AssessmentSubCategory } from'@/lib/assessment-types'
import QuestionModal from'./question-modal'

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

type SortKey ='index'|'main'|'sub'|'active'
type SortDir ='asc'|'desc'

export default function QuestionsTab({ questions, mainCats, subCats, onRefresh }: Props) {
 const [search, setSearch] = useState('')
 const [sortKey, setSortKey] = useState<SortKey>('index')
 const [sortDir, setSortDir] = useState<SortDir>('asc')
 const [modalQ, setModalQ] = useState<QuestionWithCategories | null |'new'>()

 const existingIndexes = useMemo(
 () => new Set(questions.map((q) => q.index_number)),
 [questions]
 )

 function toggleSort(key: SortKey) {
 if (sortKey === key) {
 setSortDir((d) => d ==='asc'?'desc':'asc')
 } else {
 setSortKey(key)
 setSortDir('asc')
 }
 }

 const filtered = useMemo(() => {
 const q = search.toLowerCase()
 let list = questions.filter((qn) =>
 !q
 || String(qn.index_number).includes(q)
 || qn.main_category.label.toLowerCase().includes(q)
 || qn.main_category.code.toLowerCase().includes(q)
 || qn.sub_category.label.toLowerCase().includes(q)
 || qn.sub_category.code.toLowerCase().includes(q)
 || qn.question_text.toLowerCase().includes(q)
 )

 list = [...list].sort((a, b) => {
 let cmp = 0
 if (sortKey ==='index') cmp = a.index_number - b.index_number
 if (sortKey ==='main') cmp = a.main_category.label.localeCompare(b.main_category.label)
 if (sortKey ==='sub') cmp = a.sub_category.label.localeCompare(b.sub_category.label)
 if (sortKey ==='active') cmp = Number(b.is_active) - Number(a.is_active)
 return sortDir ==='asc'? cmp : -cmp
 })

 return list
 }, [questions, search, sortKey, sortDir])

 function SortIcon({ k }: { k: SortKey }) {
 if (sortKey !== k) return <ArrowUpDown size={11} className="text-[#B3C5D5]"/>
 return sortDir ==='asc'
 ? <ArrowUp size={11} className="text-primary"/>
 : <ArrowDown size={11} className="text-primary"/>
 }

 return (
 <div className="space-y-4">
 {/* Toolbar */}
 <div className="flex items-center gap-3">
 <div className="relative flex-1 max-w-80">
 <Search size={13} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground"/>
 <input
 value={search}
 onChange={(e) => setSearch(e.target.value)}
 placeholder="Index, Kategorie, Fragetext…"
 className="w-full h-9 pl-8 pr-3 rounded-lg border border-border text-[12px] bg-card focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
 />
 </div>
 <span className="text-[12px] text-muted-foreground">{filtered.length} Fragen</span>
 <button
 onClick={() => setModalQ('new')}
 className="flex items-center gap-1.5 h-9 px-4 rounded-lg bg-primary text-white text-[13px] font-medium hover:bg-primary-dark transition-colors ml-auto"
 >
 <Plus size={15} />
 Neue Frage
 </button>
 </div>

 {/* Table */}
 <div className="bg-card rounded-xl border border-border overflow-hidden">
 <div className="overflow-x-auto">
 <table className="w-full text-[12px]">
 <thead>
 <tr className="border-b border-border bg-background">
 <th className="text-left px-4 py-2.5 w-16">
 <button onClick={() => toggleSort('index')} className="flex items-center gap-1 font-semibold text-muted-foreground hover:text-foreground">
 # <SortIcon k="index"/>
 </button>
 </th>
 <th className="text-left px-4 py-2.5 w-32">
 <button onClick={() => toggleSort('main')} className="flex items-center gap-1 font-semibold text-muted-foreground hover:text-foreground">
 Hauptkat. <SortIcon k="main"/>
 </button>
 </th>
 <th className="text-left px-4 py-2.5 w-40">
 <button onClick={() => toggleSort('sub')} className="flex items-center gap-1 font-semibold text-muted-foreground hover:text-foreground">
 Unterkat. <SortIcon k="sub"/>
 </button>
 </th>
 <th className="text-left px-4 py-2.5">Fragetext</th>
 <th className="text-center px-4 py-2.5 w-20">
 <button onClick={() => toggleSort('active')} className="flex items-center gap-1 font-semibold text-muted-foreground hover:text-foreground mx-auto">
 Aktiv <SortIcon k="active"/>
 </button>
 </th>
 </tr>
 </thead>
 <tbody>
 {filtered.length === 0 ? (
 <tr>
 <td colSpan={5} className="px-4 py-12 text-center text-muted-foreground text-[13px]">
 {search ?'Keine Ergebnisse für diese Suche.':'Noch keine Fragen vorhanden.'}
 </td>
 </tr>
 ) : (
 filtered.map((q) => (
 <tr
 key={q.id}
 onClick={() => setModalQ(q)}
 className="border-b border-[#F0F4F8] hover:bg-background transition-colors cursor-pointer"
 >
 <td className="px-4 py-2.5">
 <span className="w-7 h-7 rounded-md bg-primary-dark text-white text-[11px] font-bold inline-flex items-center justify-center">
 {q.index_number}
 </span>
 </td>
 <td className="px-4 py-2.5">
 <span className="font-mono text-[11px] text-muted-foreground">{q.main_category.code}</span>
 </td>
 <td className="px-4 py-2.5">
 <span className="font-mono text-[11px] text-muted-foreground">{q.sub_category.code}</span>
 <span className="ml-1.5 text-[11px] text-foreground">{q.sub_category.label}</span>
 </td>
 <td className="px-4 py-2.5 max-w-0 w-full">
 <p className="truncate text-foreground">{q.question_text}</p>
 </td>
 <td className="px-4 py-2.5 text-center">
 <span
 className="inline-block text-[10px] font-medium px-2 py-0.5 rounded-full"
 style={{
 backgroundColor: q.is_active ?'#D1FAE5':'#FEE2E2',
 color: q.is_active ?'#065F46':'#991B1B',
 }}
 >
 {q.is_active ?'Aktiv':'Inaktiv'}
 </span>
 </td>
 </tr>
 ))
 )}
 </tbody>
 </table>
 </div>
 </div>

 {/* Modal */}
 {modalQ !== undefined && (
 <QuestionModal
 question={modalQ ==='new'? null : modalQ}
 mainCats={mainCats}
 subCats={subCats}
 existingIndexes={existingIndexes}
 onClose={() => setModalQ(undefined)}
 onSaved={() => { setModalQ(undefined); onRefresh() }}
 />
 )}
 </div>
 )
}
