import { useState, useEffect, useRef } from 'react';
import { Link } from 'react-router-dom';
import {
  Calculator,
  Table,
  AlertCircle,
  AlertTriangle,
  BookOpen,
  Play,
  Pause,
  RotateCcw,
  Heart,
  Wind,
  Timer,
  Droplets,
  Ruler,
  Scale,
  Activity,
  ChevronRight,
  Flame,
  Pill,
} from 'lucide-react';

const GlasgowCalculator = () => {
  return (
    <Link to="/herramientas/glasgow" className="block card-procedure p-4 hover:border-primary/50 transition-colors">
      <div className="flex items-center gap-3 mb-2">
        <Activity className="w-5 h-5 text-primary" />
        <h3 className="font-bold text-foreground">Escala de Glasgow (GCS)</h3>
      </div>
      <p className="text-sm text-muted-foreground mb-3">
        Evaluación neurológica rápida con criterios específicos para **Adultos** y **Lactantes/Pediatría**.
      </p>
      <div className="flex justify-between items-center bg-muted/50 p-2 rounded-lg">
        <span className="text-xs font-medium">Ver calculadora avanzada</span>
        <ChevronRight className="w-4 h-4 text-primary" />
      </div>
    </Link>
  );
};


const RCPTimer = () => {
  const [segundos, setSegundos] = useState(0);
  const [corriendo, setCorriendo] = useState(false);
  const intervaloRef = useRef<number | null>(null);

  useEffect(() => {
    if (corriendo) {
      intervaloRef.current = window.setInterval(() => {
        setSegundos((s) => s + 1);
      }, 1000);
    } else if (intervaloRef.current) {
      clearInterval(intervaloRef.current);
    }
    return () => {
      if (intervaloRef.current) clearInterval(intervaloRef.current);
    };
  }, [corriendo]);

  const minutos = Math.floor(segundos / 60);
  const remainingSegundos = segundos % 60;
  const ciclos = Math.floor(segundos / 120);

  const reset = () => {
    setSegundos(0);
    setCorriendo(false);
  };

  const getAlerta = () => {
    if (segundos === 0) return '';
    if (segundos % 120 === 0) return '🔄 Cambiar reductor';
    if (segundos % 30 === 0) return '👁️ Evaluar ritmo';
    return '';
  };

  return (
    <div className="card-procedure p-4">
      <div className="flex items-center gap-2 mb-3">
        <Timer className="w-5 h-5 text-primary" />
        <h3 className="font-bold text-foreground">Temporizador RCP</h3>
      </div>

      <div className="space-y-3">
        <div className="text-center p-6 bg-muted rounded-lg">
          <p className="text-5xl font-bold text-foreground">
            {minutos.toString().padStart(2, '0')}:
            {remainingSegundos.toString().padStart(2, '0')}
          </p>
          {getAlerta() && (
            <p className="mt-2 text-sm text-yellow-500 font-medium">{getAlerta()}</p>
          )}
        </div>

        <p className="text-sm text-muted-foreground text-center">
          Cycles: {ciclos} | 100-120 com/min
        </p>

        <div className="flex gap-2">
          <button
            onClick={() => setCorriendo(!corriendo)}
            className={`flex-1 p-3 rounded-lg font-medium flex items-center justify-center gap-2 ${
              corriendo
                ? 'bg-yellow-500 text-black'
                : 'bg-primary text-primary-foreground'
            }`}
          >
            {corriendo ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}
            {corriendo ? 'Pausar' : 'Iniciar'}
          </button>
          <button
            onClick={reset}
            className="p-3 rounded-lg bg-muted text-muted-foreground flex items-center justify-center"
          >
            <RotateCcw className="w-4 h-4" />
          </button>
        </div>
      </div>
    </div>
  );
};

const OxygenDurationCalculator = () => {
  const [presion, setPresion] = useState(200);
  const [flujo, setFlujo] = useState(15);
  const duracion = Math.round((presion - 200) / flujo);

  return (
    <div className="card-procedure p-4">
      <div className="flex items-center gap-2 mb-3">
        <Wind className="w-5 h-5 text-primary" />
        <h3 className="font-bold text-foreground">Duración de O₂</h3>
      </div>

      <div className="space-y-3">
        <div>
          <label className="text-sm text-muted-foreground">Presión cilindro (bar)</label>
          <input
            type="number"
            value={presion}
            onChange={(e) => setPresion(Number(e.target.value))}
            className="w-full p-2 mt-1 bg-muted rounded border border-border"
          />
        </div>

        <div>
          <label className="text-sm text-muted-foreground">Flujo (L/min)</label>
          <input
            type="range"
            min="1"
            max="25"
            value={flujo}
            onChange={(e) => setFlujo(Number(e.target.value))}
            className="w-full"
          />
          <p className="text-sm text-center text-foreground">{flujo} L/min</p>
        </div>

        <div className="p-4 bg-muted rounded-lg text-center">
          <p className="text-sm text-muted-foreground">Duración estimada</p>
          <p className="text-2xl font-bold text-foreground">
            {presion <= 200 ? '⛔ Vacío' : `~${duracion} min`}
          </p>
        </div>
      </div>
    </div>
  );
};

const DripRateCalculator = () => {
  const [volumen, setVolumen] = useState(500);
  const [tiempo, setTiempo] = useState(60);
  const [factor, setFactor] = useState(20);
  const gotas = Math.round((volumen / tiempo) * factor);
  const microgotas = Math.round((volumen / tiempo) * factor * 60);

  return (
    <div className="card-procedure p-4">
      <div className="flex items-center gap-2 mb-3">
        <Droplets className="w-5 h-5 text-primary" />
        <h3 className="font-bold text-foreground">Velocidad de Perfusión</h3>
      </div>

      <div className="space-y-3">
        <div>
          <label className="text-sm text-muted-foreground">Volumen (ml)</label>
          <input
            type="number"
            value={volumen}
            onChange={(e) => setVolumen(Number(e.target.value))}
            className="w-full p-2 mt-1 bg-muted rounded border border-border"
          />
        </div>

        <div>
          <label className="text-sm text-muted-foreground">Tiempo (min)</label>
          <input
            type="number"
            value={tiempo}
            onChange={(e) => setTiempo(Number(e.target.value))}
            className="w-full p-2 mt-1 bg-muted rounded border border-border"
          />
        </div>

        <div>
          <label className="text-sm text-muted-foreground">Factor gotero</label>
          <select
            value={factor}
            onChange={(e) => setFactor(Number(e.target.value))}
            className="w-full p-2 mt-1 bg-muted rounded border border-border"
          >
            <option value="10">10 (infusión adulto)</option>
            <option value="15">15 (estándar)</option>
            <option value="20">20 (macro)</option>
            <option value="60">60 (microgotas)</option>
          </select>
        </div>

        <div className="grid grid-cols-2 gap-2">
          <div className="p-3 bg-muted rounded-lg text-center">
            <p className="text-xs text-muted-foreground">Gotas/min</p>
            <p className="text-xl font-bold text-foreground">{gotas}</p>
          </div>
          <div className="p-3 bg-muted rounded-lg text-center">
            <p className="text-xs text-muted-foreground">Microgotas/min</p>
            <p className="text-xl font-bold text-foreground">{microgotas}</p>
          </div>
        </div>
      </div>
    </div>
  );
};

const BMICalculator = () => {
  const [peso, setPeso] = useState(70);
  const alturaRef = useRef<HTMLInputElement>(null);
  const [altura, setAltura] = useState(170);
  const imc = peso / Math.pow(altura / 100, 2);

  const getColor = () => {
    if (imc < 18.5) return 'text-blue-500';
    if (imc < 25) return 'text-green-500';
    if (imc < 30) return 'text-yellow-500';
    return 'text-red-500';
  };

  const getClasificacion = () => {
    if (imc < 18.5) return 'Bajo peso';
    if (imc < 25) return 'Normal';
    if (imc < 30) return 'Sobrepeso';
    return 'Obesidad';
  };

  return (
    <div className="card-procedure p-4">
      <div className="flex items-center gap-2 mb-3">
        <Scale className="w-5 h-5 text-primary" />
        <h3 className="font-bold text-foreground">Índice de Masa Corporal</h3>
      </div>

      <div className="space-y-3">
        <div>
          <label className="text-sm text-muted-foreground">Peso (kg)</label>
          <input
            type="number"
            value={peso}
            onChange={(e) => setPeso(Number(e.target.value))}
            className="w-full p-2 mt-1 bg-muted rounded border border-border"
          />
        </div>

        <div>
          <label className="text-sm text-muted-foreground">Altura (cm)</label>
          <input
            type="number"
            value={altura}
            onChange={(e) => setAltura(Number(e.target.value))}
            className="w-full p-2 mt-1 bg-muted rounded border border-border"
          />
        </div>

        <div className="p-4 bg-muted rounded-lg text-center">
          <p className="text-sm text-muted-foreground">IMC</p>
          <p className={`text-3xl font-bold ${getColor()}`}>{imc.toFixed(1)}</p>
          <p className={`text-sm ${getColor()}`}>{getClasificacion()}</p>
        </div>
      </div>
    </div>
  );
};

const PediatricDoseCalculator = () => {
  const [peso, setPeso] = useState(30);
  const [dosis, setDosis] = useState(0.1);
  const [concentracion, setConcentracion] = useState(1);
  const total = peso * dosis;
  const volumen = total / concentracion;

  const medicamentos = [
    { nombre: 'Adrenalina', dosis: 0.01, conc: 1 },
    { nombre: 'Amiodarona', dosis: 5, conc: 10 },
    { nombre: 'Atropina', dosis: 0.02, conc: 1 },
    { nombre: 'Adenosina', dosis: 0.1, conc: 3 },
  ];

  const seleccionar = (med: typeof medicamentos[0]) => {
    setDosis(med.dosis);
    setConcentracion(med.conc);
  };

  return (
    <div className="card-procedure p-4">
      <div className="flex items-center gap-2 mb-3">
        <Calculator className="w-5 h-5 text-primary" />
        <h3 className="font-bold text-foreground">Dosis Pediátricas</h3>
      </div>

      <div className="space-y-3">
        <div className="flex gap-1 overflow-x-auto pb-2">
          {medicamentos.map((med) => (
            <button
              key={med.nombre}
              onClick={() => seleccionar(med)}
              className="px-2 py-1 text-xs bg-muted rounded whitespace-nowrap"
            >
              {med.nombre}
            </button>
          ))}
        </div>

        <div>
          <label className="text-sm text-muted-foreground">Peso (kg)</label>
          <input
            type="number"
            value={peso}
            onChange={(e) => setPeso(Number(e.target.value))}
            className="w-full p-2 mt-1 bg-muted rounded border border-border"
          />
        </div>

        <div className="grid grid-cols-2 gap-2">
          <div>
            <label className="text-sm text-muted-foreground">Dosis (mg/kg)</label>
            <input
              type="number"
              step="0.01"
              value={dosis}
              onChange={(e) => setDosis(Number(e.target.value))}
              className="w-full p-2 mt-1 bg-muted rounded border border-border"
            />
          </div>
          <div>
            <label className="text-sm text-muted-foreground">Conc. (mg/ml)</label>
            <input
              type="number"
              value={concentracion}
              onChange={(e) => setConcentracion(Number(e.target.value))}
              className="w-full p-2 mt-1 bg-muted rounded border border-border"
            />
          </div>
        </div>

        <div className="grid grid-cols-2 gap-2">
          <div className="p-3 bg-muted rounded-lg text-center">
            <p className="text-xs text-muted-foreground">Dosis total</p>
            <p className="text-lg font-bold text-foreground">{total.toFixed(2)} mg</p>
          </div>
          <div className="p-3 bg-muted rounded-lg text-center">
            <p className="text-xs text-muted-foreground">Volumen</p>
            <p className="text-lg font-bold text-foreground">{volumen.toFixed(2)} ml</p>
          </div>
        </div>
      </div>
    </div>
  );
};

const CervicalCollarSizeCalculator = () => {
  const [altura, setAltura] = useState(170);
  const getTalla = () => {
    if (altura < 150) return 'Pediatrico';
    if (altura < 165) return 'S';
    if (altura < 180) return 'M';
    return 'L';
  };

  return (
    <div className="card-procedure p-4">
      <div className="flex items-center gap-2 mb-3">
        <Ruler className="w-5 h-5 text-primary" />
        <h3 className="font-bold text-foreground">Talla Collarín Cervical</h3>
      </div>

      <div className="space-y-3">
        <div>
          <label className="text-sm text-muted-foreground">Altura (cm)</label>
          <input
            type="range"
            min="120"
            max="210"
            value={altura}
            onChange={(e) => setAltura(Number(e.target.value))}
            className="w-full"
          />
          <p className="text-sm text-center text-foreground">{altura} cm</p>
        </div>

        <div className="p-4 bg-muted rounded-lg text-center">
          <p className="text-sm text-muted-foreground">Talla recomendada</p>
          <p className="text-3xl font-bold text-foreground">{getTalla()}</p>
        </div>
      </div>
    </div>
  );
};

const featureFlags = {
  vitalsDashboard: false,
  advancedTools: false,
  smartPerfusions: true,
  interactiveChecklists: false,
  pathways: false,
};

const tabs = [
  { id: 'calculadoras', label: 'Calculadoras', icon: Calculator },
  { id: 'anatomia', label: 'Anatomía', icon: BookOpen },
  { id: 'codigos', label: 'Códigos', icon: AlertCircle },
  { id: 'perfusiones', label: 'Perfusiones', icon: Table },
];

const codigosProtocolo = [
  {
    name: 'Código Ictus',
    description: 'Activación ante sospecha de ictus agudo',
    path: '/ictus',
    color: 'bg-secondary',
  },
  {
    name: 'Código IAM',
    description: 'SCACEST - Infarto con elevación ST',
    path: '/patologias',
    color: 'bg-primary',
  },
  {
    name: 'Código Sepsis',
    description: 'Sospecha de sepsis severa / shock séptico',
    path: '/shock',
    color: 'bg-destructive',
  },
  {
    name: 'Código Parada',
    description: 'PCR - Parada cardiorrespiratoria',
    path: '/rcp',
    color: 'bg-primary',
  },
];

const infusionTables = [
  { id: '1', name: 'Dopamina', description: '4-20 mcg/kg/min' },
  { id: '2', name: 'Noradrenalina', description: '0.1-30 mcg/kg/min' },
  { id: '3', name: 'Adrenalina', description: '0.01-0.3 mcg/kg/min' },
  { id: '4', name: 'Amiodarona', description: 'Bolo: 5mg/kg' },
];

const Herramientas = () => {
  const [activeTab, setActiveTab] = useState('calculadoras');
  const [perfusionsMode, setPerfusionsMode] = useState<'tabla' | 'calculadora'>('calculadora');

  return (
    <div className="space-y-4">
      <div>
        <h1 className="text-2xl font-bold text-foreground mb-1">Herramientas</h1>
        <p className="text-muted-foreground text-sm">
          Calculadoras, tablas y códigos de emergencia
        </p>
      </div>

      <div className="flex gap-2 overflow-x-auto scrollbar-hide -mx-4 px-4">
        {tabs.map((tab) => {
          const Icon = tab.icon;
          return (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition-colors ${
                activeTab === tab.id
                  ? 'bg-secondary text-secondary-foreground'
                  : 'bg-muted text-muted-foreground hover:bg-accent'
              }`}
            >
              <Icon className="w-4 h-4" />
              {tab.label}
            </button>
          );
        })}
      </div>

      {activeTab === 'calculadoras' && (
        <div className="grid gap-4 md:grid-cols-2">
          <GlasgowCalculator />
          <Link to="/herramientas/triage" className="block card-procedure p-4 border-l-4 border-l-orange-500 hover:border-primary/50 transition-colors">
            <div className="flex items-center gap-3 mb-2">
              <AlertTriangle className="w-5 h-5 text-orange-500" />
              <h3 className="font-bold text-foreground">Triage START (IMV)</h3>
            </div>
            <p className="text-sm text-muted-foreground mb-3">
              Clasificación rápida de víctimas en catástrofes. Prioridades Rojo, Amarillo, Verde, Negro.
            </p>
            <div className="flex justify-between items-center bg-muted/50 p-2 rounded-lg">
              <span className="text-xs font-medium">Iniciar clasificación</span>
              <ChevronRight className="w-4 h-4 text-primary" />
            </div>
          </Link>
          <Link to="/herramientas/quemados" className="block card-procedure p-4 border-l-4 border-l-orange-600 hover:border-primary/50 transition-colors">
            <div className="flex items-center gap-3 mb-2">
              <Flame className="w-5 h-5 text-orange-600" />
              <h3 className="font-bold text-foreground">Quemados y Parkland</h3>
            </div>
            <p className="text-sm text-muted-foreground mb-3">
              Cálculo de superficie corporal quemada (SCQ) y fluidoterapia inicial (Fórmula de Parkland).
            </p>
            <div className="flex justify-between items-center bg-muted/50 p-2 rounded-lg">
              <span className="text-xs font-medium">Abrir calculadora</span>
              <ChevronRight className="w-4 h-4 text-primary" />
            </div>
          </Link>
          <Link to="/herramientas/dosis" className="block card-procedure p-4 border-l-4 border-l-emerald-600 hover:border-primary/50 transition-colors">
            <div className="flex items-center gap-3 mb-2">
              <Pill className="w-5 h-5 text-emerald-600" />
              <h3 className="font-bold text-foreground">Dosis Pediátricas</h3>
            </div>
            <p className="text-sm text-muted-foreground mb-3">
              Cálculo de mg y ml por peso (kg) para fármacos críticos (Adrenalina, Amiodarona, etc.).
            </p>
            <div className="flex justify-between items-center bg-muted/50 p-2 rounded-lg">
              <span className="text-xs font-medium">Abrir calculadora</span>
              <ChevronRight className="w-4 h-4 text-primary" />
            </div>
          </Link>
          <RCPTimer />
          <OxygenDurationCalculator />
          <DripRateCalculator />
          <BMICalculator />
          <PediatricDoseCalculator />
          <CervicalCollarSizeCalculator />
        </div>
      )}

      {activeTab === 'perfusiones' && (
        <div className="space-y-4">
          <div className="flex gap-2">
            <button
              type="button"
              onClick={() => setPerfusionsMode('calculadora')}
              className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${
                perfusionsMode === 'calculadora'
                  ? 'bg-secondary text-secondary-foreground'
                  : 'bg-muted text-muted-foreground'
              }`}
            >
              Calculadora
            </button>
            <button
              type="button"
              onClick={() => setPerfusionsMode('tabla')}
              className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${
                perfusionsMode === 'tabla'
                  ? 'bg-secondary text-secondary-foreground'
                  : 'bg-muted text-muted-foreground'
              }`}
            >
              Tablas
            </button>
          </div>

          {perfusionsMode === 'calculadora' ? (
            <DripRateCalculator />
          ) : (
            <div className="grid gap-3">
              {infusionTables.map((table) => (
                <div key={table.id} className="card-procedure p-4">
                  <h3 className="font-bold text-foreground">{table.name}</h3>
                  <p className="text-sm text-muted-foreground">{table.description}</p>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {activeTab === 'anatomia' && (
        <div className="card-procedure p-4">
          <div className="flex items-center gap-2 mb-3">
            <BookOpen className="w-5 h-5 text-primary" />
            <h3 className="font-bold text-foreground">Guía de Terminología Anatómica</h3>
          </div>
          <p className="text-sm text-muted-foreground">
            Referencia rápida de términos anatómicos de uso común en emergencias.
            Próximamente disponible.
          </p>
        </div>
      )}

      {activeTab === 'codigos' && (
        <div className="space-y-3">
          {codigosProtocolo.map((codigo) => (
            <Link
              key={codigo.name}
              to={codigo.path}
              className="block card-procedure hover:border-primary/50"
            >
              <div className="flex items-center gap-4">
                <div className={`w-12 h-12 rounded-lg ${codigo.color} flex items-center justify-center`}>
                  <AlertCircle className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h3 className="font-bold text-foreground">{codigo.name}</h3>
                  <p className="text-muted-foreground text-sm">
                    {codigo.description}
                  </p>
                </div>
              </div>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
};

export default Herramientas;