import { useEffect, useMemo, useRef, useState } from 'react'
import { Download, FileText, Search, X, Copy, Check, WrapText } from 'lucide-react'
import Modal from './ui/Modal'
import { copyText, downloadText } from '../lib/clipboard'

export default function LogsModal({ name, logs, loading, onClose }) {
  const bottomRef = useRef(null)
  const [filter, setFilter] = useState('')
  const [wrap,   setWrap]   = useState(true)
  const [copied, setCopied] = useState(false)

  const lines = useMemo(() => (logs ?? '').split('\n'), [logs])
  const shown = useMemo(() => {
    const q = filter.trim().toLowerCase()
    return q ? lines.filter(l => l.toLowerCase().includes(q)) : lines
  }, [lines, filter])

  // Défilement en bas à l'arrivée des logs (pas pendant un filtrage)
  useEffect(() => {
    if (!loading && !filter && bottomRef.current) {
      bottomRef.current.scrollIntoView({ behavior: 'smooth' })
    }
  }, [logs, loading, filter])

  const handleDownload = () => {
    downloadText(`${name.replace(/[^a-z0-9]/gi, '_')}.log`, logs)
  }

  const handleCopy = async () => {
    if (await copyText(shown.join('\n'))) {
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    }
  }

  const hasLogs = !loading && logs

  return (
    <Modal
      size="xl"
      title={name}
      subtitle={hasLogs
        ? `${lines.length} ligne${lines.length > 1 ? 's' : ''}${filter ? ` · ${shown.length} correspondance${shown.length > 1 ? 's' : ''}` : ''}`
        : undefined}
      icon={<FileText size={16} className="text-indigo-400 flex-shrink-0" />}
      onClose={onClose}
      bodyClassName="flex flex-col overflow-hidden p-0"
      panelClassName="max-h-[88vh]"
      headerRight={hasLogs && (
        <>
          <button
            onClick={() => setWrap(w => !w)}
            aria-pressed={wrap}
            title={wrap ? 'Désactiver le retour à la ligne' : 'Activer le retour à la ligne'}
            aria-label="Retour à la ligne automatique"
            className={`p-1.5 rounded-lg transition-colors ${wrap ? 'bg-gray-800 text-indigo-400' : 'text-gray-500 hover:text-gray-200 hover:bg-gray-800'}`}
          >
            <WrapText size={14} />
          </button>
          <button
            onClick={handleCopy}
            title="Copier les logs affichés"
            aria-label="Copier les logs affichés"
            className="p-1.5 rounded-lg text-gray-500 hover:text-gray-200 hover:bg-gray-800 transition-colors"
          >
            {copied ? <Check size={14} className="text-emerald-400" /> : <Copy size={14} />}
          </button>
          <button
            onClick={handleDownload}
            title="Télécharger le fichier de logs"
            aria-label="Télécharger le fichier de logs"
            className="p-1.5 rounded-lg text-gray-500 hover:text-gray-200 hover:bg-gray-800 transition-colors"
          >
            <Download size={14} />
          </button>
        </>
      )}
    >
      {/* Filtre */}
      {hasLogs && (
        <div className="relative px-4 py-2 border-b border-gray-800 flex-shrink-0">
          <Search size={13} className="absolute left-7 top-1/2 -translate-y-1/2 text-gray-600 pointer-events-none" />
          <input
            type="search"
            value={filter}
            onChange={e => setFilter(e.target.value)}
            placeholder="Filtrer les lignes…"
            aria-label="Filtrer les lignes de log"
            className="w-full bg-gray-800/60 border border-gray-700 rounded-lg pl-8 pr-8 py-1.5 text-xs font-mono placeholder-gray-600 focus:outline-none focus:border-indigo-500 transition-colors"
          />
          {filter && (
            <button
              onClick={() => setFilter('')}
              aria-label="Effacer le filtre"
              className="absolute right-7 top-1/2 -translate-y-1/2 p-0.5 rounded text-gray-500 hover:text-gray-200 transition-colors"
            >
              <X size={13} />
            </button>
          )}
        </div>
      )}

      {/* Contenu */}
      <div className="flex-1 overflow-auto bg-gray-950 p-4">
        {loading ? (
          <div className="space-y-2" aria-busy="true" aria-label="Chargement des logs">
            {Array.from({ length: 8 }, (_, i) => (
              <div key={i} className="skeleton h-3 rounded" style={{ width: `${45 + ((i * 17) % 50)}%` }} />
            ))}
          </div>
        ) : (
          <>
            <pre className={`text-xs font-mono text-gray-300 leading-5 ${wrap ? 'whitespace-pre-wrap break-all' : 'whitespace-pre'}`}>
              {shown.length > 0 ? shown.join('\n') : (filter ? '(aucune ligne ne correspond au filtre)' : '(aucun log disponible)')}
            </pre>
            <div ref={bottomRef} />
          </>
        )}
      </div>
    </Modal>
  )
}
