import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import {
  Wind,
  AlertTriangle,
  ChevronRight,
  Baby,
  Users,
  Check,
  RotateCcw,
  GraduationCap,
  BookOpen,
  Cloud,
} from 'lucide-react';
import { protocolApi, TelephoneProtocol } from '../services/api';

// Simplified components
const BackButton = ({ to, label }: { to: string; label: string }) => (
  <Link to={to} className="flex items-center gap-3 p-4 bg-card border border-border rounded-xl hover:border-primary/50 transition-colors">
    <AlertTriangle className="w-5 h-5" />
    <span>{label}</span>
  </Link>
);

// Adaptar estructura de la API al formato esperado por el frontend
interface ProtocolStep {
  id: string;
  instruction: string;
  verification?: string;
  notes?: string;
  critical?: boolean;
}

interface Protocol {
  id: string;
  title: string;
  shortTitle: string;
  category: string;
  ageGroup: string;
  description: string;
  steps: ProtocolStep[];
  warnings?: string[];
  keyPoints?: string[];
  equipment?: string[];
  drugs?: string[];
}

const mapApiProtocolToProtocol = (apiProtocol: TelephoneProtocol): Protocol => {
  const steps = apiProtocol.steps.map(step => ({
    id: step.id,
    instruction: step.instruction,
    verification: step.verification,
    notes: step.notes,
    critical: step.critical,
  }));

  const warnings = apiProtocol.importantNotes;

  // Campos que no vienen en la API actual
  const keyPoints: string[] = [];
  const equipment: string[] = [];
  const drugs: string[] = [];

  return {
    id: apiProtocol.id,
    title: apiProtocol.title,
    shortTitle: apiProtocol.shortTitle,
    category: apiProtocol.category,
    ageGroup: apiProtocol.ageGroup,
    description: apiProtocol.description,
    steps,
    warnings,
    keyPoints,
    equipment,
    drugs,
  };
};

const ViaAerea = () => {
  // Estados para carga de datos
  const [protocols, setProtocols] = useState<Protocol[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Cargar protocolos desde la API al montar el componente
  useEffect(() => {
    const fetchProtocols = async () => {
      try {
        setLoading(true);
        const response = await protocolApi.getAll();
        
        // Filtrar protocolos de OVACE
        const ovaceProtocols = response.data.filter(p => p.category === 'ovace');
        
        // Mapear a formato del frontend
        const mappedProtocols = ovaceProtocols.map(mapApiProtocolToProtocol);
        
        setProtocols(mappedProtocols);
        setError(null);
      } catch (err) {
        console.error('Error fetching protocols:', err);
        setError('No se pudieron cargar los protocolos. Usando datos locales.');
        // Podríamos cargar datos locales de respaldo aquí si fuera necesario
      } finally {
        setLoading(false);
      }
    };

    fetchProtocols();
  }, []);

  // Encontrar el protocolo OVACE Adulto
  const ovaceProtocol = protocols.find(p => p.id === 'ovace-telephone-adult');

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="w-8 h-8 border-2 border-primary border-t-transparent rounded-full animate-spin"></div>
      </div>
    );
  }

  if (error) {
    console.warn(error);
  }

  return (
    <div className="space-y-6">
      <BackButton to="/" label="Volver al inicio" />

      {/* Header */}
      <div className="space-y-4">
        <div className="flex items-center gap-3">
          <div className="w-12 h-12 rounded-xl bg-red-500/20 flex items-center justify-center">
            <Wind className="w-7 h-7 text-red-500" />
          </div>
          <div className="flex-1">
            <div className="flex items-center gap-2">
              <h1 className="text-3xl font-bold text-foreground">Vía Aérea</h1>
              <span className="inline-flex items-center gap-1 px-2 py-1 text-xs bg-blue-500/10 text-blue-500 border border-blue-500/20 rounded-md">
                <Cloud className="w-3 h-3" />
                Externo
              </span>
            </div>
            <p className="text-muted-foreground">OVACE (Obstrucción de Vía Aérea por Cuerpo Extraño)</p>
          </div>
        </div>
      </div>

      {/* Protocolo OVACE */}
      {ovaceProtocol && (
        <div className="bg-card border border-border rounded-xl p-6 space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="text-xl font-semibold text-foreground">{ovaceProtocol.title}</h2>
            <span className="px-3 py-1 bg-red-500/20 text-red-600 dark:text-red-400 rounded-full text-xs font-medium">
              Crítico
            </span>
          </div>

          <div className="space-y-4">
            <div>
              <h3 className="font-semibold text-foreground mb-2 flex items-center gap-2">
                <AlertTriangle className="w-4 h-4 text-yellow-500" />
                Pasos del Protocolo
              </h3>
              <ol className="space-y-2 list-decimal list-inside">
                {ovaceProtocol.steps.map((step, index) => (
                  <li key={index} className="text-foreground pl-2">
                    {step.instruction}
                    {step.verification && (
                      <div className="mt-1 text-xs text-muted-foreground">
                        Verificación: {step.verification}
                      </div>
                    )}
                    {step.notes && (
                      <div className="mt-1 text-xs text-muted-foreground italic">
                        Nota: {step.notes}
                      </div>
                    )}
                    {step.critical && (
                      <span className="ml-2 px-2 py-0.5 bg-red-500/20 text-red-600 rounded text-xs">
                        CRÍTICO
                      </span>
                    )}
                  </li>
                ))}
              </ol>
            </div>

            {/* Advertencias */}
            {ovaceProtocol.warnings && ovaceProtocol.warnings.length > 0 && (
              <div>
                <h3 className="font-semibold text-foreground mb-2">Advertencias Importantes</h3>
                <ul className="space-y-1">
                  {ovaceProtocol.warnings.map((warning, index) => (
                    <li key={index} className="text-sm text-muted-foreground flex items-start gap-2">
                      <span className="text-orange-500 mt-1">•</span>
                      <span>{warning}</span>
                    </li>
                  ))}
                </ul>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Si no hay datos de la API, mostrar mensaje */}
      {!ovaceProtocol && !loading && (
        <div className="bg-card border border-border rounded-xl p-6 space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="text-xl font-semibold text-foreground">OVACE (Obstrucción de Vía Aérea por Cuerpo Extraño)</h2>
            <span className="px-3 py-1 bg-red-500/20 text-red-600 dark:text-red-400 rounded-full text-xs font-medium">
              Crítico
            </span>
          </div>

          <div className="space-y-4">
            <div>
              <h3 className="font-semibold text-foreground mb-2 flex items-center gap-2">
                <AlertTriangle className="w-4 h-4 text-yellow-500" />
                Pasos del Protocolo
              </h3>
              <ol className="space-y-2 list-decimal list-inside">
                <li className="text-foreground pl-2">Valorar la gravedad de la obstrucción</li>
                <li className="text-foreground pl-2">Si es leve: animar a toser</li>
                <li className="text-foreground pl-2">Si es grave: iniciar maniobras de desobstrucción</li>
              </ol>
            </div>
          </div>
        </div>
      )}

      {/* Variaciones por Edad */}
      <div className="bg-card border border-border rounded-xl p-6 space-y-4">
        <h2 className="text-xl font-semibold text-foreground">Variaciones por Edad</h2>
        
        <div className="space-y-4">
          <div className="bg-muted/50 rounded-lg p-4">
            <div className="font-semibold text-foreground mb-2 flex items-center gap-2">
              <Users className="w-4 h-4" />
              Adultos y Niños (&gt;1 año)
            </div>
            <ul className="text-sm text-muted-foreground space-y-1">
              <li>• 5 golpes interescapulares</li>
              <li>• 5 compresiones abdominales (Heimlich)</li>
              <li>• Alternar hasta resolución o pérdida de consciencia</li>
            </ul>
          </div>
          
          <div className="bg-muted/50 rounded-lg p-4">
            <div className="font-semibold text-foreground mb-2 flex items-center gap-2">
              <Baby className="w-4 h-4" />
              Lactantes (&lt;1 año)
            </div>
            <ul className="text-sm text-muted-foreground space-y-1">
              <li>• 5 golpes en la espalda</li>
              <li>• 5 compresiones torácicas</li>
              <li>• NO hacer compresiones abdominales</li>
            </ul>
          </div>
        </div>
      </div>

      {/* Enlaces relacionados */}
      <div className="bg-muted/50 border border-border rounded-xl p-4">
        <h3 className="font-semibold text-foreground mb-3">Protocolos Relacionados</h3>
        <div className="space-y-2">
          <Link
            to="/rcp"
            className="flex items-center justify-between p-3 bg-card rounded-lg hover:bg-accent transition-colors"
          >
            <span className="text-foreground">RCP (si pierde consciencia)</span>
            <ChevronRight className="w-5 h-5 text-muted-foreground" />
          </Link>
        </div>
      </div>
    </div>
  );
};

export default ViaAerea;
