'use client'

import { useState, useEffect } from 'react'
import Link from 'next/link'
import Image from 'next/image'
import { usePathname } from 'next/navigation'
import {
  HomeIcon,
  GridIcon,
  ImageIcon,
  BookOpenIcon,
  PhoneIcon,
  TagIcon,
  MenuIcon,
  XIcon,
  ChevronRightIcon,
  MessageCircleIcon,
} from 'lucide-react'
import { Icon } from '@iconify/react'
import { cn } from '@/lib/utils'
import { getMediaUrl } from '@/lib/api'
import { ModeToggle } from '@/components/layout/mode-toggle'
import { openWhatsAppModal } from '@/components/layout/whatsapp-modal'

type SidebarProps = {
  domain?: any
  menu?: any[]
}

const defaultNav = [
  { name: 'Beranda', href: '/#home', icon: HomeIcon },
  { name: 'Kategori', href: '/#categories', icon: GridIcon },
  { name: 'Galeri', href: '/#brands', icon: ImageIcon },
  { name: 'Artikel', href: '/#posts', icon: BookOpenIcon },
  { name: 'Kontak', href: '/contact-us', icon: PhoneIcon },
]

const Sidebar = ({ domain, menu }: SidebarProps) => {
  const pathname = usePathname()
  const [isOpen, setIsOpen] = useState(false)
  const [isScrolled, setIsScrolled] = useState(false)

  useEffect(() => {
    const handleScroll = () => setIsScrolled(window.scrollY > 10)
    window.addEventListener('scroll', handleScroll)
    return () => window.removeEventListener('scroll', handleScroll)
  }, [])

  // Close sidebar on route change (mobile)
  useEffect(() => {
    setIsOpen(false)
  }, [pathname])

  const navItems = menu && menu.length > 0
    ? menu.map((m: any) => ({ name: m.name, href: m.url || '#', icon: TagIcon }))
    : defaultNav

  const whatsappUrl = domain?.whatsapp
    ? domain.whatsapp.startsWith('http')
      ? domain.whatsapp
      : `https://wa.me/${domain.whatsapp.replace(/\D/g, '').replace(/^0/, '62')}`
    : null

  return (
    <>
      {/* Mobile top bar */}
      <div
        className={cn(
          'fixed top-0 left-0 right-0 z-50 flex items-center justify-between px-4 h-14 lg:hidden',
          'bg-background/80 backdrop-blur-md border-b border-border transition-all duration-300',
          isScrolled && 'shadow-sm'
        )}
      >
        <Link href='/' className='flex items-center gap-2'>
          {domain?.logo ? (
            <Image
              src={getMediaUrl(domain.logo)}
              alt={domain.name || 'Logo'}
              width={120}
              height={40}
              className='object-contain h-8 w-auto'
            />
          ) : (
            <span className='font-bold text-lg tracking-tight'>{domain?.name || 'Site'}</span>
          )}
        </Link>
        <div className='flex items-center gap-2'>
          <ModeToggle />
          <button
            onClick={() => setIsOpen(!isOpen)}
            className='p-2 rounded-lg hover:bg-muted transition-colors'
            aria-label='Toggle menu'
          >
            {isOpen ? <XIcon className='w-5 h-5' /> : <MenuIcon className='w-5 h-5' />}
          </button>
        </div>
      </div>

      {/* Mobile overlay */}
      {isOpen && (
        <div
          className='fixed inset-0 z-40 bg-black/50 lg:hidden backdrop-blur-sm'
          onClick={() => setIsOpen(false)}
        />
      )}

      {/* Sidebar */}
      <aside
        className={cn(
          'fixed left-0 top-0 z-50 h-screen w-64 flex flex-col',
          'bg-card border-r border-border',
          'transition-transform duration-300 ease-in-out',
          'max-lg:shadow-2xl',
          isOpen ? 'translate-x-0' : 'max-lg:-translate-x-full'
        )}
      >
        {/* Sidebar Header / Logo */}
        <div className='flex items-center justify-between p-5 border-b border-border shrink-0'>
          <Link href='/' className='flex items-center gap-3 min-w-0'>
            {domain?.logo ? (
              <Image
                src={getMediaUrl(domain.logo)}
                alt={domain.name || 'Logo'}
                width={140}
                height={50}
                className='object-contain h-10 w-auto max-w-[140px]'
              />
            ) : (
              <div className='flex flex-col'>
                <span className='font-bold text-base leading-tight truncate'>
                  {domain?.name || 'My Site'}
                </span>
                <span className='text-xs text-muted-foreground'>Website</span>
              </div>
            )}
          </Link>
          <button
            onClick={() => setIsOpen(false)}
            className='lg:hidden p-1.5 rounded-md hover:bg-muted transition-colors shrink-0'
          >
            <XIcon className='w-4 h-4' />
          </button>
        </div>

        {/* Navigation */}
        <nav className='flex-1 overflow-y-auto py-4 px-3 space-y-1'>
          {navItems.map((item, i) => {
            const Icon = item.icon
            const isActive = pathname === item.href || (item.href !== '/' && pathname.startsWith(item.href.split('#')[0]) && item.href.split('#')[0] !== '/')
            return (
              <Link
                key={i}
                href={item.href}
                className={cn(
                  'group flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium',
                  'transition-all duration-200',
                  isActive
                    ? 'bg-primary text-primary-foreground shadow-sm'
                    : 'text-muted-foreground hover:text-foreground hover:bg-muted'
                )}
              >
                <Icon className='w-4 h-4 shrink-0' />
                <span className='flex-1 truncate'>{item.name}</span>
                <ChevronRightIcon
                  className={cn(
                    'w-3 h-3 opacity-0 -translate-x-1 transition-all duration-200',
                    'group-hover:opacity-50 group-hover:translate-x-0',
                    isActive && 'opacity-100 translate-x-0'
                  )}
                />
              </Link>
            )
          })}
        </nav>

        {/* Sidebar Footer */}
        <div className='p-4 border-t border-border space-y-3 shrink-0'>
          {/* WhatsApp CTA */}
          {whatsappUrl && (
            <button
              type='button'
              onClick={() => {
                setIsOpen(false)
                openWhatsAppModal()
              }}
              className='cursor-pointer flex items-center gap-3 w-full px-3 py-2.5 rounded-xl bg-[#25D366] hover:bg-[#128C7E] text-white text-sm font-semibold transition-all duration-200 hover:shadow-lg hover:shadow-green-500/25 hover:-translate-y-0.5'
            >
              <Icon icon='ic:baseline-whatsapp' className='w-5 h-5 shrink-0' />
              <span>Chat Admin</span>
            </button>
          )}

          {/* Social + Theme Toggle */}
          <div className='flex items-center justify-between'>
            <div className='flex items-center gap-2'>
              {domain?.instagram && (
                <a href={domain.instagram} target='_blank' rel='noopener noreferrer'
                  className='p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors'>
                  <Icon icon='mdi:instagram' className='w-4 h-4' />
                </a>
              )}
              {domain?.youtube && (
                <a href={domain.youtube} target='_blank' rel='noopener noreferrer'
                  className='p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors'>
                  <Icon icon='mdi:youtube' className='w-4 h-4' />
                </a>
              )}
              {domain?.tiktok && (
                <a href={domain.tiktok} target='_blank' rel='noopener noreferrer'
                  className='p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors'>
                  <Icon icon='ic:baseline-tiktok' className='w-4 h-4' />
                </a>
              )}
            </div>
            <ModeToggle />
          </div>
        </div>
      </aside>
    </>
  )
}

export default Sidebar
