import { useState } from 'react';
import { Link } from 'react-router-dom';
import {
  Search,
  Info,
  BookOpen,
  Cloud,
} from 'lucide-react';

// Mock data for drugs and TES medications
interface Drug {
  id: string;
  name: string;
  category: string; // matches the category ids in the categories array below
  description?: string;
  dose?: string;
  route?: string;
}

interface TESMedication {
  id: string;
  name: string;
  category: string; // matches the category ids in the tesCategories array below
  description?: string;
  dose?: string;
  route?: string;
}

// Mock drugs data (simplified)
const mockDrugs: Drug[] = [
  { id: '1', name: 'Salbutamol', category: 'respiratorio', description: 'Broncodilatador', dose: '2.5-5 mg nebulizado', route: 'Inhalatorio' },
  { id: '2', name: 'Ipratropio', category: 'respiratorio', description: 'Anticolinérgico', dose: '250-500 mcg nebulizado', route: 'Inhalatorio' },
  { id: '3', name: 'Adrenalina', category: 'cardiovascular', description: 'Vasoconstrictor y broncodilatador', dose: '0.5-1 mg IM o 0.1 mg IV', route: 'IM/IV' },
  { id: '4', name: 'Noradrenalina', category: 'cardiovascular', description: 'Vasoconstrictor', dose: '0.05-0.5 mcg/kg/min IV', route: 'IV' },
  { id: '5', name: 'Ondansetron', category: 'analgesia', description: 'Antiemético', dose: '4-8 mg IV/IM', route: 'IV/IM' },
  { id: '6', name: 'Paracetamol', category: 'analgesia', description: 'Analgésico y antitérmico', dose: '1g PO/IV/IM', route: 'PO/IV/IM' },
  { id: '7', name: 'Salina 0.9%', category: 'oxigenoterapia', description: 'Solución cristaloide isotónica', dose: 'Según requerimiento', route: 'IV' },
  { id: '8', name: 'Glucosa 50%', category: 'oxigenoterapia', description: 'Solución de dextrosa hipertonica', dose: '25-50 mL IV', route: 'IV' },
];

// Mock TES medications data (simplified)
const mockTESMedications: TESMedication[] = [
  { id: 't1', name: 'Glucosa oral', category: 'hipoglucemia', description: 'Para tratamiento de hipoglucemia consciente', dose: '15-20 g de azúcar o equivalente', route: 'Oral' },
  { id: 't2', name: 'Glucagón IM', category: 'hipoglucemia', description: 'Para tratamiento de hipoglucemia inconsciente', dose: '1 mg IM', route: 'IM' },
  { id: 't3', name: 'Salbutamol', category: 'respiratorio', description: 'Broncodilatador para crisis asmática', dose: '2.5-5 mg nebulizado', route: 'Inhalatorio' },
  { id: 't4', name: 'Ipratropio', category: 'respiratorio', description: 'Anticolinérgico para crisis respiratoria', dose: '250-500 mcg nebulizado', route: 'Inhalatorio' },
  { id: 't5', name: 'Adrenalina Autoinyectable', category: 'anafilaxia', description: 'Para tratamiento de reacción anafiláctica', dose: '0.3-0.5 mg IM', route: 'IM' },
  { id: 't6', name: 'Difenhidramina', category: 'anafilaxia', description: 'Antihistamínico para reacción alérgica', dose: '25-50 mg IV/IM', route: 'IV/IM' },
];

// Categories for drugs (from original)
const categories = [
  { id: 'tes', label: 'Medicación TES' },
  { id: 'todos', label: 'Todos' },
  { id: 'oxigenoterapia', label: 'Oxigenoterapia' },
  { id: 'cardiovascular', label: 'Cardiovascular' },
  { id: 'respiratorio', label: 'Respiratorio' },
  { id: 'neurologico', label: 'Neurológico' },
  { id: 'analgesia', label: 'Analgesia' },
  { id: 'otros', label: 'Otros' },
];

// Categories for TES medications (from original)
const tesCategories = [
  { id: 'todos', label: 'Todos' },
  { id: 'hipoglucemia', label: 'Hipoglucemias' },
  { id: 'respiratorio', label: 'Crisis Respiratorias' },
  { id: 'anafilaxia', label: 'Crisis Anafilácticas' },
];

// Mock components for guides (we'll skip them for now and just show buttons that toggle modals, but we won't implement the modals)
const DrugAdministrationGuide = () => null;
const PharmaceuticalTerminologyGuide = () => null;

// Mock component for drug card (simplified)
const DrugCard = ({ drug, defaultExpanded }: { drug: Drug; defaultExpanded?: boolean }) => (
  <div className="border border-gray-200 rounded-lg p-4 mb-4">
    <h3 className="font-semibold text-gray-800">{drug.name}</h3>
    <p className="text-gray-600">{drug.description}</p>
    {drug.dose && <p className="text-sm text-gray-500"><strong>Dosis:</strong> {drug.dose}</p>}
    {drug.route && <p className="text-sm text-gray-500"><strong>Vía:</strong> {drug.route}</p>}
  </div>
);

// Mock component for TES medication card (simplified)
const TESMedicationCard = ({ medication }: { medication: TESMedication }) => (
  <div className="border border-gray-200 rounded-lg p-4 mb-4">
    <h3 className="font-semibold text-gray-800">{medication.name}</h3>
    <p className="text-gray-600">{medication.description}</p>
    {medication.dose && <p className="text-sm text-gray-500"><strong>Dosis:</strong> {medication.dose}</p>}
    {medication.route && <p className="text-sm text-gray-500"><strong>Vía:</strong> {medication.route}</p>}
  </div>
);

const Farmacos = () => {
  const [showAdministrationGuide, setShowAdministrationGuide] = useState(false);
  const [showTerminologyGuide, setShowTerminologyGuide] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [activeCategory, setActiveCategory] = useState<string>('todos');
  const [activeTESCategory, setActiveTESCategory] = useState<string>('todos');

  // Filter drugs based on activeCategory and searchQuery
  const filteredDrugs = mockDrugs.filter(drug => {
    const matchesCategory = activeCategory === 'todos' || activeCategory === 'tes' ? true : drug.category === activeCategory;
    const matchesSearch = drug.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                          (drug.description && drug.description.toLowerCase().includes(searchQuery.toLowerCase()));
    return matchesCategory && matchesSearch;
  });

  // Filter TES medications based on activeTESCategory and searchQuery
  const filteredTESMedications = mockTESMedications.filter(med => {
    const matchesCategory = activeTESCategory === 'todos' || activeTESCategory === 'tes' ? true : med.category === activeTESCategory;
    const matchesSearch = med.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                          (med.description && med.description.toLowerCase().includes(searchQuery.toLowerCase()));
    return matchesCategory && matchesSearch;
  });

  // If activeCategory is 'tes', we show TES medications, otherwise we show drugs
  const showTES = activeCategory === 'tes';

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <div className="flex items-center gap-2">
            <h1 className="text-2xl font-bold text-foreground">Fármacos</h1>
            {/* We'll skip the external flag for now */}
          </div>
          <p className="text-muted-foreground text-sm">
            Vademécum de emergencias
          </p>
        </div>
      </div>

      {/* We'll skip the guides for now and just show placeholder buttons */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <button
            onClick={() => setShowAdministrationGuide(true)}
            className="flex items-center gap-2 px-4 py-2 text-sm text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded-lg transition-colors"
          >
            <Info className="w-4 h-4" />
            Ver Principios de Administración
          </button>
          <button
            onClick={() => setShowTerminologyGuide(true)}
            className="flex items-center gap-2 px-4 py-2 text-sm text-purple-600 hover:text-purple-700 hover:bg-purple-50 rounded-lg transition-colors"
          >
            <BookOpen className="w-4 h-4" />
            Ver Abreviaturas y Terminología
          </button>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => {
              setShowAdministrationGuide(false);
              setShowTerminologyGuide(false);
            }}
            className="px-4 py-2 bg-gray-200 text-gray-600 rounded hover:bg-gray-300"
          >
            Cerrar guías
          </button>
        </div>
      </div>

      {/* Search */}
      <div className="relative mb-4">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-muted-foreground" />
        <input
          type="text"
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          placeholder="Buscar fármaco..."
          className="w-full pl-10 pr-4 h-12 bg-card border border-border rounded-xl text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary"
        />
      </div>

      {/* Category Tabs */}
      <div className="flex gap-2 overflow-x-auto scrollbar-hide -mx-2 px-2 mb-4">
        {categories.map((cat) => (
          <button
            key={cat.id}
            onClick={() => {
              setActiveCategory(cat.id);
              if (cat.id !== 'tes') {
                setActiveTESCategory('todos'); // Reset TES category when switching to non-TES category
              }
            }}
            className={`px-3 py-1 rounded-full text-sm font-medium whitespace-nowrap transition-colors ${
              activeCategory === cat.id
                ? 'bg-secondary text-secondary-foreground'
                : 'bg-muted text-muted-foreground hover:bg-accent'
            }`}
          >
            {cat.label}
          </button>
        ))}
      </div>

      {/* TES Medication Subcategories (only show when activeCategory is 'tes') */}
      {activeCategory === 'tes' && (
        <div className="flex gap-2 overflow-x-auto scrollbar-hide -mx-2 px-2 mb-4">
          {tesCategories.map((cat) => (
            <button
              key={cat.id}
              onClick={() => setActiveTESCategory(cat.id)}
              className={`px-3 py-1 rounded-full text-sm font-medium whitespace-nowrap transition-colors ${
                activeTESCategory === cat.id
                  ? 'bg-primary text-primary-foreground'
                  : 'bg-muted text-muted-foreground hover:bg-accent'
              }`}
            >
              {cat.label}
            </button>
          ))}
        </div>
      )}

      {/* Results */}
      <div className="space-y-4">
        {showTES ? (
          <>
            {filteredTESMedications.length > 0 ? (
              <>
                <h2 className="text-xl font-semibold text-foreground mb-2">Medicaciones TES</h2>
                <div className="space-y-3">
                  {filteredTESMedications.map((med) => (
                    <TESMedicationCard key={med.id} medication={med} />
                  ))}
                </div>
              </>
            ) : (
              <div className="text-center py-8">
                <p className="text-muted-foreground">No se encontraron medicaciones TES</p>
              </div>
            )}
          </>
        ) : (
          <>
            {filteredDrugs.length > 0 ? (
              <>
                <h2 className="text-xl font-semibold text-foreground mb-2">Fármacos</h2>
                <div className="space-y-3">
                  {filteredDrugs.map((drug) => (
                    <DrugCard key={drug.id} drug={drug} defaultExpanded={false} />
                  ))}
                </div>
              </>
            ) : (
              <div className="text-center py-8">
                <p className="text-muted-foreground">No se encontraron fármacos</p>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
};

export default Farmacos;