'use client';

import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useProfileStore, PROFILE_AVATAR_GRADIENTS, PROFILE_AVATAR_EMOJIS, Profile } from '@/stores/profileStore';
import { FiPlus, FiTrash2, FiEdit2, FiCheck, FiX } from 'react-icons/fi';
import Button from '@/components/ui/Button';
import { cn } from '@/lib/utils';
import toast from 'react-hot-toast';

const PRESET_AVATARS = [
  { name: 'Ninja', url: '/avatars/avatar_ninja.png' },
  { name: 'Robot', url: '/avatars/avatar_robot.png' },
  { name: 'Superhero', url: '/avatars/avatar_superhero.png' },
  { name: 'Astronaut', url: '/avatars/avatar_astronaut.png' },
  { name: 'Gamer', url: '/avatars/avatar_gamer.png' },
  { name: 'Unicorn', url: '/avatars/avatar_unicorn.png' },
];

export default function ProfileSelection() {
  const { profiles, selectProfile, addProfile, deleteProfile } = useProfileStore();
  const [isManaging, setIsManaging] = useState(false);
  const [isCreating, setIsCreating] = useState(false);
  const [selectedProfileId, setSelectedProfileId] = useState<string | null>(null);

  const playTudumSound = () => {
    if (typeof window === 'undefined') return;
    try {
      const AudioContext = window.AudioContext || (window as any).webkitAudioContext;
      if (!AudioContext) return;
      const ctx = new AudioContext();

      // Low frequency base G note
      const osc1 = ctx.createOscillator();
      const gain1 = ctx.createGain();
      osc1.type = 'sawtooth';
      osc1.frequency.setValueAtTime(80, ctx.currentTime);
      osc1.frequency.exponentialRampToValueAtTime(100, ctx.currentTime + 0.15);

      gain1.gain.setValueAtTime(0.01, ctx.currentTime);
      gain1.gain.linearRampToValueAtTime(0.5, ctx.currentTime + 0.05);
      gain1.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.45);

      // Main "Dum" note
      const osc2 = ctx.createOscillator();
      const gain2 = ctx.createGain();
      osc2.type = 'triangle';
      osc2.frequency.setValueAtTime(95, ctx.currentTime + 0.08);
      osc2.frequency.exponentialRampToValueAtTime(85, ctx.currentTime + 0.4);

      gain2.gain.setValueAtTime(0.01, ctx.currentTime + 0.08);
      gain2.gain.linearRampToValueAtTime(0.7, ctx.currentTime + 0.12);
      gain2.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.8);

      // Sub-bass rumble
      const subOsc = ctx.createOscillator();
      const subGain = ctx.createGain();
      subOsc.type = 'sine';
      subOsc.frequency.setValueAtTime(45, ctx.currentTime + 0.08);
      subGain.gain.setValueAtTime(0.01, ctx.currentTime + 0.08);
      subGain.gain.linearRampToValueAtTime(0.65, ctx.currentTime + 0.15);
      subGain.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 1.1);

      // Lowpass Filter
      const filter = ctx.createBiquadFilter();
      filter.type = 'lowpass';
      filter.frequency.setValueAtTime(140, ctx.currentTime);
      filter.frequency.exponentialRampToValueAtTime(75, ctx.currentTime + 0.6);

      osc1.connect(gain1);
      gain1.connect(filter);

      osc2.connect(gain2);
      gain2.connect(filter);

      subOsc.connect(subGain);
      subGain.connect(filter);

      filter.connect(ctx.destination);

      osc1.start(ctx.currentTime);
      osc1.stop(ctx.currentTime + 0.5);

      osc2.start(ctx.currentTime + 0.08);
      osc2.stop(ctx.currentTime + 0.95);

      subOsc.start(ctx.currentTime + 0.08);
      subOsc.stop(ctx.currentTime + 1.25);
    } catch (err) {
      console.warn('Audio Context failed to initialize:', err);
    }
  };
  
  // Create profile form states
  const [newName, setNewName] = useState('');
  const [selectedColor, setSelectedColor] = useState(PROFILE_AVATAR_GRADIENTS[0]);
  const [selectedEmoji, setSelectedEmoji] = useState(PROFILE_AVATAR_EMOJIS[0]);
  const [selectedAvatarUrl, setSelectedAvatarUrl] = useState<string | null>(null);
  const [isKids, setIsKids] = useState(false);

  const handleCreateProfile = (e: React.FormEvent) => {
    e.preventDefault();
    if (!newName.trim()) {
      toast.error('Por favor escribe un nombre');
      return;
    }
    if (profiles.length >= 4) {
      toast.error('Has alcanzado el límite máximo de 4 perfiles');
      return;
    }
    addProfile(newName.trim(), selectedColor, selectedEmoji, isKids, selectedAvatarUrl || undefined);
    toast.success('Perfil creado correctamente');
    
    // Reset states
    setNewName('');
    setSelectedColor(PROFILE_AVATAR_GRADIENTS[Math.min(profiles.length + 1, PROFILE_AVATAR_GRADIENTS.length - 1)]);
    setSelectedEmoji(PROFILE_AVATAR_EMOJIS[Math.min(profiles.length + 1, PROFILE_AVATAR_EMOJIS.length - 1)]);
    setSelectedAvatarUrl(null);
    setIsKids(false);
    setIsCreating(false);
  };

  const handleDeleteProfile = (id: string, name: string) => {
    if (confirm(`¿Estás seguro de que deseas eliminar el perfil "${name}"? Todo su historial y favoritos se perderán.`)) {
      deleteProfile(id);
      toast.success('Perfil eliminado');
    }
  };

  return (
    <div className="min-h-screen bg-[#141414] text-white flex items-center justify-center p-6 relative overflow-hidden select-none">
      {/* Background radial highlight */}
      <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[800px] h-[800px] bg-primary/5 rounded-full blur-[120px] pointer-events-none" />

      <div className="max-w-4xl w-full flex flex-col items-center justify-center z-10">
        
        <AnimatePresence mode="wait">
          {!isCreating ? (
            <motion.div
              key="select"
              initial={{ opacity: 0, y: 15 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -15 }}
              className="text-center w-full"
            >
              <h1 className="text-3xl md:text-5xl font-extrabold tracking-tight mb-8 bg-gradient-to-r from-white via-white to-white/60 bg-clip-text text-transparent">
                {isManaging ? 'Administrar Perfiles' : '¿Quién está viendo hoy?'}
              </h1>

              {/* Profiles list */}
              <div className="flex flex-wrap justify-center gap-6 md:gap-8 my-10">
                {profiles.map((p, index) => (
                  <motion.div
                    key={p.id}
                    initial={{ opacity: 0, scale: 0.9, y: 10 }}
                    animate={
                      selectedProfileId === p.id 
                        ? { scale: 1.25, y: -10, opacity: [1, 1, 0] } 
                        : (selectedProfileId ? { scale: 0.8, opacity: 0 } : { opacity: 1, scale: 1, y: 0 })
                    }
                    transition={
                      selectedProfileId 
                        ? { duration: 0.85, ease: 'easeInOut' } 
                        : { delay: index * 0.05 }
                    }
                    className={cn(
                      "flex flex-col items-center group cursor-pointer transition-all duration-300",
                      selectedProfileId && selectedProfileId !== p.id && "pointer-events-none"
                    )}
                    onClick={() => {
                      if (!isManaging && !selectedProfileId) {
                        setSelectedProfileId(p.id);
                        playTudumSound();
                        setTimeout(() => {
                          selectProfile(p);
                          toast.success(`Bienvenido, ${p.name}`);
                        }, 900);
                      }
                    }}
                  >
                    {/* Avatar box */}
                    <div 
                      className={cn(
                        "relative w-28 h-28 md:w-32 md:h-32 rounded-xl shadow-lg flex items-center justify-center text-5xl md:text-6xl border-2 transition-all duration-300 overflow-hidden",
                        isManaging 
                          ? "border-white/20 hover:scale-105" 
                          : "border-transparent group-hover:border-white group-hover:scale-105 group-hover:shadow-white/10"
                      )}
                      style={{ background: p.avatarColor }}
                    >
                      {p.avatarUrl ? (
                        <img src={p.avatarUrl} alt="" className="w-full h-full object-cover select-none pointer-events-none" />
                      ) : (
                        p.avatarEmoji
                      )}

                      {/* Management Overlay */}
                      {isManaging && (
                        <div className="absolute inset-0 bg-black/60 rounded-xl flex items-center justify-center transition-opacity">
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              handleDeleteProfile(p.id, p.name);
                            }}
                            className="p-3 rounded-full bg-red-600/90 text-white hover:bg-red-700 transition-all scale-100 hover:scale-110 shadow-lg"
                            title="Eliminar Perfil"
                          >
                            <FiTrash2 size={20} />
                          </button>
                        </div>
                      )}
                    </div>

                    {/* Profile name */}
                    <span 
                      className={cn(
                        "mt-4 text-sm md:text-base font-semibold transition-colors duration-200",
                        isManaging ? "text-white/60" : "text-white/70 group-hover:text-white"
                      )}
                    >
                      {p.name}
                      {p.isKids && (
                        <span className="ml-1.5 text-[9px] font-black tracking-widest text-primary bg-primary/10 border border-primary/20 px-1.5 py-0.5 rounded uppercase">
                          KIDS
                        </span>
                      )}
                    </span>
                  </motion.div>
                ))}

                {/* Add new profile block */}
                {profiles.length < 4 && (
                  <motion.div
                    initial={{ opacity: 0, scale: 0.9, y: 10 }}
                    animate={{ opacity: 1, scale: 1, y: 0 }}
                    transition={{ delay: profiles.length * 0.05 }}
                    className="flex flex-col items-center group cursor-pointer"
                    onClick={() => setIsCreating(true)}
                  >
                    <div className="w-28 h-28 md:w-32 md:h-32 rounded-xl border-2 border-dashed border-white/20 flex items-center justify-center text-white/40 group-hover:border-white group-hover:text-white transition-all duration-300 hover:scale-105">
                      <FiPlus size={36} />
                    </div>
                    <span className="mt-4 text-sm md:text-base font-semibold text-white/40 group-hover:text-white transition-colors duration-200">
                      Agregar perfil
                    </span>
                  </motion.div>
                )}
              </div>

              {/* Action buttons */}
              <div className="flex flex-col sm:flex-row gap-4 justify-center items-center mt-10">
                {profiles.length > 0 && (
                  <Button
                    variant={isManaging ? 'primary' : 'secondary'}
                    onClick={() => setIsManaging(!isManaging)}
                    className="min-w-[200px]"
                    icon={isManaging ? <FiCheck size={16} /> : <FiEdit2 size={16} />}
                  >
                    {isManaging ? 'Listo' : 'Administrar Perfiles'}
                  </Button>
                )}
              </div>
            </motion.div>
          ) : (
            <motion.div
              key="create"
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="glass-card p-6 md:p-8 rounded-2xl border border-white/10 w-full max-w-md shadow-2xl relative"
            >
              {/* Close Button */}
              <button
                onClick={() => setIsCreating(false)}
                className="absolute top-4 right-4 p-2 text-white/50 hover:text-white bg-white/5 hover:bg-white/10 rounded-full transition-colors"
              >
                <FiX size={18} />
              </button>

              <h2 className="text-2xl font-black text-white mb-6">Crear Perfil</h2>

              <form onSubmit={handleCreateProfile} className="space-y-6">
                
                {/* Profile Avatar Preview */}
                <div className="flex flex-col items-center gap-3">
                  <div 
                    className="w-24 h-24 rounded-xl flex items-center justify-center text-5xl shadow-xl border-2 border-white/10 overflow-hidden"
                    style={{ background: selectedColor }}
                  >
                    {selectedAvatarUrl ? (
                      <img src={selectedAvatarUrl} alt="" className="w-full h-full object-cover" />
                    ) : (
                      selectedEmoji
                    )}
                  </div>
                  <span className="text-xs text-white/40">Tu avatar personalizado</span>
                </div>

                {/* Name field */}
                <div className="space-y-2">
                  <label className="text-xs font-bold text-white/60 uppercase tracking-wider block">Nombre del Perfil</label>
                  <input
                    type="text"
                    value={newName}
                    onChange={(e) => setNewName(e.target.value.slice(0, 12))}
                    placeholder="Escribe el nombre"
                    className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder-white/20 focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all text-sm font-semibold"
                    maxLength={12}
                    required
                  />
                </div>

                {/* Preset Avatars picker */}
                <div className="space-y-2">
                  <label className="text-xs font-bold text-white/60 uppercase tracking-wider block font-sans">Elige un Avatar Premium</label>
                  <div className="grid grid-cols-6 gap-2 bg-white/5 p-2.5 rounded-xl border border-white/5">
                    {PRESET_AVATARS.map((av) => {
                      const isSelected = selectedAvatarUrl === av.url;
                      return (
                        <button
                          key={av.url}
                          type="button"
                          onClick={() => {
                            setSelectedAvatarUrl(isSelected ? null : av.url);
                          }}
                          className={cn(
                            "relative aspect-square rounded-lg overflow-hidden border-2 transition-all hover:scale-105 select-none border-0 p-0 cursor-pointer bg-transparent",
                            isSelected ? "border-primary scale-105 shadow shadow-primary/30" : "border-transparent opacity-60 hover:opacity-100"
                          )}
                          title={av.name}
                        >
                          <img src={av.url} alt={av.name} className="w-full h-full object-cover" />
                          {isSelected && (
                            <div className="absolute inset-0 bg-primary/20 flex items-center justify-center">
                              <div className="w-5 h-5 rounded-full bg-primary flex items-center justify-center shadow">
                                <FiCheck size={11} className="text-white" />
                              </div>
                            </div>
                          )}
                        </button>
                      );
                    })}
                  </div>
                </div>

                {/* Colors picker */}
                <div className="space-y-2">
                  <label className="text-xs font-bold text-white/60 uppercase tracking-wider block">Elige un Fondo</label>
                  <div className="flex flex-wrap gap-2.5">
                    {PROFILE_AVATAR_GRADIENTS.map((color) => (
                      <button
                        key={color}
                        type="button"
                        onClick={() => setSelectedColor(color)}
                        className={cn(
                          "w-8 h-8 rounded-lg border transition-all hover:scale-110",
                          selectedColor === color ? "border-white scale-110 ring-2 ring-primary/45" : "border-transparent"
                        )}
                        style={{ background: color }}
                      />
                    ))}
                  </div>
                </div>

                {/* Emoji picker */}
                <div className="space-y-2">
                  <label className="text-xs font-bold text-white/60 uppercase tracking-wider block">Elige un Emoji</label>
                  <div className="flex flex-wrap gap-2.5">
                    {PROFILE_AVATAR_EMOJIS.map((emoji) => (
                      <button
                        key={emoji}
                        type="button"
                        onClick={() => setSelectedEmoji(emoji)}
                        className={cn(
                          "w-8 h-8 rounded-lg bg-white/5 hover:bg-white/10 border transition-all text-lg flex items-center justify-center hover:scale-110",
                          selectedEmoji === emoji ? "border-white bg-white/10 scale-110" : "border-transparent"
                        )}
                      >
                        {emoji}
                      </button>
                    ))}
                  </div>
                </div>

                {/* Kids Mode Toggle */}
                <div className="flex items-center justify-between p-3.5 bg-white/5 rounded-xl border border-white/5">
                  <div>
                    <h4 className="text-sm font-bold text-white">Perfil Infantil</h4>
                    <p className="text-[10px] text-white/40 mt-0.5">Acceso exclusivo a contenido apto para niños.</p>
                  </div>
                  <input
                    type="checkbox"
                    checked={isKids}
                    onChange={(e) => setIsKids(e.target.checked)}
                    className="w-5 h-5 accent-primary cursor-pointer rounded"
                  />
                </div>

                {/* Submit buttons */}
                <div className="grid grid-cols-2 gap-3 pt-2">
                  <Button
                    variant="secondary"
                    type="button"
                    onClick={() => setIsCreating(false)}
                  >
                    Cancelar
                  </Button>
                  <Button
                    variant="primary"
                    type="submit"
                  >
                    Guardar
                  </Button>
                </div>

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

      </div>
    </div>
  );
}
