import { useState, useMemo } from 'react';
import { Search } from 'lucide-react';
import { 
  communicationScripts, 
  CommunicationScript,
  ScriptCategory,
  ScriptContext,
  getScriptsByCategory,
  getScriptsByContext,
  searchScripts
} from '@/data/communication-scripts';

const Comunicacion = () => {
  const [selectedScript, setSelectedScript] = useState<CommunicationScript | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<ScriptCategory | 'all'>('all');
  const [selectedContext, setSelectedContext] = useState<ScriptContext | 'all'>('all');

  const filteredScripts = useMemo(() => {
    let filtered = communicationScripts;

    // Filtrar por categoría
    if (selectedCategory !== 'all') {
      filtered = getScriptsByCategory(selectedCategory);
    }

    // Filtrar por contexto
    if (selectedContext !== 'all') {
      filtered = filtered.filter(script => 
        selectedCategory === 'all' 
          ? script.context === selectedContext
          : script.context === selectedContext && script.category === selectedCategory
      );
    }

    // Filtrar por búsqueda
    if (searchQuery.trim()) {
      const searchResults = searchScripts(searchQuery);
      filtered = filtered.filter(script => 
        searchResults.includes(script)
      );
    }

    return filtered;
  }, [selectedCategory, selectedContext, searchQuery]);

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-foreground mb-1">Comunicación</h1>
        <p className="text-muted-foreground text-sm">
          Guías de comunicación para emergencias
        </p>
      </div>

      {/* Búsqueda y Filtros */}
      <div className="space-y-4">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <input
            type="text"
            placeholder="Buscar scripts de comunicación..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full pl-10 pr-4 py-2 bg-card border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </div>
        
        <div className="flex gap-2 overflow-x-auto pb-2">
          {['all', 'emergencia', 'hospitalaria', 'interconsulta', 'familia'].map((cat) => (
            <button
              key={cat}
              onClick={() => setSelectedCategory(cat === 'all' ? 'all' : cat as ScriptCategory)}
              className={`px-3 py-1 rounded-full text-sm font-medium whitespace-nowrap transition-colors ${
                selectedCategory === cat
                  ? 'bg-primary text-primary-foreground'
                  : 'bg-muted text-muted-foreground hover:bg-accent'
              }`}
            >
              {cat === 'all' ? 'Todas' : cat.charAt(0).toUpperCase() + cat.slice(1)}
            </button>
          ))}
        </div>
      </div>

      {/* Lista de Scripts */}
      <div className="space-y-3">
        {filteredScripts.length === 0 ? (
          <p className="text-center text-muted-foreground py-8">No hay scripts que coincidan con los filtros.</p>
        ) : (
          filteredScripts.map((script) => (
            <div
              key={script.id}
              onClick={() => setSelectedScript(script)}
              className="bg-card border border-border rounded-lg p-4 cursor-pointer hover:border-primary/50 transition-colors"
            >
              <h3 className="font-semibold text-foreground">{script.title}</h3>
              <p className="text-sm text-muted-foreground mt-1">
                Categoría: {script.category} • Contexto: {script.context}
              </p>
            </div>
          ))
        )}
      </div>

      {/* Visor de Script Seleccionado */}
      {selectedScript && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
          <div className="bg-card border border-border rounded-lg p-6 max-w-lg w-full max-h-[80vh] overflow-y-auto">
            <div className="flex justify-between items-start mb-4">
              <h2 className="text-xl font-bold">{selectedScript.title}</h2>
              <button
                onClick={() => setSelectedScript(null)}
                className="text-muted-foreground hover:text-foreground"
              >
                ✕
              </button>
            </div>
            <div className="space-y-2">
              {selectedScript.content.map((line, index) => (
                <p key={index} className="text-foreground">
                  {line}
                </p>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Comunicacion;