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

interface BodyPart {
  id: string;
  name: string;
  percentage: number;
}

const BurnCalculator = () => {
  const [selectedParts, setSelectedParts] = useState<Record<string, boolean>>({});
  const [weight, setWeight] = useState<number>(70);
  const [isPediatric, setIsPediatric] = useState(false);

  const bodyPartsAdult: BodyPart[] = [
    { id: 'head', name: 'Cabeza (9%)', percentage: 9 },
    { id: 'trunk_front', name: 'Tronco Anterior (18%)', percentage: 18 },
    { id: 'trunk_back', name: 'Tronco Posterior (18%)', percentage: 18 },
    { id: 'arm_l', name: 'Brazo Izquierdo (9%)', percentage: 9 },
    { id: 'arm_r', name: 'Brazo Derecho (9%)', percentage: 9 },
    { id: 'leg_l', name: 'Pierna Izquierda (18%)', percentage: 18 },
    { id: 'leg_r', name: 'Pierna Derecha (18%)', percentage: 18 },
    { id: 'genitals', name: 'Genitales (1%)', percentage: 1 },
  ];

  // Regla aproximada para lactantes (Cabeza 18%, Piernas 14%)
  const bodyPartsPed: BodyPart[] = [
    { id: 'head', name: 'Cabeza (18%)', percentage: 18 },
    { id: 'trunk_front', name: 'Tronco Anterior (18%)', percentage: 18 },
    { id: 'trunk_back', name: 'Tronco Posterior (18%)', percentage: 18 },
    { id: 'arm_l', name: 'Brazo Izquierdo (9%)', percentage: 9 },
    { id: 'arm_r', name: 'Brazo Derecho (9%)', percentage: 9 },
    { id: 'leg_l', name: 'Pierna Izquierda (14%)', percentage: 14 },
    { id: 'leg_r', name: 'Pierna Derecha (14%)', percentage: 14 },
    { id: 'genitals', name: 'Genitales (1%)', percentage: 1 },
  ];

  const currentParts = isPediatric ? bodyPartsPed : bodyPartsAdult;

  const tbsa = useMemo(() => {
    return currentParts
      .filter(part => selectedParts[part.id])
      .reduce((sum, part) => sum + part.percentage, 0);
  }, [selectedParts, currentParts]);

  // Parkland: 4ml x kg x %TBSA
  const parklandTotal = weight * tbsa * 4;
  const first8h = parklandTotal / 2;

  const togglePart = (id: string) => {
    setSelectedParts(prev => ({ ...prev, [id]: !prev[id] }));
  };

  const reset = () => {
    setSelectedParts({});
    setWeight(70);
    setIsPediatric(false);
  };

  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">
            <Flame className="w-6 h-6 text-orange-600" />
            Superficie Quemada (TBSA)
          </h1>
        </div>
        <Button variant="ghost" size="sm" onClick={reset} className="gap-2">
          <RotateCcw className="w-4 h-4" /> Reset
        </Button>
      </div>

      <div className="flex p-1 bg-muted rounded-xl">
        <button
          onClick={() => { setIsPediatric(false); setSelectedParts({}); }}
          className={`flex-1 py-2 rounded-lg text-sm font-bold transition-all ${!isPediatric ? 'bg-background shadow-sm' : 'text-muted-foreground'}`}
        >
          ADULTO (Regla de 9)
        </button>
        <button
          onClick={() => { setIsPediatric(true); setSelectedParts({}); }}
          className={`flex-1 py-2 rounded-lg text-sm font-bold transition-all ${isPediatric ? 'bg-background shadow-sm' : 'text-muted-foreground'}`}
        >
          PED / LACTANTE
        </button>
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardHeader className="py-4">
            <CardTitle className="text-sm font-bold uppercase tracking-widest text-muted-foreground">Áreas Afectadas</CardTitle>
          </CardHeader>
          <CardContent className="space-y-2">
            {currentParts.map(part => (
              <Button
                key={part.id}
                variant={selectedParts[part.id] ? 'default' : 'outline'}
                onClick={() => togglePart(part.id)}
                className={`w-full justify-between h-auto py-3 px-4 ${selectedParts[part.id] ? 'bg-orange-600 hover:bg-orange-700' : ''}`}
              >
                <span>{part.name}</span>
                {selectedParts[part.id] && <Calculator className="w-4 h-4 opacity-50" />}
              </Button>
            ))}
          </CardContent>
        </Card>

        <div className="space-y-4">
          <Card className="border-2 border-primary">
            <CardHeader className="pb-2">
              <CardTitle className="text-xs font-black uppercase text-primary tracking-widest">Resultado TBSA</CardTitle>
            </CardHeader>
            <CardContent className="text-center py-6">
              <div className="text-7xl font-black text-foreground">{tbsa}%</div>
              <p className="text-muted-foreground text-sm mt-2">Superficie Corporal Quemada Total</p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="flex items-center gap-2 text-sm font-bold">
                <Droplets className="w-4 h-4 text-blue-500" />
                Fórmula de Parkland
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-1">
                <label className="text-xs text-muted-foreground font-bold">Peso del paciente (kg)</label>
                <input
                  type="number"
                  value={weight}
                  onChange={(e) => setWeight(Number(e.target.value))}
                  className="w-full text-2xl font-bold bg-muted p-3 rounded-xl border-none focus:ring-2 focus:ring-primary"
                />
              </div>

              {tbsa > 0 && (
                <div className="p-4 bg-blue-500/10 rounded-xl border border-blue-500/20 space-y-3">
                  <div className="flex justify-between items-end">
                    <span className="text-sm">Total 24h:</span>
                    <span className="text-2xl font-black text-blue-600">{parklandTotal} ml</span>
                  </div>
                  <div className="flex justify-between items-end border-t border-blue-500/20 pt-2">
                    <span className="text-sm font-bold">Primeras 8h:</span>
                    <span className="text-xl font-bold text-blue-500">{first8h} ml</span>
                  </div>
                  <p className="text-[10px] text-muted-foreground italic leading-tight">
                    * Cristaloides (Ringer Lactato). Iniciar 50% del total en las primeras 8h desde el momento de la lesión.
                  </p>
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>

      <div className="bg-muted/50 p-4 rounded-xl flex gap-3 text-sm text-muted-foreground underline-offset-4 decoration-primary/30">
        <Info className="w-5 h-5 flex-shrink-0 text-primary" />
        <p>
          Utilice la <b>Regla de la Palma</b> (palma con dedos del paciente = 1%) para quemaduras pequeñas o irregulares. No puntuar quemaduras de 1er grado para fluidoterapia.
        </p>
      </div>
    </div>
  );
};

export default BurnCalculator;
