import { useState } from 'react';
import { Link } from 'react-router-dom';
import { ChevronLeft, RotateCcw, Activity, AlertTriangle, CheckCircle2, XCircle } from 'lucide-react';
import { Card, CardHeader, CardTitle, CardContent } from "../components/ui/card";
import { Button } from "../components/ui/button";

type TriageColor = 'RED' | 'YELLOW' | 'GREEN' | 'BLACK' | null;

const TriageStart = () => {
  const [step, setStep] = useState<'walking' | 'breathing' | 'airway_check' | 'respiratory_rate' | 'pulse' | 'mental_status' | 'result'>('walking');
  const [result, setResult] = useState<TriageColor>(null);

  const reset = () => {
    setStep('walking');
    setResult(null);
  };

  const handleWalk = (canWalk: boolean) => {
    if (canWalk) {
      setResult('GREEN');
      setStep('result');
    } else {
      setStep('breathing');
    }
  };

  const handleBreathing = (isBreathing: boolean) => {
    if (isBreathing) {
      setStep('respiratory_rate');
    } else {
      setStep('airway_check');
    }
  };

  const handleAirwayCheck = (nowBreathing: boolean) => {
    if (nowBreathing) {
      setResult('RED');
    } else {
      setResult('BLACK');
    }
    setStep('result');
  };

  const handleRate = (above30: boolean) => {
    if (above30) {
      setResult('RED');
      setStep('result');
    } else {
      setStep('pulse');
    }
  };

  const handlePulse = (hasPulse: boolean) => {
    if (!hasPulse) {
      setResult('RED');
      setStep('result');
    } else {
      setStep('mental_status');
    }
  };

  const handleMental = (obeys: boolean) => {
    if (obeys) {
      setResult('YELLOW');
    } else {
      setResult('RED');
    }
    setStep('result');
  };

  const getResultDetails = () => {
    switch (result) {
      case 'RED': return { label: 'ROJO (Prioridad 1)', desc: 'Inmediato - Requiere estabilización rápida.', color: 'bg-red-500', text: 'text-white' };
      case 'YELLOW': return { label: 'AMARILLO (Prioridad 2)', desc: 'Diferido - Requiere atención médica pero puede esperar.', color: 'bg-yellow-500', text: 'text-black' };
      case 'GREEN': return { label: 'VERDE (Prioridad 3)', desc: 'Leve - Puede deambular. No requiere atención inmediata.', color: 'bg-green-500', text: 'text-white' };
      case 'BLACK': return { label: 'NEGRO (Prioridad 0)', desc: 'Fallecido o no recuperable.', color: 'bg-slate-900', text: 'text-white' };
      default: return null;
    }
  };

  const resInfo = getResultDetails();

  return (
    <div className="space-y-6 pb-20">
      <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">
            <AlertTriangle className="w-6 h-6 text-yellow-500" />
            Triage START
          </h1>
        </div>
        <Button variant="ghost" size="sm" onClick={reset} className="gap-2">
          <RotateCcw className="w-4 h-4" /> Reset
        </Button>
      </div>

      <div className="min-h-[300px] flex flex-col justify-center">
        {step === 'walking' && (
          <div className="animate-in fade-in zoom-in duration-300 space-y-8">
            <div className="text-center space-y-4">
              <div className="w-20 h-20 bg-primary/10 rounded-full flex items-center justify-center mx-auto">
                <Activity className="w-10 h-10 text-primary" />
              </div>
              <h2 className="text-3xl font-black text-foreground">¿Puede caminar?</h2>
              <p className="text-muted-foreground">Paso 1: Evaluar capacidad de deambulación.</p>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <Button onClick={() => handleWalk(true)} className="h-32 text-xl font-bold bg-green-500 hover:bg-green-600">SÍ</Button>
              <Button onClick={() => handleWalk(false)} className="h-32 text-xl font-bold bg-slate-700 hover:bg-slate-800">NO</Button>
            </div>
          </div>
        )}

        {step === 'breathing' && (
          <div className="animate-in slide-in-from-right duration-300 space-y-8">
            <h2 className="text-2xl font-bold text-center">¿Respira espontáneamente?</h2>
            <div className="grid grid-cols-2 gap-4">
              <Button onClick={() => handleBreathing(true)} className="h-32 text-xl font-bold py-6">SÍ</Button>
              <Button onClick={() => handleBreathing(false)} className="h-32 text-xl font-bold py-6 variant-outline border-2">NO</Button>
            </div>
          </div>
        )}

        {step === 'airway_check' && (
          <div className="animate-in slide-in-from-right duration-300 space-y-8 text-center">
            <div className="bg-destructive/10 text-destructive p-4 rounded-xl border border-destructive/20 font-bold text-lg mb-6">
              ⚠️ ABRIR VÍA AÉREA (Maniobra frente-mentón)
            </div>
            <h2 className="text-2xl font-bold">¿Respira después de abrir vía aérea?</h2>
            <div className="grid grid-cols-2 gap-4">
              <Button onClick={() => handleAirwayCheck(true)} className="h-32 text-xl font-bold py-6">SÍ</Button>
              <Button onClick={() => handleAirwayCheck(false)} className="h-32 text-xl font-bold py-6 bg-slate-900">NO</Button>
            </div>
          </div>
        )}

        {step === 'respiratory_rate' && (
          <div className="animate-in slide-in-from-right duration-300 space-y-8">
            <h2 className="text-2xl font-bold text-center">¿Frecuencia Respiratoria {'>'} 30/min?</h2>
            <div className="grid grid-cols-2 gap-4">
              <Button onClick={() => handleRate(true)} className="h-32 text-xl font-bold py-6 bg-red-500">SÍ ({'>'}30)</Button>
              <Button onClick={() => handleRate(false)} className="h-32 text-xl font-bold py-6 bg-green-500">NO ({"<"}30)</Button>
            </div>
          </div>
        )}

        {step === 'pulse' && (
          <div className="animate-in slide-in-from-right duration-300 space-y-8">
            <h2 className="text-2xl font-bold text-center">¿Pulso radial presente o fuerte?</h2>
            <div className="grid grid-cols-2 gap-4">
              <Button onClick={() => handlePulse(true)} className="h-32 text-xl font-bold py-6 bg-green-500">PRESENTE</Button>
              <Button onClick={() => handlePulse(false)} className="h-32 text-xl font-bold py-6 bg-red-500">AUSENTE / DÉBIL</Button>
            </div>
          </div>
        )}

        {step === 'mental_status' && (
          <div className="animate-in slide-in-from-right duration-300 space-y-8">
            <h2 className="text-2xl font-bold text-center">¿Obedece órdenes sencillas?</h2>
            <p className="text-center text-muted-foreground uppercase text-xs tracking-widest font-bold">Estado Mental</p>
            <div className="grid grid-cols-2 gap-4">
              <Button onClick={() => handleMental(true)} className="h-32 text-xl font-bold py-6 bg-green-500 uppercase">SÍ</Button>
              <Button onClick={() => handleMental(false)} className="h-32 text-xl font-bold py-6 bg-red-500 uppercase">NO</Button>
            </div>
          </div>
        )}

        {step === 'result' && resInfo && (
          <div className="animate-in zoom-in spin-in-1 duration-500 flex flex-col items-center">
            <div className={`${resInfo.color} ${resInfo.text} w-full rounded-3xl p-10 text-center shadow-xl space-y-6`}>
              {result === 'BLACK' ? <XCircle className="w-20 h-20 mx-auto" /> : <CheckCircle2 className="w-20 h-20 mx-auto" />}
              <div className="space-y-2">
                <h3 className="text-3xl font-black uppercase tracking-tighter">{resInfo.label}</h3>
                <p className="text-lg opacity-90">{resInfo.desc}</p>
              </div>
            </div>
            <Button onClick={reset} className="mt-8 w-full py-6 text-lg font-bold" variant="outline">
              Comenzar nuevo Triage
            </Button>
          </div>
        )}
      </div>

      {/* Progress Footer */}
      {step !== 'walking' && step !== 'result' && (
        <div className="flex justify-center gap-1 mt-10">
          {['breathing', 'respiratory_rate', 'pulse', 'mental_status'].map((s, idx) => (
            <div 
              key={s} 
              className={`h-1.5 rounded-full transition-all duration-500 ${step === s ? 'w-8 bg-primary' : 'w-4 bg-muted'}`}
            />
          ))}
        </div>
      )}
    </div>
  );
};

export default TriageStart;
