'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { motion } from 'framer-motion';
import { FiUser, FiMail, FiShield, FiSmartphone, FiLogOut, FiLock, FiMonitor, FiClock, FiTrash2, FiPlay } from 'react-icons/fi';
import Button from '@/components/ui/Button';
import Input from '@/components/ui/Input';
import Badge from '@/components/ui/Badge';
import { useAuthStore } from '@/stores/authStore';
import { useProfileStore } from '@/stores/profileStore';
import { getDeviceIcon, getRoleLabel, formatRelativeTime } from '@/lib/utils';
import toast from 'react-hot-toast';

const mockDevices = [
  { id: 'd1', name: 'Chrome — Windows 11', type: 'web' as const, lastActive: '2024-03-20T10:30:00Z', ip: '192.168.1.100', current: true },
  { id: 'd2', name: 'Safari — iPhone 15', type: 'mobile' as const, lastActive: '2024-03-20T09:15:00Z', ip: '192.168.1.101', current: false },
  { id: 'd3', name: 'Smart TV — Samsung', type: 'tv' as const, lastActive: '2024-03-19T21:45:00Z', ip: '192.168.1.102', current: false },
];

export default function ProfilePage() {
  const router = useRouter();
  const { user, logout } = useAuthStore();
  const { activeProfile, watchProgress, clearProgress } = useProfileStore();

  const [activeTab, setActiveTab] = useState<'profile' | 'history'>('profile');
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [changingPassword, setChangingPassword] = useState(false);

  const historyItems = activeProfile ? watchProgress[activeProfile.id] || [] : [];

  const handleChangePassword = async (e: React.FormEvent) => {
    e.preventDefault();
    if (newPassword !== confirmPassword) {
      toast.error('Las contraseñas no coinciden');
      return;
    }
    if (newPassword.length < 6) {
      toast.error('La contraseña debe tener al menos 6 caracteres');
      return;
    }
    setChangingPassword(true);
    // Simulate API call
    await new Promise(r => setTimeout(r, 1000));
    toast.success('Contraseña actualizada correctamente');
    setCurrentPassword('');
    setNewPassword('');
    setConfirmPassword('');
    setChangingPassword(false);
  };

  const handleLogout = async () => {
    await logout();
    router.push('/login');
  };

  return (
    <div className="max-w-xl mx-auto space-y-6 px-4 py-6">
      
      {/* Page Title */}
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
      >
        <h1 className="text-2xl font-bold text-white flex items-center gap-2">
          👤 Mi Cuenta
        </h1>
      </motion.div>

      {/* Tabs Selector */}
      <div className="flex bg-white/5 border border-white/10 rounded-xl p-1 select-none">
        <button
          onClick={() => setActiveTab('profile')}
          className={`flex-1 py-2 text-xs font-bold uppercase tracking-wider rounded-lg transition-all border-0 cursor-pointer ${
            activeTab === 'profile'
              ? 'bg-primary text-white shadow shadow-primary/20'
              : 'text-white/40 hover:text-white'
          }`}
        >
          👤 Mi Perfil
        </button>
        <button
          onClick={() => setActiveTab('history')}
          className={`flex-1 py-2 text-xs font-bold uppercase tracking-wider rounded-lg transition-all border-0 cursor-pointer ${
            activeTab === 'history'
              ? 'bg-primary text-white shadow shadow-primary/20'
              : 'text-white/40 hover:text-white'
          }`}
        >
          ⏳ Historial
        </button>
      </div>

      {activeTab === 'profile' ? (
        <>
          {/* Membership Card (Tarjeta Cat Tv) */}
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            className="relative overflow-hidden rounded-2xl p-6 text-white shadow-2xl border border-white/10"
            style={{
              background: 'linear-gradient(135deg, rgba(230,0,122,0.85) 0%, rgba(0,223,216,0.85) 100%)',
              backdropFilter: 'blur(20px)'
            }}
          >
            {/* Logo on card */}
            <div className="absolute top-5 right-5">
              <img src="/logo.png" alt="Cat Tv" className="h-9 w-auto object-contain select-none" />
            </div>

            {/* Card Content */}
            <div className="flex flex-col justify-between h-40">
              <div>
                <span className="text-[9px] font-bold tracking-widest uppercase text-white/70 select-none">Tarjeta de Suscripción</span>
                <h2 className="text-xl font-black tracking-wider mt-1 text-white uppercase truncate">{user?.username || 'USUARIO'}</h2>
              </div>

              <div className="grid grid-cols-2 gap-4 mt-auto">
                <div>
                  <p className="text-[9px] text-white/60 font-semibold tracking-wider uppercase select-none">Estado</p>
                  <div className="flex items-center gap-1.5 mt-0.5 select-none">
                    <span className="w-2 h-2 rounded-full bg-green-400 animate-pulse" />
                    <span className="text-xs font-bold uppercase tracking-wider">Activo</span>
                  </div>
                </div>
                <div>
                  <p className="text-[9px] text-white/60 font-semibold tracking-wider uppercase select-none">Vencimiento</p>
                  <p className="text-xs font-bold mt-0.5 tracking-wide">
                    {user?.expiresAt 
                      ? new Date(user.expiresAt).toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit', year: 'numeric' })
                      : 'Ilimitado / Por siempre'}
                  </p>
                </div>
              </div>
            </div>
          </motion.div>

          {/* Devices list (Connected devices) */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.15 }}
            className="glass-card p-6 rounded-xl"
          >
            <div className="flex items-center justify-between mb-4 select-none">
              <h3 className="text-base font-bold text-white flex items-center gap-2">
                <FiMonitor size={18} className="text-accent" />
                Dispositivos Conectados
              </h3>
              <Badge variant="neutral" size="sm">
                {user?.connectedDevices || 1} / {user?.maxDevices || 3}
              </Badge>
            </div>

            <div className="space-y-3">
              {mockDevices.map((device) => (
                <div
                  key={device.id}
                  className="flex items-center justify-between p-3 bg-white/5 rounded-lg hover:bg-white/[0.08] transition-colors"
                >
                  <div className="flex items-center gap-3">
                    <span className="text-xl select-none">{getDeviceIcon(device.type)}</span>
                    <div>
                      <p className="text-xs text-white font-medium flex items-center gap-2">
                        {device.name}
                        {device.current && <Badge variant="success" size="sm">Actual</Badge>}
                      </p>
                      <p className="text-[10px] text-white/40 mt-0.5">
                        IP: {device.ip} · Activo {formatRelativeTime(device.lastActive)}
                      </p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </motion.div>
        </>
      ) : (
        /* Render Watch History list */
        <motion.div
          initial={{ opacity: 0, y: 15 }}
          animate={{ opacity: 1, y: 0 }}
          className="glass-card p-6 rounded-xl space-y-4"
        >
          <div className="flex items-center justify-between select-none">
            <h3 className="text-base font-bold text-white flex items-center gap-2">
              <FiClock size={18} className="text-accent" />
              Historial de Reproducción
            </h3>
            {historyItems.length > 0 && (
              <Button
                variant="secondary"
                size="sm"
                icon={<FiTrash2 size={12} />}
                onClick={() => {
                  if (confirm('¿Deseas borrar todo tu historial de reproducción?')) {
                    clearProgress();
                    toast.success('Historial borrado');
                  }
                }}
              >
                Limpiar Todo
              </Button>
            )}
          </div>

          {historyItems.length === 0 ? (
            <p className="text-xs text-white/30 text-center py-8 italic select-none">
              No tienes contenido reproducido recientemente.
            </p>
          ) : (
            <div className="space-y-3 max-h-[400px] overflow-y-auto pr-1 scrollbar-thin scrollbar-thumb-white/10">
              {historyItems.map((item) => {
                const progressPct = item.duration > 0 ? (item.currentTime / item.duration) * 100 : 0;
                const href = item.type === 'series' 
                  ? `/series/${item.seriesId || item.contentId}`
                  : `/movies/${item.contentId}`;

                return (
                  <div
                    key={item.contentId}
                    className="flex items-center justify-between p-3 bg-white/5 rounded-lg border border-white/5 hover:bg-white/[0.08] transition-all"
                  >
                    <div className="flex items-center gap-3 min-w-0">
                      {/* Thumbnail/Poster */}
                      <div className="w-10 h-14 bg-black/40 rounded overflow-hidden flex-shrink-0 relative border border-white/5">
                        {item.logoUrl ? (
                          <img src={item.logoUrl} alt="" className="w-full h-full object-cover animate-fade-in" />
                        ) : (
                          <div className="w-full h-full flex items-center justify-center text-white/20 text-[9px] font-bold uppercase">Poster</div>
                        )}
                      </div>
                      
                      <div className="min-w-0">
                        <p className="text-xs font-bold text-white truncate max-w-[200px] sm:max-w-xs">{item.title}</p>
                        <p className="text-[10px] text-white/40 mt-0.5">
                          Restan {Math.max(Math.ceil((item.duration - item.currentTime) / 60), 0)} min
                        </p>
                        
                        {/* Progress Bar */}
                        <div className="w-32 h-1 bg-white/10 rounded-full mt-2 overflow-hidden">
                          <div className="h-full bg-primary" style={{ width: `${progressPct}%` }} />
                        </div>
                      </div>
                    </div>

                    {/* Action buttons */}
                    <div className="flex items-center gap-1">
                      <button
                        onClick={() => router.push(href)}
                        className="p-2 rounded-lg bg-white/5 text-white/60 hover:text-white hover:bg-primary transition-all cursor-pointer border-0 flex items-center justify-center"
                        title="Ver de nuevo"
                      >
                        <FiPlay size={13} className="fill-current" />
                      </button>
                      <button
                        onClick={() => {
                          const updatedProgress = { ...watchProgress };
                          const currentProfileId = activeProfile!.id;
                          updatedProgress[currentProfileId] = updatedProgress[currentProfileId].filter(
                            (p: any) => p.contentId !== item.contentId
                          );
                          useProfileStore.setState({ watchProgress: updatedProgress });
                          toast.success('Elemento eliminado del historial');
                        }}
                        className="p-2 rounded-lg bg-white/5 text-white/40 hover:text-red-500 hover:bg-white/10 transition-all cursor-pointer border-0 flex items-center justify-center"
                        title="Eliminar"
                      >
                        <FiTrash2 size={13} />
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </motion.div>
      )}

      {/* Logout button */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.25 }}
      >
        <Button
          variant="danger"
          size="lg"
          icon={<FiLogOut size={20} />}
          onClick={handleLogout}
          fullWidth
        >
          Cerrar Sesión
        </Button>
      </motion.div>

    </div>
  );
}
