import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import {
  Phone,
  RotateCcw,
} from 'lucide-react';

// 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">
    <span>⚠️</span>
    <span>{label}</span>
  </Link>
);

// Mock Badge component
const Badge = ({ variant, children }: { variant: string; children: React.ReactNode }) => (
  <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${variant === 'default' ? 'bg-muted text-muted-foreground' : ''}`}>
    {children}
  </span>
);

// Mock TelephoneProtocolViewer (we'll show the protocol details directly)
const TelephoneProtocolViewer = ({ protocol, onReset }: { protocol: any; onReset: () => void }) => (
  <div className="space-y-6">
    <button onClick={onReset} className="mb-4 text-sm text-muted-foreground hover:text-foreground flex items-center gap-2">
      ← Volver a lista de protocolos
    </button>
    
    <div className="bg-card border border-border rounded-lg p-6">
      <h2 className="text-xl font-semibold text-foreground mb-4">{protocol.title}</h2>
      <p className="text-muted-foreground">
        {protocol.shortTitle} • {protocol.category} • {protocol.ageGroup}
      </p>
      
      <div className="space-y-4">
        <h3 className="font-semibold text-foreground mb-2">Descripción</h3>
        <p>{protocol.description}</p>
      </div>
      
      <div className="space-y-4">
        <h3 className="font-semibold text-foreground mb-2">Evaluación Inicial</h3>
        <ol className="space-y-2 list-decimal list-inside">
          {protocol.initialAssessment.map((step: string, index: number) => (
            <li key={index} className="text-foreground pl-2">
              {step}
            </li>
          ))}
        </ol>
      </div>
      
      <div className="space-y-4">
        <h3 className="font-semibold text-foreground mb-2">Pasos del Protocolo</h3>
        <ol className="space-y-2 list-decimal list-inside">
          {protocol.steps.map((step: any, index: number) => (
            <li key={index} className="text-foreground pl-2">
              {step.instruction}
            </li>
          ))}
        </ol>
      </div>
    </div>
  </div>
);

// Interfaces (mismas que el backend)
interface TelephoneProtocolStep {
  id: string;
  order: number;
  instruction: string;
  verification?: string;
  notes?: string;
  critical?: boolean;
}

interface TelephoneProtocol {
  id: string;
  title: string;
  shortTitle: string;
  category: string;
  ageGroup: string;
  description: string;
  initialAssessment: string[];
  steps: TelephoneProtocolStep[];
  importantNotes?: string[];
  source?: string;
}

const categoryLabels: Record<string, string> = {
  rcp: 'RCP',
  desa: 'DESA',
  ovace: 'OVACE',
  sca: 'SCA',
  ictus: 'Ictus',
  comunicacion: 'Comunicación',
};

const ageGroupLabels: Record<string, string> = {
  adulto: 'Adulto',
  pediatrico: 'Pediatría',
  lactante: 'Lactante',
  todos: 'Todos',
};

const Telefono = () => {
  const [protocols, setProtocols] = useState<TelephoneProtocol[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedProtocol, setSelectedProtocol] = useState<TelephoneProtocol | null>(null);
  const [selectedCategory, setSelectedCategory] = useState<string | 'todos'>('todos');
  const [selectedAgeGroup, setSelectedAgeGroup] = useState<string | 'todos'>('todos');

  useEffect(() => {
    const fetchProtocols = async () => {
      try {
        const response = await fetch(`${import.meta.env.VITE_API_URL}/content`);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        setProtocols(data.data || []);
        setError(null);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load protocols');
        console.error('Error fetching protocols:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchProtocols();
  }, []);

  const filteredProtocols = protocols.filter((protocol) => {
    const categoryMatch = selectedCategory === 'todos' || protocol.category === selectedCategory;
    const ageMatch = selectedAgeGroup === 'todos' || protocol.ageGroup === selectedAgeGroup || protocol.ageGroup === 'todos';
    return categoryMatch && ageMatch;
  });

  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[200px] space-y-4">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
        <p className="text-muted-foreground">Cargando protocolos...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[200px] space-y-4">
        <p className="text-red-500">Error: {error}</p>
        <button
          onClick={() => {
            setLoading(true);
            setError(null);
          }}
          className="px-4 py-2 bg-primary text-primary-foreground rounded-lg"
        >
          Reintentar
        </button>
      </div>
    );
  }

  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">
          <Phone className="w-8 h-8 text-primary" />
          <div>
            <h1 className="text-3xl font-bold text-foreground">Protocolos Transtelefónicos</h1>
            <p className="text-muted-foreground text-sm">
              Guía paso a paso para testigos por teléfono
            </p>
          </div>
        </div>
      </div>

      {!selectedProtocol ? (
        <>
          {/* Filters */}
          <div className="space-y-4">
            {/* Category Filter */}
            <div className="space-y-2">
              <p className="text-xs text-muted-foreground mb-1 uppercase tracking-wide">Categoría</p>
              <div className="flex gap-2 overflow-x-auto scrollbar-hide -mx-2 px-2">
                <button
                  onClick={() => setSelectedCategory('todos')}
                  className={`px-3 py-1 rounded-full text-sm font-medium whitespace-nowrap transition-colors ${
                    selectedCategory === 'todos'
                      ? 'bg-primary text-primary-foreground'
                      : 'bg-muted text-muted-foreground hover:bg-accent'
                  }`}
                >
                  Todos
                </button>
                {['rcp', 'desa', 'ovace', 'sca', 'ictus', 'comunicacion'].map((category) => (
                  <button
                    key={category}
                    onClick={() => setSelectedCategory(category)}
                    className={`px-3 py-1 rounded-full text-sm font-medium whitespace-nowrap transition-colors ${
                      selectedCategory === category
                        ? 'bg-primary text-primary-foreground'
                        : 'bg-muted text-muted-foreground hover:bg-accent'
                    }`}
                  >
                    {categoryLabels[category]}
                  </button>
                ))}
              </div>
            </div>

            {/* Age Group Filter */}
            <div className="space-y-2">
              <p className="text-xs text-muted-foreground mb-1 uppercase tracking-wide">Grupo Etario</p>
              <div className="flex gap-2 overflow-x-auto scrollbar-hide -mx-2 px-2">
                <button
                  onClick={() => setSelectedAgeGroup('todos')}
                  className={`px-3 py-1 rounded-full text-sm font-medium whitespace-nowrap transition-colors ${
                    selectedAgeGroup === 'todos'
                      ? 'bg-primary text-primary-foreground'
                      : 'bg-muted text-muted-foreground hover:bg-accent'
                  }`}
                >
                  Todos
                </button>
                {['adulto', 'pediatrico', 'lactante'].map((ageGroup) => (
                  <button
                    key={ageGroup}
                    onClick={() => setSelectedAgeGroup(ageGroup)}
                    className={`px-3 py-1 rounded-full text-sm font-medium whitespace-nowrap transition-colors ${
                      selectedAgeGroup === ageGroup
                        ? 'bg-primary text-primary-foreground'
                        : 'bg-muted text-muted-foreground hover:bg-accent'
                    }`}
                  >
                    {ageGroupLabels[ageGroup]}
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* Protocol List */}
          <div className="space-y-3">
            {filteredProtocols.length === 0 ? (
              <p className="text-center text-muted-foreground py-8">No hay protocolos que coincidan con los filtros.</p>
            ) : (
              filteredProtocols.map((protocol) => (
                <div
                  key={protocol.id}
                  onClick={() => setSelectedProtocol(protocol)}
                  className="bg-card border border-border rounded-lg p-4 cursor-pointer hover:border-primary/50 transition-colors"
                >
                  <div className="flex items-start justify-between">
                    <div className="space-y-1">
                      <h3 className="font-semibold text-foreground">{protocol.title}</h3>
                      <p className="text-sm text-muted-foreground">{protocol.description}</p>
                      <div className="flex gap-2 mt-2">
                        <Badge variant="default">{categoryLabels[protocol.category]}</Badge>
                        <Badge variant="default">{ageGroupLabels[protocol.ageGroup]}</Badge>
                      </div>
                    </div>
                    <span className="text-primary">
                      <RotateCcw className="w-5 h-5" />
                    </span>
                  </div>
                </div>
              ))
            )}
          </div>
        </>
      ) : (
        <TelephoneProtocolViewer protocol={selectedProtocol} onReset={() => setSelectedProtocol(null)} />
      )}
    </div>
  );
};

export default Telefono;