'use client';

import { useState, useEffect } from 'react';

interface ModeToggleProps {
  conversationId: number;
  initialMode: 'AI' | 'HUMAN';
  onModeChange: (newMode: 'AI' | 'HUMAN') => void;
}

export function ModeToggle({ conversationId, initialMode, onModeChange }: ModeToggleProps) {
  const [mode, setMode] = useState<'AI' | 'HUMAN'>(initialMode);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setMode(initialMode);
  }, [initialMode]);

  const toggleMode = async () => {
    if (loading) return;

    const newMode = mode === 'AI' ? 'HUMAN' : 'AI';
    setLoading(true);

    try {
      const res = await fetch(`/api/mode/${conversationId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ mode: newMode }),
      });

      if (res.ok) {
        setMode(newMode);
        onModeChange(newMode);
      } else {
        console.error('Error al cambiar el modo');
      }
    } catch (err) {
      console.error('Error en la petición de cambio de modo:', err);
    } finally {
      setLoading(false);
    }
  };

  const isAI = mode === 'AI';

  return (
    <div className="flex items-center gap-2.5 select-none bg-white/[0.02] border border-white/[0.04] pl-3 pr-1.5 py-1.5 rounded-xl">
      {/* Label */}
      <span className={`text-[10px] font-extrabold uppercase tracking-widest transition-colors duration-300 ${isAI ? 'text-emerald-400' : 'text-indigo-400'}`}>
        {isAI ? '🤖 IA' : '👤 Humano'}
      </span>

      {/* Toggle Switch */}
      <button
        onClick={toggleMode}
        disabled={loading}
        className="relative w-11 h-6 rounded-full transition-all duration-300 focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
        style={{
          background: isAI
            ? 'linear-gradient(135deg, #10b981, #059669)'
            : 'linear-gradient(135deg, #8b5cf6, #6366f1)',
          boxShadow: isAI
            ? '0 0 10px rgba(16,185,129,0.2)'
            : '0 0 10px rgba(139,92,246,0.2)',
        }}
        title={isAI ? 'Cambiar a modo Humano' : 'Cambiar a modo IA'}
      >
        {/* Track highlight */}
        <div
          className="absolute inset-0 rounded-full transition-opacity duration-300"
          style={{ background: 'rgba(255,255,255,0.08)', opacity: loading ? 0.5 : 0 }}
        />

        {/* Thumb */}
        <div
          className="absolute top-[3px] w-[18px] h-[18px] rounded-full bg-white shadow-[0_2px_4px_rgba(0,0,0,0.3)] transition-all duration-300 flex items-center justify-center"
          style={{
            left: isAI ? '3px' : 'calc(100% - 21px)',
          }}
        >
          <span className="text-[9px] leading-none select-none">
            {isAI ? '🤖' : '👤'}
          </span>
        </div>
      </button>
    </div>
  );
}
