import { useState } from 'react';
import { useProtocol } from '../../hooks/useProtocol';
import { URGENCIAS, ICONOS } from './types';
import { ChevronRight, Loader2, AlertTriangle, Info, AlertCircle } from 'lucide-react';
import { Protocol, ProtocolStep } from '../../hooks/useProtocol';

interface VisualProtocolRendererProps {
  protocolId: string;
}

function StepNum({ children, urgency }: { children: React.ReactNode; urgency?: string }) {
  return (
    <div
      className={`w-8 h-8 rounded-lg flex items-center justify-center font-bold text-sm ${
        urgency === 'critica'
          ? 'bg-red-500 text-white'
          : 'bg-primary text-primary-foreground'
      }`}
    >
      {children}
    </div>
  );
}

function OptionPill({ children, variant }: { children: React.ReactNode; variant: 'si' | 'no' }) {
  return (
    <span
      className={`px-3 py-1.5 rounded-full text-sm font-medium ${
        variant === 'si'
          ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400'
          : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'
      }`}
    >
      {children}
    </span>
  );
}

function AlertBox({ tipo, texto }: { tipo: string; texto: string }) {
  const styles = {
    warning: 'bg-yellow-50 border-yellow-300 text-yellow-800 dark:bg-yellow-900/20 dark:border-yellow-700 dark:text-yellow-300',
    danger: 'bg-red-50 border-red-300 text-red-800 dark:bg-red-900/20 dark:border-red-700 dark:text-red-300',
    info: 'bg-blue-50 border-blue-300 text-blue-800 dark:bg-blue-900/20 dark:border-blue-700 dark:text-blue-300',
  };
  
  const icons = {
    warning: <AlertTriangle className="w-5 h-5" />,
    danger: <AlertCircle className="w-5 h-5" />,
    info: <Info className="w-5 h-5" />,
  };

  return (
    <div className={`flex items-start gap-3 p-4 rounded-lg border ${styles[tipo as keyof typeof styles]}`}>
      {icons[tipo as keyof typeof icons]}
      <p className="text-sm">{texto}</p>
    </div>
  );
}

function MultimediaBlock({ imagen, video }: { imagen?: string; video?: string }) {
  if (!imagen && !video) return null;

  return (
    <div className="mt-4 overflow-hidden rounded-lg border border-border bg-muted/30">
      {video ? (
        <video 
          src={video} 
          controls 
          className="w-full aspect-video object-cover"
          poster={imagen}
        />
      ) : (
        <img 
          src={imagen} 
          alt="Ayuda visual" 
          className="w-full object-cover max-h-[300px]" 
        />
      )}
    </div>
  );
}

function ChecklistBlock({ step, numero }: { step: ProtocolStep; numero: number }) {
  return (
    <div className="flex gap-3">
      <StepNum>{numero}</StepNum>
      <div className="flex-1 space-y-2">
        <h3 className="font-semibold text-foreground">{step.titulo}</h3>
        {step.descripcion && <p className="text-sm text-muted-foreground">{step.descripcion}</p>}
        {step.items && (
          <div className="space-y-1 mt-3">
            {step.items.map((item, i) => (
              <div key={i} className="flex items-start gap-2 text-sm">
                <span className="w-1.5 h-1.5 rounded-full bg-muted-foreground mt-2" />
                <span className="text-foreground">{item}</span>
              </div>
            ))}
          </div>
        )}
        <MultimediaBlock imagen={step.imagen} video={step.video} />
      </div>
    </div>
  );
}

function DecisionBlock({ step, numero }: { step: ProtocolStep; numero: number }) {
  return (
    <div className="flex gap-3">
      <StepNum>{numero}</StepNum>
      <div className="flex-1 rounded-xl border-2 border-blue-200 border-l-4 border-l-blue-400 p-4 dark:border-blue-800 dark:border-l-blue-600">
        <h3 className="font-semibold text-foreground mb-3">{step.titulo}</h3>
        {step.descripcion && <p className="text-sm text-muted-foreground mb-3">{step.descripcion}</p>}
        <div className="flex gap-2 mb-3">
          {step.si && <OptionPill variant="si">→ {step.si}</OptionPill>}
          {step.no && <OptionPill variant="no">→ {step.no}</OptionPill>}
        </div>
        <MultimediaBlock imagen={step.imagen} video={step.video} />
      </div>
    </div>
  );
}

function TechniqueBlock({ step, numero }: { step: ProtocolStep; numero: number }) {
  return (
    <div className="flex gap-3">
      <StepNum urgency={step.urgencia}>{numero}</StepNum>
      <div className={`flex-1 rounded-xl p-4 border ${
        step.urgencia === 'critica'
          ? 'bg-red-50 border-red-200 dark:bg-red-950/30 dark:border-red-800'
          : 'bg-card border-border'
      }`}>
        <div className="flex items-center gap-2 mb-2">
          <h3 className="font-semibold text-foreground">{step.titulo}</h3>
          {step.badge && (
            <span className="px-2 py-0.5 text-xs bg-blue-100 text-blue-700 rounded-full dark:bg-blue-900/30 dark:text-blue-400">
              {step.badge}
            </span>
          )}
        </div>
        {step.descripcion && <p className="text-sm text-muted-foreground mb-3">{step.descripcion}</p>}
        {step.parametros && (
          <div className="space-y-1">
            {step.parametros.map((param, i) => (
              <div
                key={i}
                className={`flex justify-between p-2 rounded ${
                  param.destacado
                    ? 'bg-primary/10 border border-primary/30'
                    : 'bg-muted/50'
                }`}
              >
                <span className="text-xs text-muted-foreground">{param.label}</span>
                <span className={`text-sm font-mono font-semibold ${
                  param.destacado ? 'text-primary' : 'text-foreground'
                }`}>
                  {param.valor}
                </span>
              </div>
            ))}
          </div>
        )}
        <MultimediaBlock imagen={step.imagen} video={step.video} />
      </div>
    </div>
  );
}

function InfoBlock({ step, numero }: { step: ProtocolStep; numero: number }) {
  return (
    <div className="flex gap-3">
      <StepNum>{numero}</StepNum>
      <div className="flex-1 rounded-xl border border-border p-4">
        <h3 className="font-semibold text-foreground mb-2">{step.titulo}</h3>
        {step.descripcion && <p className="text-sm text-muted-foreground">{step.descripcion}</p>}
        <MultimediaBlock imagen={step.imagen} video={step.video} />
      </div>
    </div>
  );
}

function StepRouter({ step, numero }: { step: ProtocolStep; numero: number }) {
  switch (step.tipo) {
    case 'checklist':
      return <ChecklistBlock step={step} numero={numero} />;
    case 'decision':
      return <DecisionBlock step={step} numero={numero} />;
    case 'tecnica':
      return <TechniqueBlock step={step} numero={numero} />;
    case 'info':
      return <InfoBlock step={step} numero={numero} />;
    default:
      return null;
  }
}

function DrugCard({ drug }: { drug: { nombre: string; filas: { label: string; valor: string }[]; formula?: string } }) {
  return (
    <div className="bg-card border border-border rounded-lg p-4">
      <h4 className="font-semibold text-foreground mb-3">{drug.nombre}</h4>
      <div className="space-y-1">
        {drug.filas.map((fila, i) => (
          <div key={i} className="flex justify-between text-sm">
            <span className="text-muted-foreground">{fila.label}</span>
            <span className="text-foreground font-mono">{fila.valor}</span>
          </div>
        ))}
        {drug.formula && (
          <p className="text-xs text-muted-foreground mt-2 pt-2 border-t border-border">{drug.formula}</p>
        )}
      </div>
    </div>
  );
}

function DrugSection({ farmacos }: { farmacos: { nombre: string; filas: { label: string; valor: string }[]; formula?: string }[] }) {
  if (!farmacos || farmacos.length === 0) return null;
  
  return (
    <div className="space-y-3">
      <h3 className="font-semibold text-foreground">💊 Fármacos</h3>
      <div className="grid gap-3 md:grid-cols-2">
        {farmacos.map((drug, i) => (
          <DrugCard key={i} drug={drug} />
        ))}
      </div>
    </div>
  );
}

function EquipmentSection({ equipamiento }: { equipamiento?: string[] }) {
  if (!equipamiento || equipamiento.length === 0) return null;
  
  return (
    <div className="p-4 bg-muted/50 rounded-lg border border-border">
      <h3 className="font-semibold text-foreground mb-3">🛠️ Equipamiento</h3>
      <div className="flex flex-wrap gap-2">
        {equipamiento.map((eq, i) => (
          <span key={i} className="px-2 py-1 bg-card text-sm rounded border border-border">
            {eq}
          </span>
        ))}
      </div>
    </div>
  );
}

export function VisualProtocolRenderer({ protocolId }: VisualProtocolRendererProps) {
  const { protocol, loading, error } = useProtocol(protocolId);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-8 h-8 animate-spin text-primary" />
      </div>
    );
  }

  if (error || !protocol) {
    return (
      <div className="p-6 bg-red-50 border border-red-200 rounded-lg dark:bg-red-950/30 dark:border-red-800">
        <p className="text-red-700 dark:text-red-300">{error || 'Protocolo no encontrado'}</p>
      </div>
    );
  }

  // Normalizar datos de Estilo 2 (fases) a Estilo 1 (pasos)
  const normalizedSteps: ProtocolStep[] = protocol.pasos || (protocol.fases?.map(fase => ({
    tipo: fase.tipo as any,
    titulo: fase.nombre,
    descripcion: fase.tipo === 'decision' ? fase.pregunta || fase.descripcion : fase.descripcion,
    items: fase.items?.map((item: any) => typeof item === 'string' ? item : (item as any).texto),
    urgencia: (fase as any).urgencia,
    badge: (fase as any).badge,
    parametros: fase.parametros as any,
    si: (fase.ramas as any[])?.find(r => r.condicion.toLowerCase() === 'sí' || r.condicion.toLowerCase() === 'si')?.condicion,
    no: (fase.ramas as any[])?.find(r => r.condicion.toLowerCase() === 'no')?.condicion,
  })) || []);

  const urgenciaInfo = URGENCIAS[protocol.urgencia] || { label: protocol.urgencia, color: 'border-muted' };

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      {/* Header */}
      <div className="space-y-3">
        <div className="flex items-center gap-3">
          <span className={`px-3 py-1 rounded-full text-sm font-medium border ${urgenciaInfo.color}`}>
            {urgenciaInfo.label}
          </span>
          <span className="text-xs text-muted-foreground">v{protocol.version}</span>
          {protocol.fuente && (
            <span className="text-xs text-muted-foreground">· {protocol.fuente}</span>
          )}
        </div>
        
        <h1 className="text-2xl font-bold text-foreground">{protocol.titulo}</h1>
        
        {(protocol.subtitulo || protocol.descripcion) && (
          <p className="text-muted-foreground">{protocol.subtitulo || protocol.descripcion}</p>
        )}
      </div>

      {/* Global Alerts */}
      {protocol.alertas?.map((alerta, i) => (
        <AlertBox key={i} tipo={alerta.tipo} texto={alerta.texto} />
      ))}

      {/* Steps */}
      <div className="space-y-4">
        {normalizedSteps.map((step, i) => (
          <StepRouter key={i} step={step} numero={i + 1} />
        ))}
      </div>

      {/* Drugs */}
      <DrugSection farmacos={protocol.farmacos || []} />

      {/* Equipment */}
      <EquipmentSection equipamiento={protocol.equipamiento} />
    </div>
  );
}