import { useState, useMemo } from 'react';
import { Link } from 'react-router-dom';
import { ChevronLeft, Pill, Info, RotateCcw, Search, AlertCircle } from 'lucide-react';
import { Card, CardHeader, CardTitle, CardContent } from "../components/ui/card";
import { Button } from "../components/ui/button";

interface DrugDose {
  name: string;
  indication: string;
  dose: string;
  math: (weight: number) => number;
  unit: string;
  max?: number;
  notes?: string;
  category: 'resucitacion' | 'sedacion' | 'analgesia' | 'otros';
}

const DoseCalculator = () => {
  const [weight, setWeight] = useState<number>(10);
  const [searchTerm, setSearchTerm] = useState('');

  const drugs: DrugDose[] = [
    { 
      name: 'Adrenalina (RCP)', 
      indication: 'Parada cardiorrespiratoria', 
      dose: '0.01 mg/kg (1:10.000)', 
      math: (w) => w * 0.01, 
      unit: 'mg (0.1 ml/kg)', 
      category: 'resucitacion',
      notes: 'Repetir cada 3-5 min. Concentración 1mg en 10ml.'
    },
    { 
      name: 'Amiodarona', 
      indication: 'FV / TV sin pulso (tras 3ª desfibrilación)', 
      dose: '5 mg/kg', 
      math: (w) => w * 5, 
      unit: 'mg', 
      max: 300, 
      category: 'resucitacion' 
    },
    { 
      name: 'Midazolam (Convulsión)', 
      indication: 'Estatus epiléptico (vía IV)', 
      dose: '0.1 mg/kg', 
      math: (w) => w * 0.1, 
      unit: 'mg', 
      max: 5, 
      category: 'sedacion' 
    },
    { 
      name: 'Fentanilo', 
      indication: 'Analgesia intensa (vía IV)', 
      dose: '1 mcg/kg', 
      math: (w) => w * 1, 
      unit: 'mcg', 
      category: 'analgesia' 
    },
    { 
      name: 'Paracetamol', 
      indication: 'Fiebre / Dolor leve (vía Oral)', 
      dose: '15 mg/kg', 
      math: (w) => w * 15, 
      unit: 'mg', 
      category: 'analgesia' 
    },
    { 
      name: 'Salbutamol', 
      indication: 'Broncoespasmo (Nebulizado)', 
      dose: '0.15 mg/kg (min 2.5mg)', 
      math: (w) => Math.max(2.5, w * 0.15), 
      unit: 'mg', 
      max: 5, 
      category: 'otros' 
    },
  ];

  const filteredDrugs = useMemo(() => {
    return drugs.filter(d => 
      d.name.toLowerCase().includes(searchTerm.toLowerCase()) || 
      d.indication.toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [searchTerm]);

  const reset = () => {
    setWeight(10);
    setSearchTerm('');
  };

  return (
    <div className="space-y-6 pb-32">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Link to="/herramientas" className="p-2 hover:bg-muted rounded-full transition-colors">
            <ChevronLeft className="w-6 h-6" />
          </Link>
          <h1 className="text-2xl font-bold flex items-center gap-2">
            <Pill className="w-6 h-6 text-emerald-600" />
            Dosis Pediátricas
          </h1>
        </div>
        <Button variant="ghost" size="sm" onClick={reset} className="gap-2">
          <RotateCcw className="w-4 h-4" /> Reset
        </Button>
      </div>

      <Card className="border-2 border-emerald-500/20 bg-emerald-500/5">
        <CardContent className="pt-6 space-y-4">
          <div className="flex flex-col items-center gap-2">
            <label className="text-sm font-black uppercase tracking-widest text-emerald-800">Peso del Paciente</label>
            <div className="flex items-center gap-4">
              <button 
                className="w-12 h-12 rounded-full bg-white shadow-sm border border-emerald-200 flex items-center justify-center text-2xl font-bold"
                onClick={() => setWeight(prev => Math.max(1, prev - 1))}
              >-</button>
              <div className="flex flex-col items-center">
                <input 
                  type="number" 
                  value={weight} 
                  onChange={(e) => setWeight(Number(e.target.value))}
                  className="bg-transparent border-none text-5xl font-black text-center w-32 focus:ring-0"
                />
                <span className="text-sm font-bold opacity-60">KILOGRAMOS (kg)</span>
              </div>
              <button 
                className="w-12 h-12 rounded-full bg-white shadow-sm border border-emerald-200 flex items-center justify-center text-2xl font-bold"
                onClick={() => setWeight(prev => prev + 1)}
              >+</button>
            </div>
          </div>
          <div className="relative mt-4">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <input 
              type="text" 
              placeholder="Buscar fármaco o indicación..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full bg-background/50 pl-10 pr-4 py-3 rounded-xl border border-emerald-200 focus:ring-2 focus:ring-emerald-500 transition-all"
            />
          </div>
        </CardContent>
      </Card>

      <div className="grid gap-4">
        {filteredDrugs.length > 0 ? (
          filteredDrugs.map((drug) => {
            const result = drug.math(weight);
            const finalValue = (drug.max && result > drug.max) ? drug.max : result;
            const isCapped = drug.max !== undefined && result > drug.max;

            return (
              <Card key={drug.name} className="overflow-hidden border-l-4 border-l-emerald-500">
                <CardContent className="p-0">
                  <div className="p-4 flex justify-between items-start bg-emerald-50/30">
                    <div>
                      <h3 className="font-black text-lg text-emerald-950 uppercase">{drug.name}</h3>
                      <p className="text-xs text-muted-foreground font-medium">{drug.indication}</p>
                    </div>
                    <div className="bg-emerald-600 text-white px-3 py-1 rounded-full text-[10px] font-black uppercase">
                      {drug.category}
                    </div>
                  </div>
                  <div className="p-4 flex items-center justify-between border-t border-emerald-100 italic text-muted-foreground text-xs">
                    <span>Dosis: {drug.dose}</span>
                    {drug.max && <span>Máx: {drug.max} {drug.unit}</span>}
                  </div>
                  <div className="p-6 bg-white flex flex-col items-center">
                    <div className="flex items-baseline gap-2">
                      <span className="text-4xl font-black text-emerald-600">
                        {finalValue.toLocaleString('es-ES', { maximumFractionDigits: 2 })}
                      </span>
                      <span className="text-xl font-bold text-emerald-900/60 uppercase">{drug.unit}</span>
                    </div>
                    {isCapped && (
                      <div className="mt-2 flex items-center gap-1 text-[10px] text-orange-600 font-bold uppercase">
                        <AlertCircle className="w-3 h-3" /> Dosis máxima alcanzada
                      </div>
                    )}
                  </div>
                  {drug.notes && (
                    <div className="p-3 bg-muted/30 text-[10px] text-muted-foreground border-t border-muted border-dashed flex gap-2">
                       <Info className="w-3 h-3 flex-shrink-0" />
                       <p>{drug.notes}</p>
                    </div>
                  )}
                </CardContent>
              </Card>
            );
          })
        ) : (
          <div className="text-center py-20 opacity-30">
            <RotateCcw className="w-12 h-12 mx-auto mb-2" />
            <p className="font-bold">No se encontraron fármacos</p>
          </div>
        )}
      </div>

      <div className="bg-destructive/5 p-4 rounded-xl border border-destructive/10 flex gap-3">
        <AlertCircle className="w-5 h-5 text-destructive flex-shrink-0 mt-0.5" />
        <div className="space-y-1">
          <p className="text-xs font-black text-destructive uppercase tracking-widest">Aviso de Seguridad</p>
          <p className="text-[11px] text-destructive/80 leading-normal italic">
            Esta herramienta es un apoyo al cálculo y no sustituye el juicio clínico. Verifique siempre la concentración de la ampolla antes de administrar. Dosis basadas en guías ERC/AHA 2021.
          </p>
        </div>
      </div>
    </div>
  );
};

export default DoseCalculator;
