import Image from 'next/image';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import { LogOut, X, TrendingUp, Award } from 'lucide-react';

import { useUser, useIsAdmin } from '@/store/auth.store';
import { useLogout } from '@/hooks/useAuth';
import { cn } from '@/lib/utils';
import { adminNavItems, userNavItems } from '@/config/dashboard';

interface SidebarProps {
  isOpen: boolean;
  onClose: () => void;
}

export function Sidebar({ isOpen, onClose }: SidebarProps) {
  const pathname = usePathname();
  const user = useUser();
  const isAdmin = useIsAdmin();
  const logout = useLogout();

  const navItems = isAdmin ? adminNavItems : userNavItems;
  const isActive = (href: string, exact?: boolean) =>
    exact ? pathname === href : pathname.startsWith(href);

  return (
    <>
      {/* Mobile Backdrop */}
      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={onClose}
            className="fixed inset-0 bg-black/60 backdrop-blur-sm z-40 lg:hidden"
          />
        )}
      </AnimatePresence>

      {/* Sidebar Panel */}
      <aside
        className={cn(
          'fixed top-0 left-0 h-screen w-[280px] bg-white/70 backdrop-blur-xl border-r border-white/50 z-50 flex flex-col transition-transform duration-300 ease-in-out shadow-[4px_0_24px_rgba(0,0,0,0.02)] lg:shadow-none',
          isOpen ? 'translate-x-0' : '-translate-x-full lg:translate-x-0'
        )}
      >
        {/* Header Logo */}
        <div className="h-20 px-6 flex items-center justify-between shrink-0 border-b border-white/50">
          <div className="flex items-center gap-3">
            <Image src={'/logo.avif'} width={32} height={32} alt="logo" />
            <div>
              <p className="font-black text-gray-900 text-sm uppercase tracking-wider leading-none">
                Garam <span className="text-yellow-600">Kapal</span>
              </p>
              <p className="text-[10px] font-bold text-gray-500 uppercase tracking-widest mt-1">
                {isAdmin ? 'Admin Panel' : 'Member Portal'}
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="lg:hidden p-2 rounded-lg text-gray-500 hover:bg-white hover:text-gray-900 transition-colors shadow-sm bg-white/50 border border-white/50"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* User Info Card */}
        <div className="px-4 py-6 shrink-0 border-b border-white/50">
          <div className="bg-white/50 rounded-2xl p-4 border border-white/50 flex flex-col gap-4 relative overflow-hidden shadow-sm">
            <div className="absolute -top-10 -right-10 w-24 h-24 bg-yellow-400/20 rounded-full blur-2xl pointer-events-none" />
            <div className="flex items-center gap-3 relative z-10">
              {user?.avatar_url ? (
                <Image
                  src={user.avatar_url}
                  alt={user.name ?? ''}
                  width={40}
                  height={40}
                  className="rounded-full object-cover border-2 border-white shrink-0 shadow-sm"
                />
              ) : (
                <div className="w-10 h-10 rounded-full bg-white border border-gray-200 flex items-center justify-center font-black text-gray-700 text-sm shrink-0 shadow-sm">
                  {user?.name?.charAt(0).toUpperCase() ?? 'U'}
                </div>
              )}
              <div className="flex-1 min-w-0">
                <p className="font-bold text-gray-900 text-sm truncate tracking-wide">
                  {user?.name}
                </p>
                <p className="text-[10px] text-gray-500 font-medium truncate mt-0.5">
                  {user?.email}
                </p>
              </div>
            </div>
            <div className="flex items-center justify-between pt-3 border-t border-white/50 relative z-10">
              <span className="text-[10px] font-bold text-gray-500 uppercase tracking-widest">
                {isAdmin ? 'Status' : 'Total Poin'}
              </span>
              <div className="flex items-center gap-1.5 px-2 py-1 rounded-md bg-yellow-100 border border-yellow-200">
                {isAdmin ? (
                  <>
                    <TrendingUp className="w-3 h-3 text-yellow-700" />
                    <span className="text-[10px] font-bold text-yellow-700 uppercase tracking-wider">
                      Super Admin
                    </span>
                  </>
                ) : (
                  <>
                    <Award className="w-3 h-3 text-yellow-700" />
                    <span className="text-[10px] font-bold text-yellow-700 tracking-wider">
                      {user?.points}
                    </span>
                  </>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Navigation Menu */}
        <nav className="flex-1 overflow-y-auto p-4 custom-scrollbar relative">
          <div className="absolute bottom-0 right-0 opacity-10 pointer-events-none">
            <Image
              src="/mascots/capt-yodi-chill-pose.avif"
              alt="Captain Yodi"
              className="w-32 h-32 object-contain"
              width={500}
              height={500}
            />
          </div>
          <p className="text-[10px] font-bold text-gray-500 uppercase tracking-widest px-2 mb-3">
            Menu Utama
          </p>
          <ul className="space-y-1.5">
            {navItems.map((item) => {
              const active = isActive(item.href, item.exact);
              const Icon = item.icon;
              return (
                <li key={item.href}>
                  <Link
                    href={item.href}
                    onClick={() => onClose()}
                    className={cn(
                      'w-full flex items-center gap-3 px-3 py-3 rounded-xl text-sm font-bold uppercase tracking-wider transition-all duration-200 group',
                      active
                        ? 'bg-[#FFD738] text-gray-900 shadow-md shadow-[#FFD738]/20'
                        : 'text-gray-500 hover:bg-white/80 hover:text-gray-900'
                    )}
                  >
                    <Icon
                      className={cn(
                        'w-5 h-5 shrink-0 transition-colors',
                        active
                          ? 'text-gray-900'
                          : 'text-gray-400 group-hover:text-yellow-600'
                      )}
                    />
                    <span className="flex-1">{item.label}</span>
                  </Link>
                </li>
              );
            })}
          </ul>
        </nav>

        {/* Logout */}
        <div className="p-4 shrink-0">
          <button
            onClick={async () => await logout.mutateAsync()}
            disabled={logout.isPending}
            className="w-full flex items-center justify-center gap-2 px-4 py-3 rounded-xl bg-white/50 border border-gray-200 shadow-sm text-gray-500 hover:bg-rose-50 hover:border-rose-200 hover:text-rose-600 font-bold text-sm uppercase tracking-wider transition-all disabled:opacity-50 cursor-pointer disabled:cursor-not-allowed disabled:hover:bg-rose-50 disabled:hover:border-rose-200 disabled:hover:text-rose-600"
          >
            <LogOut className="w-4 h-4 shrink-0" />
            {logout.isPending ? 'Keluar...' : 'Keluar'}
          </button>
        </div>
      </aside>
    </>
  );
}
