import { useEffect, useState } from 'react';
import { publicAuthService } from '../services/authService';
import { useNavigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import type { Listing } from '../types';
import {
  User, Package, Settings, ChevronRight,
  Clock, Eye, ShieldCheck, QrCode, Lock,
  Bell, RefreshCcw
} from 'lucide-react';
import { usePublicAuthStore } from '../store/publicAuthStore';
import api from '../services/api';
import LazyImage from '../components/LazyImage';
import { useWizardStore } from '../store/wizardStore';
import clsx from 'clsx';

interface MfaData {
  qrCodeUri: string;
  secret: string;
}

type TabType = 'listings' | 'security' | 'settings';

export default function ProfilePage() {
  const { user, logout } = usePublicAuthStore();
  const [activeTab, setActiveTab] = useState<TabType>('listings');
  const [listings, setListings] = useState<Listing[]>([]);
  const [loading, setLoading] = useState(true);
  const [mfaSetupData, setMfaSetupData] = useState<MfaData | null>(null);
  const [mfaCode, setMfaCode] = useState('');
  const baseUrl = import.meta.env.VITE_BASE_URL;
  const setRepublishData = useWizardStore(state => state.setRepublishData);
  const [republishTarget, setRepublishTarget] = useState<Listing | null>(null);
  const navigate = useNavigate();

  useEffect(() => {
    if (!user) {
      navigate('/login');
      return;
    }
    loadMyData();
  }, [navigate, user]);

  const handleConfirmRepublish = async () => {
    if (!republishTarget) return;
    try {
      // Buscamos el detalle técnico (Modelo, KM, Puertas, etc.)
      const res = await api.get(`/listings/${republishTarget.id}`);

      // Cargamos el Store con toda la data
      setRepublishData(res.data);

      // Navegamos al Wizard
      navigate('/publicar');
    } catch (error) {
      alert("Error al recuperar datos técnicos del aviso");
    } finally {
      setRepublishTarget(null);
    }
  };

  const loadMyData = async () => {
    try {
      const response = await api.get('/listings/my');
      setListings(response.data);
    } catch (error) {
      console.error("Error al cargar datos del perfil", error);
    } finally {
      setLoading(false);
    }
  };

  const handleSetupMfa = async () => {
    try {
      const data = await publicAuthService.setupMfa();
      setMfaSetupData(data);
    } catch (error) {
      console.error("Error al configurar MFA", error);
    }
  };

  const handleVerifyAndEnableMfa = async () => {
    if (mfaCode.length !== 6) return;
    try {
      const res = await publicAuthService.verifyMfa(mfaCode);
      if (res.success) {
        alert("¡MFA activado con éxito!");
        setMfaSetupData(null);
        setMfaCode('');
      }
    } catch (error) {
      alert("Error al verificar código.");
    }
  };

  const handleUpdateOverlay = async (id: number, status: string | null) => {
    try {
      await api.patch(`/listings/${id}/overlay`, JSON.stringify(status), {
        headers: { 'Content-Type': 'application/json' }
      });
      loadMyData();
    } catch (error) {
      alert("Error al actualizar estado");
    }
  };

  if (loading) return (
    <div className="min-h-screen flex items-center justify-center bg-slate-50">
      <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
    </div>
  );

  return (
    <div className="min-h-screen bg-[#f8fafc] font-sans">

      {/* 1. HEADER REFINADO (Más bajo y elegante) */}
      <div className="bg-[#0f172a] relative overflow-hidden pt-12 pb-20">
        {/* Luces de fondo más tenues */}
        <div className="absolute top-0 right-0 w-[400px] h-[400px] bg-blue-500/5 rounded-full blur-[100px]"></div>
        <div className="absolute bottom-0 left-1/4 w-[300px] h-[300px] bg-indigo-500/5 rounded-full blur-[80px]"></div>

        <div className="max-w-6xl mx-auto px-6 relative z-10">
          <div className="flex flex-col md:flex-row items-end gap-8">

            {/* Avatar más integrado */}
            <div className="relative">
              <div className="w-24 h-24 bg-white rounded-[2rem] flex items-center justify-center shadow-2xl border border-white/10 relative z-10">
                <User size={40} className="text-slate-900" />
              </div>
              <div className="absolute z-20 -bottom-2 -right-2 bg-emerald-500 w-8 h-8 rounded-full border-4 border-[#0f172a] flex items-center justify-center text-white shadow-lg">
                <ShieldCheck size={14} />
              </div>
            </div>

            <div className="text-center md:text-left flex-1 pb-2">
              <div className="flex items-center justify-center md:justify-start gap-4 mb-3">
                <h1 className="text-3xl font-black text-white tracking-tighter uppercase leading-none">
                  {user?.username}
                </h1>
                <span className="bg-blue-500/10 text-blue-400 px-3 py-1.5 rounded-xl text-[9px] font-black uppercase tracking-[0.2em] border border-blue-500/20">
                  Verificado
                </span>
              </div>

              <div className="flex items-center justify-center md:justify-start gap-6 text-slate-400">
                <div className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest">
                  <Package size={14} className="text-blue-500" />
                  {listings.filter(l => l.status === 'Published').length} ACTIVAS
                </div>
                <div className="w-1 h-1 bg-slate-800 rounded-full"></div>
                <div className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest">
                  <Clock size={14} className="text-slate-600" />
                  Miembro desde 2025
                </div>
              </div>
            </div>

            <div className="flex gap-3 pb-2">
              <button className="bg-white/5 hover:bg-white/10 text-white p-3 rounded-2xl border border-white/10 transition-all">
                <Bell size={20} />
              </button>
              <button
                onClick={() => { logout(); navigate('/'); }}
                className="bg-rose-500/10 hover:bg-rose-500 text-rose-500 hover:text-white px-6 py-3 rounded-2xl border border-rose-500/20 transition-all text-[10px] font-black uppercase tracking-widest"
              >
                Cerrar Sesión
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 2. CONTENIDO (Sidebar + Main) */}
      <div className="max-w-6xl mx-auto px-6 -mt-8 relative z-20">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">

          {/* SIDEBAR MÁS ESTILIZADO */}
          <aside className="lg:col-span-3">
            <div className="bg-white/80 backdrop-blur-xl rounded-[2.5rem] p-3 shadow-2xl shadow-slate-200/50 border border-white sticky top-24">
              <nav className="space-y-1">
                <SidebarItem
                  icon={<Package size={18} />}
                  label="Publicaciones"
                  active={activeTab === 'listings'}
                  onClick={() => setActiveTab('listings')}
                />
                <SidebarItem
                  icon={<Lock size={18} />}
                  label="Seguridad"
                  active={activeTab === 'security'}
                  onClick={() => setActiveTab('security')}
                />
                <SidebarItem
                  icon={<Settings size={18} />}
                  label="Ajustes"
                  active={activeTab === 'settings'}
                  onClick={() => setActiveTab('settings')}
                />
              </nav>
            </div>
          </aside>

          {/* CONTENIDO DINÁMICO */}
          <main className="lg:col-span-9">
            <div className="bg-white rounded-[3rem] p-10 shadow-2xl shadow-slate-200/60 border border-slate-100 min-h-[550px]">
              <AnimatePresence mode="wait">
                {activeTab === 'listings' && (
                  <motion.div key="listings" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }}>
                    <h2 className="text-2xl font-black text-slate-900 mb-8 uppercase tracking-tighter">Historial de anuncios</h2>
                    {listings.length === 0 ? (
                      <div className="flex flex-col items-center justify-center py-20 opacity-30">
                        <Package size={64} className="mb-4" />
                        <p className="font-black uppercase tracking-widest text-xs">Sin actividad reciente</p>
                      </div>
                    ) : (
                      <div className="space-y-6">
                        {listings.map(item => (
                          <div key={item.id} className="flex flex-col p-6 bg-slate-50 hover:bg-white hover:shadow-xl rounded-[2.5rem] transition-all border border-transparent hover:border-slate-100 group">
                            <div className="flex gap-6 items-start">
                              {/* Contenedor de imagen con tamaño fijo y aspecto cuadrado */}
                              <div className="w-24 h-24 bg-white rounded-3xl overflow-hidden flex-shrink-0 relative border border-slate-100 shadow-sm">
                                {item.mainImageUrl ? (
                                  <LazyImage
                                    src={`${baseUrl}${item.mainImageUrl}`}
                                    alt={item.title}
                                    className="w-full h-full"
                                  />
                                ) : (
                                  <div className="w-full h-full flex items-center justify-center text-slate-200 bg-slate-50">
                                    <Package size={32} />
                                  </div>
                                )}
                              </div>

                              <div className="flex-1 flex flex-col min-h-[96px] justify-between">
                                <div className="flex justify-between items-start">
                                  <div>
                                    <h4 className="font-black text-slate-900 leading-tight group-hover:text-blue-600 transition-colors uppercase text-sm">
                                      {item.title}
                                    </h4>
                                    <div className="flex gap-4 mt-2">
                                      <span className="text-[10px] font-bold text-slate-400 flex items-center gap-1 uppercase">
                                        <Clock size={12} /> {new Date(item.createdAt).toLocaleDateString()}
                                      </span>
                                      <span className="text-[10px] font-bold text-slate-400 flex items-center gap-1 uppercase">
                                        <Eye size={12} /> {item.viewCount} vistas
                                      </span>
                                    </div>
                                  </div>
                                  <div className="text-right">
                                    <p className="font-black text-slate-900 text-lg">${item.price.toLocaleString()}</p>

                                    {/* BADGE DINÁMICO DE ESTADO */}
                                    <span className={clsx(
                                      "text-[9px] font-black uppercase px-2 py-1 rounded-lg border shadow-sm inline-block mt-1",
                                      // Estilos para Publicado
                                      item.status === 'Published' && "text-emerald-500 bg-emerald-50 border-emerald-100",
                                      // Estilos para Pendiente de Moderación (Naranja)
                                      item.status === 'Pending' && "text-amber-500 bg-amber-50 border-amber-100",
                                      // Estilos para Borrador o Error (Gris)
                                      (item.status === 'Draft' || !item.status) && "text-slate-400 bg-slate-50 border-slate-200"
                                    )}>
                                      {item.status === 'Published' ? 'Publicado' :
                                        item.status === 'Pending' ? 'En Revisión' :
                                          'Borrador'}
                                    </span>
                                  </div>
                                </div>
                              </div>
                            </div>

                            {/* PANEL DE GESTIÓN */}
                            <div className="flex items-center justify-between mt-4 pt-4 border-t border-slate-100">
                              <div className="flex gap-2">
                                {['Vendido', 'Reservado', 'Alquilado'].map(status => (
                                  <button
                                    key={status}
                                    onClick={() => handleUpdateOverlay(item.id, item.overlayStatus === status ? null : status)}
                                    className={clsx(
                                      "px-3 py-1.5 rounded-xl text-[9px] font-black uppercase transition-all border",
                                      item.overlayStatus === status
                                        ? "bg-slate-900 text-white border-slate-900 shadow-lg scale-105"
                                        : "bg-white text-slate-400 border-slate-200 hover:border-slate-400"
                                    )}
                                  >
                                    {status}
                                  </button>
                                ))}
                              </div>

                              <button
                                onClick={() => setRepublishTarget(item)}
                                className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-xl text-[9px] font-black uppercase shadow-lg shadow-blue-200 hover:bg-blue-700 transition-all active:scale-95"
                              >
                                <RefreshCcw size={12} /> Republicar aviso
                              </button>
                            </div>

                          </div>
                        ))}
                      </div>
                    )}
                  </motion.div>
                )}

                {/* TAB: SEGURIDAD / MFA */}
                {activeTab === 'security' && (
                  <motion.div key="security" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }}>
                    <h2 className="text-2xl font-black text-slate-900 mb-2 uppercase tracking-tighter">Protección de Cuenta</h2>
                    <p className="text-slate-500 text-sm mb-10">Gestiona la seguridad de tu acceso y la verificación en dos pasos.</p>

                    <div className="space-y-6">
                      {/* Card MFA */}
                      <div className="p-8 rounded-[2rem] bg-slate-50 border border-slate-100 relative overflow-hidden">
                        <div className="flex flex-col md:flex-row gap-8 items-start relative z-10">
                          <div className="bg-white p-4 rounded-3xl shadow-sm border border-slate-100">
                            <QrCode size={40} className="text-blue-600" />
                          </div>
                          <div className="flex-1">
                            <h4 className="font-black text-slate-900 uppercase text-base mb-1">Doble Factor de Autenticación (TOTP)</h4>
                            <p className="text-slate-500 text-xs leading-relaxed mb-6">Añade una capa extra de seguridad usando Google Authenticator o similares.</p>

                            {!mfaSetupData ? (
                              <button
                                onClick={handleSetupMfa}
                                className="bg-slate-900 text-white px-8 py-3 rounded-xl font-black uppercase text-[10px] tracking-widest hover:bg-blue-600 transition-all shadow-lg shadow-slate-200"
                              >
                                Configurar MFA ahora
                              </button>
                            ) : (
                              <div className="bg-white p-6 rounded-3xl border border-blue-100 animate-in fade-in slide-in-from-bottom-2">
                                <p className="text-[10px] font-black text-blue-600 uppercase mb-4 text-center">1. Escanea este código</p>
                                <div className="bg-white p-4 rounded-2xl w-fit mx-auto border border-slate-100 mb-6">
                                  <img
                                    src={`https://api.qrserver.com/v1/create-qr-code/?size=160x160&data=${encodeURIComponent(mfaSetupData.qrCodeUri)}`}
                                    alt="QR"
                                  />
                                </div>
                                <p className="text-[10px] font-black text-slate-400 uppercase mb-3 text-center">2. Introduce el código de 6 dígitos</p>
                                <div className="flex gap-3 max-w-xs mx-auto">
                                  <input
                                    type="text"
                                    maxLength={6}
                                    value={mfaCode}
                                    onChange={(e) => setMfaCode(e.target.value)}
                                    placeholder="000000"
                                    className="flex-1 bg-slate-50 border-none rounded-xl text-center font-mono font-bold text-xl py-3 focus:ring-2 focus:ring-blue-500 transition-all"
                                  />
                                  <button
                                    onClick={handleVerifyAndEnableMfa}
                                    className="bg-blue-600 text-white px-6 rounded-xl font-black uppercase text-[10px] hover:bg-blue-700"
                                  >
                                    Activar
                                  </button>
                                </div>
                              </div>
                            )}
                          </div>
                        </div>
                      </div>

                      {/* Card Password Change */}
                      <div className="p-8 rounded-[2rem] border border-slate-100 flex items-center justify-between group hover:bg-slate-50 transition-colors cursor-pointer">
                        <div className="flex items-center gap-6">
                          <div className="p-3 bg-slate-100 rounded-2xl text-slate-400 group-hover:text-slate-900 group-hover:bg-white transition-all shadow-sm">
                            <Lock size={20} />
                          </div>
                          <div>
                            <h4 className="font-black text-slate-900 uppercase text-sm">Cambiar Contraseña</h4>
                            <p className="text-slate-400 text-[10px] font-bold uppercase tracking-widest mt-1">Último cambio: Hace 3 meses</p>
                          </div>
                        </div>
                        <ChevronRight size={20} className="text-slate-300 group-hover:text-slate-900 transition-all" />
                      </div>
                    </div>
                  </motion.div>
                )}

                {/* TAB: AJUSTES */}
                {activeTab === 'settings' && (
                  <motion.div key="settings" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }}>
                    <h2 className="text-2xl font-black text-slate-900 mb-8 uppercase tracking-tighter">Ajustes de cuenta</h2>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      <InputGroup label="Nombre de usuario" value={user?.username || ''} disabled />
                      <InputGroup label="Email de contacto" value={user?.email || 'admin@sigcm.com'} />
                      <InputGroup label="Teléfono / WhatsApp" placeholder="+54..." />
                      <InputGroup label="Ubicación" value="La Plata, Buenos Aires" />
                    </div>
                    <div className="mt-10 pt-10 border-t border-slate-50 flex justify-end">
                      <button className="bg-blue-600 text-white px-10 py-4 rounded-2xl font-black uppercase text-xs tracking-widest shadow-xl shadow-blue-200 hover:bg-blue-700 transition-all">
                        Guardar cambios
                      </button>
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>

            </div>
          </main>
        </div>
      </div >
      {/* MODAL DE CONFIRMACIÓN */}
      <AnimatePresence>
        {republishTarget && (
          <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
            <motion.div
              initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
              onClick={() => setRepublishTarget(null)}
              className="absolute inset-0 bg-slate-900/60 backdrop-blur-sm"
            />
            <motion.div
              initial={{ scale: 0.9, opacity: 0, y: 20 }}
              animate={{ scale: 1, opacity: 1, y: 0 }}
              exit={{ scale: 0.9, opacity: 0, y: 20 }}
              className="relative bg-white p-8 rounded-[2.5rem] shadow-2xl max-w-sm w-full text-center border border-slate-100"
            >
              <div className="w-16 h-16 bg-blue-50 text-blue-600 rounded-2xl flex items-center justify-center mx-auto mb-6">
                <RefreshCcw size={32} />
              </div>
              <h3 className="text-xl font-black text-slate-900 uppercase tracking-tighter mb-3">Republicar Aviso</h3>
              <p className="text-sm text-slate-500 font-medium mb-8 leading-relaxed">
                Se creará una nueva publicación basada en <strong>{republishTarget.title}</strong>. Podrás editar los datos antes de realizar el pago.
              </p>
              <div className="flex gap-3">
                <button
                  onClick={() => setRepublishTarget(null)}
                  className="flex-1 py-4 px-6 bg-slate-100 text-slate-500 font-black uppercase text-[10px] tracking-widest rounded-2xl hover:bg-slate-200 transition-all"
                >
                  Cancelar
                </button>
                <button
                  onClick={handleConfirmRepublish}
                  className="flex-1 py-4 px-6 bg-blue-600 text-white font-black uppercase text-[10px] tracking-widest rounded-2xl shadow-lg shadow-blue-200 hover:bg-blue-700 transition-all"
                >
                  Confirmar
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </div >
  );
}

// COMPONENTES AUXILIARES PARA LIMPIEZA
function SidebarItem({ icon, label, active, onClick }: { icon: any, label: string, active: boolean, onClick: () => void }) {
  return (
    <button
      onClick={onClick}
      className={`w-full flex items-center gap-3 px-5 py-4 rounded-[1.5rem] transition-all duration-300 font-bold text-[11px] uppercase tracking-[0.15em] ${active
        ? 'bg-blue-600 text-white shadow-xl shadow-blue-200'
        : 'text-slate-400 hover:text-slate-900 hover:bg-slate-50'
        }`}
    >
      <span className={active ? 'text-white' : 'text-slate-300 group-hover:text-slate-600'}>
        {icon}
      </span>
      {label}
    </button>
  );
}

function InputGroup({ label, value, disabled, placeholder }: any) {
  return (
    <div className="space-y-2">
      <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">{label}</label>
      <input
        type="text"
        defaultValue={value}
        disabled={disabled}
        placeholder={placeholder}
        className={`w-full px-6 py-4 bg-slate-50 border-none rounded-2xl focus:ring-2 focus:ring-blue-100 outline-none transition-all font-bold text-slate-700 ${disabled ? 'opacity-50 cursor-not-allowed' : 'hover:bg-slate-100'
          }`}
      />
    </div>
  );
}