'use client'

import { useState } from 'react'
import { Link, usePathname, useRouter } from '@/i18n/navigation'
import { useTranslations } from 'next-intl'
import {
  LayoutDashboard,
  ShoppingBag,
  Heart,
  Star,
  MapPin,
  User,
  Lock,
  LogOut,
  Gift,
  TrendingUp,
  Menu,
  X
} from 'lucide-react'
import * as motion from 'framer-motion/m'
import { AnimatePresence } from 'framer-motion'

// `@/i18n/navigation`'s Link/usePathname (next-intl's locale-aware
// wrappers) instead of plain `next/link`/`next/navigation` — the rest of
// the storefront relies on a NEXT_LOCALE-cookie middleware fallback to keep
// an unprefixed href like `/account/orders` on the current locale, but that
// only covers *navigation*; it can't fix `usePathname()` returning the
// locale-prefixed path (`/ur/account`) while every `item.href` here is
// unprefixed (`/account`), which silently broke this menu's active-item
// highlight for every non-default locale. Using these wrappers fixes both
// at once and is a real navigation correctness issue, not just style.
export default function AccountSidebar() {
  const pathname = usePathname()
  const router = useRouter()
  const t = useTranslations('Account')
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false)

  const menuItems = [
    { name: t('nav.dashboard'), href: '/account', icon: LayoutDashboard },
    { name: t('nav.orders'), href: '/account/orders', icon: ShoppingBag },
    { name: t('nav.wishlist'), href: '/account/wishlist', icon: Heart },
    { name: t('nav.reviews'), href: '/account/reviews', icon: Star },
    { name: t('nav.addresses'), href: '/account/addresses', icon: MapPin },
    { name: t('nav.profile'), href: '/account/profile', icon: User },
    { name: t('nav.changePassword'), href: '/account/change-password', icon: Lock },
    { name: t('nav.referrals'), href: '/account/referrals', icon: Gift },
    { name: t('nav.earnings'), href: '/account/earnings', icon: TrendingUp },
  ]

  const handleLogout = async () => {
    try {
      await fetch('/api/frontend/auth/logout', { method: 'POST', credentials: 'include' })
    } finally {
      router.push('/login')
      router.refresh()
    }
  }

  const sidebarContent = (
    <>
      <div className="p-4 border-b border-gray-100 bg-gray-50">
        <h3 className="font-semibold text-dark">{t('nav.myAccount')}</h3>
      </div>

      <nav className="p-2">
        {menuItems.map((item) => {
          const isActive = pathname === item.href
          const Icon = item.icon

          return (
            <Link
              key={item.href}
              href={item.href}
              onClick={() => setIsMobileMenuOpen(false)}
              className={`flex items-center gap-3 px-3 py-2.5 rounded-lg transition-all duration-200 ${
                isActive
                  ? 'bg-primary/10 text-primary font-medium'
                  : 'text-dark hover:bg-gray-50'
              }`}
            >
              <Icon size={18} className={isActive ? 'text-primary' : 'text-gray-custom'} />
              <span className="text-sm">{item.name}</span>
            </Link>
          )
        })}

        <button
          onClick={handleLogout}
          className="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-red-600 hover:bg-red-50 transition-all duration-200 mt-2"
        >
          <LogOut size={18} />
          <span className="text-sm">{t('nav.logout')}</span>
        </button>
      </nav>
    </>
  )

  return (
    <>
      {/* Mobile Menu Button */}
      <div className="md:hidden mb-4">
        <button
          onClick={() => setIsMobileMenuOpen(true)}
          className="w-full flex items-center justify-between p-3 bg-white border border-gray-200 rounded-lg"
        >
          <div className="flex items-center gap-2">
            <Menu size={18} className="text-primary" />
            <span className="text-dark font-medium">{t('nav.accountMenu')}</span>
          </div>
          <span className="text-gray-custom text-sm">
            {menuItems.find(item => item.href === pathname)?.name || t('nav.menu')}
          </span>
        </button>
      </div>

      {/* Desktop Sidebar */}
      <div className="hidden md:block w-64 flex-shrink-0">
        <div className="sticky top-24 bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          {sidebarContent}
        </div>
      </div>

      {/* Mobile Drawer */}
      <AnimatePresence>
        {isMobileMenuOpen && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="fixed inset-0 bg-black/50 z-50"
              onClick={() => setIsMobileMenuOpen(false)}
            />
            <motion.div
              initial={{ x: '-100%' }}
              animate={{ x: 0 }}
              exit={{ x: '-100%' }}
              transition={{ type: 'spring', damping: 25, stiffness: 300 }}
              className="fixed top-0 left-0 w-80 h-full bg-white z-50 shadow-xl overflow-y-auto"
            >
              <div className="sticky top-0 bg-white border-b border-gray-100 p-4 flex justify-between items-center">
                <h3 className="font-bold text-dark">{t('nav.accountMenu')}</h3>
                <button
                  onClick={() => setIsMobileMenuOpen(false)}
                  className="p-2 hover:bg-gray-100 rounded-full transition"
                >
                  <X size={20} />
                </button>
              </div>
              {sidebarContent}
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </>
  )
}
