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

// Simplified components for migration
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>
);

const PageLoader = () => (
  <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>
);

const NotFound = ({ message, backTo }: { message: string; backTo: string }) => (
  <div className="min-h-flex flex-col items-center justify-center p-6 text-center">
    <h1 className="text-3xl font-bold text-foreground">{message}</h1>
    <Link to={backTo} className="mt-4 px-4 py-2 bg-primary text-primary-foreground rounded hover:bg-primary/90">
      Volver al inicio
    </Link>
  </div>
);

// 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 => {
  // Mapear steps (order no se usa visualmente)
  const steps = apiProtocol.steps.map(step => ({
    id: step.id,
    instruction: step.instruction,
    verification: step.verification,
    notes: step.notes,
    critical: step.critical,
  }));

  // Mapear importantNotes a warnings
  const warnings = apiProtocol.importantNotes;

  // Campos que no vienen en la API actual (dejar vacíos o mapear si es necesario)
  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 RCP = () => {
  const [activeTab, setActiveTab] = useState<'adulto' | 'pediatrico'>('adulto');
  const [isChecklistMode, setIsChecklistMode] = useState(false);
  const [checkedItems, setCheckedItems] = useState<Set<number>>(new Set());
  
  // 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 RCP
        const rcpProtocols = response.data.filter(p => p.category === 'rcp');
        
        // Mapear a formato del frontend
        const mappedProtocols = rcpProtocols.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();
  }, []);

  // RCP checklist steps (hardcoded for emergency use)
  const rcpChecklistSteps = [
    'Seguridad de la escena',
    'Comprobación de respuesta',
    'Apertura de vía aérea',
    'Comprobación de respiración (<10s)',
    'Activación de emergencias',
    'Inicio de compresiones',
    'Colocación del DEA',
    'Análisis y descarga si indicada',
    'RCP de alta calidad continua',
    'Reevaluación cada 2 minutos',
  ];

  // Encontrar el protocolo seleccionado basado en el tab y ageGroup
  const selectedProtocol = protocols.find(p => 
    activeTab === 'adulto' ? p.ageGroup === 'adulto' : p.ageGroup === 'pediatrico'
  );
  
  const protocolTitle = activeTab === 'adulto' ? 'Soporte Vital Básico (SVB)' : 'RCP Pediátrico';

  const handleTabChange = (tab: 'adulto' | 'pediatrico') => {
    setActiveTab(tab);
    setIsChecklistMode(false);
    setCheckedItems(new Set());
  };

  const handleToggleChecklist = () => {
    setIsChecklistMode(!isChecklistMode);
    if (!isChecklistMode) {
      setCheckedItems(new Set());
    }
  };

  const handleStepToggle = (index: number) => {
    const newChecked = new Set(checkedItems);
    if (newChecked.has(index)) {
      newChecked.delete(index);
    } else {
      newChecked.add(index);
    }
    setCheckedItems(newChecked);
  };

  if (loading) {
    return <PageLoader />;
  }

  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">
            <Heart className="w-7 h-7 text-red-500" />
          </div>
          <div>
            <h1 className="text-3xl font-bold text-foreground">RCP / Parada Cardiorrespiratoria</h1>
            <p className="text-muted-foreground">Protocolo de Reanimación Cardiopulmonar</p>
          </div>
        </div>

        {/* Tabs Adulto/Pediátrico */}
        <div className="flex gap-2 border-b border-border">
          <button
            onClick={() => handleTabChange('adulto')}
            className={`px-4 py-2 font-medium transition-colors ${
              activeTab === 'adulto'
                ? 'text-primary border-b-2 border-primary'
                : 'text-muted-foreground hover:text-foreground'
            }`}
          >
            <div className="flex items-center gap-2">
              <Users className="w-4 h-4" />
              <span>Adulto</span>
            </div>
          </button>
          <button
            onClick={() => handleTabChange('pediatrico')}
            className={`px-4 py-2 font-medium transition-colors ${
              activeTab === 'pediatrico'
                ? 'text-primary border-b-2 border-primary'
                : 'text-muted-foreground hover:text-foreground'
            }`}
          >
            <div className="flex items-center gap-2">
              <Baby className="w-4 h-4" />
              <span>Pediátrico</span>
            </div>
          </button>
        </div>
      </div>

      {/* Main Content */}
      {selectedProtocol ? (
        <div className="space-y-6 lg:grid lg:grid-cols-[1fr_280px] lg:gap-6 lg:items-start">
          {/* Main Column */}
          <div className="space-y-6">
            {/* Protocol Card */}
            <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">{protocolTitle}</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>

              {/* Checklist Toggle Button */}
              <button
                onClick={handleToggleChecklist}
                className={`w-full flex items-center justify-center gap-2 px-4 py-3 rounded-lg font-medium transition-colors ${
                  isChecklistMode
                    ? 'bg-green-500/20 text-green-600 dark:text-green-400 border-2 border-green-500/50'
                    : 'bg-muted hover:bg-accent text-foreground border border-border'
                }`}
              >
                <span className="text-lg">🟢</span>
                <span>{isChecklistMode ? 'Modo Checklist Activo' : 'Modo Checklist'}</span>
              </button>

              {/* Content Area */}
              {isChecklistMode ? (
                <div className="space-y-3">
                  <div className="flex items-center justify-between mb-4">
                    <h3 className="font-semibold text-foreground flex items-center gap-2">
                      <Check className="w-5 h-5 text-green-500" />
                      Checklist RCP - Marca los pasos completados
                    </h3>
                    {checkedItems.size > 0 && (
                      <button
                        onClick={() => setCheckedItems(new Set())}
                        className="flex items-center gap-2 px-3 py-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors"
                      >
                        <RotateCcw className="w-4 h-4" />
                        Reiniciar
                      </button>
                    )}
                  </div>
                  <div className="space-y-2">
                    {rcpChecklistSteps.map((step, index) => {
                      const isChecked = checkedItems.has(index);
                      return (
                        <button
                          key={index}
                          onClick={() => handleStepToggle(index)}
                          className={`w-full flex items-center gap-4 p-4 rounded-lg border-2 transition-all text-left ${
                            isChecked
                              ? 'bg-green-500/10 border-green-500/50'
                              : 'bg-muted border-border hover:border-primary/50'
                          }`}
                        >
                          <div
                            className={`w-12 h-12 rounded-lg border-2 flex items-center justify-center flex-shrink-0 transition-colors ${
                              isChecked
                                ? 'bg-green-500 border-green-500'
                                : 'bg-card border-muted-foreground'
                            }`}
                          >
                            {isChecked ? (
                              <Check className="w-6 h-6 text-white" />
                            ) : (
                              <span className="text-muted-foreground font-bold text-lg">{index + 1}</span>
                            )}
                          </div>
                          <span
                            className={`flex-1 font-medium ${
                              isChecked ? 'text-foreground line-through opacity-60' : 'text-foreground'
                            }`}
                          >
                            {step}
                          </span>
                        </button>
                      );
                    })}
                  </div>
                  <div className="mt-4 p-3 bg-muted/50 rounded-lg text-center">
                    <p className="text-sm text-muted-foreground">
                      {checkedItems.size} de {rcpChecklistSteps.length} pasos completados
                    </p>
                  </div>
                </div>
              ) : (
                <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">
                    {selectedProtocol.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>
              )}

              {/* Warnings */}
              {selectedProtocol.warnings && selectedProtocol.warnings.length > 0 && (
                <div>
                  <h3 className="font-semibold text-foreground mb-2 flex items-center gap-2">
                    <AlertTriangle className="w-4 h-4 text-orange-500" />
                    Advertencias Importantes
                  </h3>
                  <ul className="space-y-1">
                    {selectedProtocol.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>
              )}

              {/* Key Points */}
              {selectedProtocol.keyPoints && selectedProtocol.keyPoints.length > 0 && (
                <div>
                  <h3 className="font-semibold text-foreground mb-2">Puntos Clave</h3>
                  <ul className="space-y-1">
                    {selectedProtocol.keyPoints.map((point, index) => (
                      <li key={index} className="text-sm text-muted-foreground flex items-start gap-2">
                        <span className="text-primary mt-1">✓</span>
                        <span>{point}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              )}

              {/* Equipment */}
              {selectedProtocol.equipment && selectedProtocol.equipment.length > 0 && (
                <div>
                  <h3 className="font-semibold text-foreground mb-2">Material Necesario</h3>
                  <div className="flex flex-wrap gap-2">
                    {selectedProtocol.equipment.map((item, index) => (
                      <span
                        key={index}
                        className="px-3 py-1 bg-muted rounded-full text-sm text-foreground"
                      >
                        {item}
                      </span>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Sidebar - Desktop Only */}
          <div className="hidden lg:block space-y-4 lg:sticky lg:top-20">
            {/* Related Protocols */}
            <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="/via-aerea"
                  className="flex items-center justify-between p-3 bg-card rounded-lg hover:bg-accent transition-colors"
                >
                  <span className="text-foreground">Vía Aérea / OVACE</span>
                  <ChevronRight className="w-5 h-5 text-muted-foreground" />
                </Link>
                <Link
                  to="/soporte-vital"
                  className="flex items-center justify-between p-3 bg-card rounded-lg hover:bg-accent transition-colors"
                >
                  <span className="text-foreground">Ver todos los protocolos de Soporte Vital</span>
                  <ChevronRight className="w-5 h-5 text-muted-foreground" />
                </Link>
              </div>
            </div>

            {/* Related Content */}
            <div className="bg-card border border-border rounded-xl p-4 space-y-3">
              <h3 className="font-semibold text-foreground mb-2">Contenido Relacionado</h3>
              <div className="space-y-2">
                <Link
                  to="/guia-refuerzo"
                  className="flex items-center gap-2 px-3 py-2 bg-blue-500/10 hover:bg-blue-500/20 border border-blue-500/30 rounded-lg text-blue-600 dark:text-blue-400 transition-colors text-sm"
                >
                  <GraduationCap className="w-4 h-4 flex-shrink-0" />
                  <span className="text-xs">Guía Formativa</span>
                </Link>
                <Link
                  to="/manual"
                  className="flex items-center gap-2 px-3 py-2 bg-purple-500/10 hover:bg-purple-500/20 border border-purple-500/30 rounded-lg text-purple-600 dark:text-purple-400 transition-colors text-sm"
                >
                  <BookOpen className="w-4 h-4 flex-shrink-0" />
                  <span className="text-xs">Manual Completo</span>
                </Link>
              </div>
            </div>
          </div>

          {/* Related Protocols - Mobile/Tablet */}
          <div className="lg:hidden 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="/via-aerea"
                className="flex items-center justify-between p-3 bg-card rounded-lg hover:bg-accent transition-colors"
              >
                <span className="text-foreground">Vía Aérea / OVACE</span>
                <ChevronRight className="w-5 h-5 text-muted-foreground" />
              </Link>
              <Link
                to="/soporte-vital"
                className="flex items-center justify-between p-3 bg-card rounded-lg hover:bg-accent transition-colors"
              >
                <span className="text-foreground">Ver todos los protocolos de Soporte Vital</span>
                <ChevronRight className="w-5 h-5 text-muted-foreground" />
              </Link>
            </div>
          </div>
        </div>
      ) : (
        <NotFound message="Protocolo no encontrado" backTo="/" />
      )}

      {/* Pediatric Content */}
      {activeTab === 'pediatrico' && selectedProtocol && (
        <div className="space-y-6">
          <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">RCP Pediátrico</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">
              <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">
                {selectedProtocol.steps.map((step, index) => (
                  <li key={index} className="text-foreground pl-2">
                    {step.instruction}
                  </li>
                ))}
              </ol>
            </div>
          </div>
          
          {/* Related Links */}
          <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="/via-aerea"
                className="flex items-center justify-between p-3 bg-card rounded-lg hover:bg-accent transition-colors"
              >
                <span className="text-foreground">OVACE Pediátrico</span>
                <ChevronRight className="w-5 h-5 text-muted-foreground" />
              </Link>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default RCP;
