'use client'

import React, { useMemo, useState, useRef, useEffect } from 'react'
import { SearchInput, FilterDropdown, Pagination, ExpandableRow, ExternalLinkIcon } from './LibraryTable'
import NormCrossRefPanel from './NormCrossRefPanel'

export interface Norm {
  id: string
  number: string
  title_de: string
  norm_type: string
  scope_de: string
  machine_types: string[]
  hazard_cats: string[]
  tags: string[]
  mandatory: boolean
  relevant_sections: string[]
  beuth_url: string
  withdrawn?: boolean
  valid_until?: string
  replaced_by?: string
}

const PER_PAGE = 50
const TYPE_OPTIONS = [
  { value: '', label: 'Alle Typen' },
  { value: 'A', label: 'A-Normen' },
  { value: 'B1', label: 'B1-Normen' },
  { value: 'B2', label: 'B2-Normen' },
  { value: 'C', label: 'C-Normen' },
]
const MANDATORY_OPTIONS = [
  { value: '', label: 'Pflicht: Alle' },
  { value: 'ja', label: 'Pflicht: Ja' },
  { value: 'nein', label: 'Pflicht: Nein' },
]
const STATUS_OPTIONS = [
  { value: '', label: 'Status: Alle' },
  { value: 'active', label: 'Aktiv' },
  { value: 'withdrawn', label: 'Zurueckgezogen' },
]

interface Props { norms: Norm[] }

export default function NormenTab({ norms }: Props) {
  const [search, setSearch] = useState('')
  const [debounced, setDebounced] = useState('')
  const [typeFilter, setTypeFilter] = useState('')
  const [mandatoryFilter, setMandatoryFilter] = useState('')
  const [statusFilter, setStatusFilter] = useState('active')
  const [page, setPage] = useState(1)
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null)

  useEffect(() => {
    timer.current = setTimeout(() => setDebounced(search), 300)
    return () => { if (timer.current) clearTimeout(timer.current) }
  }, [search])

  useEffect(() => { setPage(1) }, [debounced, typeFilter, mandatoryFilter, statusFilter])

  const filtered = useMemo(() => {
    const q = debounced.toLowerCase()
    return norms.filter((n) => {
      if (q && !n.number.toLowerCase().includes(q) && !n.title_de.toLowerCase().includes(q) && !n.scope_de.toLowerCase().includes(q)) return false
      if (typeFilter && n.norm_type !== typeFilter) return false
      if (mandatoryFilter === 'ja' && !n.mandatory) return false
      if (mandatoryFilter === 'nein' && n.mandatory) return false
      if (statusFilter === 'active' && n.withdrawn) return false
      if (statusFilter === 'withdrawn' && !n.withdrawn) return false
      return true
    })
  }, [norms, debounced, typeFilter, mandatoryFilter, statusFilter])

  const totalPages = Math.ceil(filtered.length / PER_PAGE)
  const pageItems = filtered.slice((page - 1) * PER_PAGE, page * PER_PAGE)

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center gap-3">
        <div className="flex-1 min-w-[200px]">
          <SearchInput value={search} onChange={setSearch} placeholder="Nummer, Titel oder Scope suchen..." />
        </div>
        <FilterDropdown label="Normtyp" value={typeFilter} options={TYPE_OPTIONS} onChange={setTypeFilter} />
        <FilterDropdown label="Pflicht" value={mandatoryFilter} options={MANDATORY_OPTIONS} onChange={setMandatoryFilter} />
        <FilterDropdown label="Status" value={statusFilter} options={STATUS_OPTIONS} onChange={setStatusFilter} />
        <span className="text-sm text-gray-500 dark:text-gray-400 ml-auto">
          {norms.length} Normen{filtered.length !== norms.length && ` (${filtered.length} gefiltert)`}
        </span>
      </div>

      <div className="overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-700">
        <table className="w-full text-left">
          <thead className="bg-gray-100 dark:bg-gray-800">
            <tr>
              {['Nummer', 'Titel', 'Typ', 'Abschnitte', 'Pflicht', 'Beuth'].map((h) => (
                <th key={h} className="px-4 py-2.5 text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase tracking-wider">{h}</th>
              ))}
              <th className="w-8" />
            </tr>
          </thead>
          <tbody>
            {pageItems.map((n) => (
              <ExpandableRow
                key={n.id}
                colSpan={6}
                cells={[
                  <span key="num" className="font-mono text-xs">{n.number}</span>,
                  <span key="title" className="max-w-xs truncate block">{n.title_de}</span>,
                  <span key="type" className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300">{n.norm_type}</span>,
                  <span key="sec" className="text-xs text-gray-500">{n.relevant_sections.length > 0 ? n.relevant_sections.slice(0, 3).join(', ') : '-'}{n.relevant_sections.length > 3 ? ` +${n.relevant_sections.length - 3}` : ''}</span>,
                  n.mandatory
                    ? <span key="mand" className="text-green-600 font-medium text-xs">Ja</span>
                    : <span key="mand" className="text-gray-400 text-xs">Nein</span>,
                  n.beuth_url
                    ? <a key="link" href={n.beuth_url} target="_blank" rel="noopener noreferrer" onClick={(e) => e.stopPropagation()} className="text-purple-600 hover:text-purple-800 text-xs">Link<ExternalLinkIcon /></a>
                    : <span key="link" className="text-gray-300 text-xs">-</span>,
                ]}
                expandedContent={
                  <div className="space-y-2">
                    <div><span className="font-medium text-gray-700 dark:text-gray-300">Scope:</span> {n.scope_de || '-'}</div>
                    {n.relevant_sections.length > 0 && (
                      <div><span className="font-medium text-gray-700 dark:text-gray-300">Abschnitte:</span> {n.relevant_sections.join(', ')}</div>
                    )}
                    {n.machine_types.length > 0 && (
                      <div><span className="font-medium text-gray-700 dark:text-gray-300">Maschinentypen:</span> {n.machine_types.join(', ')}</div>
                    )}
                    {n.tags.length > 0 && (
                      <div className="flex flex-wrap gap-1">
                        {n.tags.map((t) => <span key={t} className="px-1.5 py-0.5 rounded text-xs bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300">{t}</span>)}
                      </div>
                    )}
                    <NormCrossRefPanel normId={n.id} />
                  </div>
                }
              />
            ))}
            {pageItems.length === 0 && (
              <tr><td colSpan={7} className="px-4 py-8 text-center text-sm text-gray-400">Keine Normen gefunden</td></tr>
            )}
          </tbody>
        </table>
      </div>

      <Pagination page={page} totalPages={totalPages} onPageChange={setPage} />
    </div>
  )
}
