'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { usePathname, useRouter } from 'next/navigation'
import { useAffiliateStore } from '@/store/affiliate-store'
import {
  Users, LayoutDashboard, DollarSign, Wallet, LogOut, Menu, X, UserPlus
} from 'lucide-react'

const navigation = [
  { name: 'Dashboard', href: '/affiliate', icon: LayoutDashboard },
  { name: 'Referral Saya', href: '/affiliate/referrals', icon: Users },
  { name: 'Komisi', href: '/affiliate/commissions', icon: DollarSign },
  { name: 'Dompet', href: '/affiliate/wallet', icon: Wallet },
]

export default function AffiliateLayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname()
  const router = useRouter()
  const { affiliate, setAffiliate } = useAffiliateStore()
  const [sidebarOpen, setSidebarOpen] = useState(false)
  const [loading, setLoading] = useState(true)

  const isAuthPage = pathname === '/affiliate/login' || pathname === '/affiliate/register'

  useEffect(() => {
    if (isAuthPage) {
      setLoading(false)
      return
    }

    fetch('/api/affiliate/auth/me')
      .then(res => res.json())
      .then(data => {
        if (data.affiliate) {
          setAffiliate(data.affiliate)
        } else {
          router.push('/affiliate/login')
        }
      })
      .catch(() => router.push('/affiliate/login'))
      .finally(() => setLoading(false))
  }, [setAffiliate, router, pathname, isAuthPage])

  if (isAuthPage) {
    return <>{children}</>
  }

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-emerald-600"></div>
      </div>
    )
  }

  const handleLogout = async () => {
    await fetch('/api/affiliate/auth/logout', { method: 'POST' })
    useAffiliateStore.getState().logout()
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {sidebarOpen && (
        <div className="fixed inset-0 z-40 lg:hidden">
          <div className="fixed inset-0 bg-black/50" onClick={() => setSidebarOpen(false)} />
          <div className="fixed inset-y-0 left-0 w-64 bg-white shadow-xl z-50">
            <SidebarContent pathname={pathname} affiliate={affiliate} onLogout={handleLogout} onClose={() => setSidebarOpen(false)} />
          </div>
        </div>
      )}

      <div className="hidden lg:fixed lg:inset-y-0 lg:flex lg:w-64 lg:flex-col">
        <div className="flex flex-col flex-grow bg-white border-r border-gray-200">
          <SidebarContent pathname={pathname} affiliate={affiliate} onLogout={handleLogout} />
        </div>
      </div>

      <div className="lg:pl-64">
        <header className="sticky top-0 z-30 bg-white border-b border-gray-200">
          <div className="flex items-center justify-between h-16 px-4 sm:px-6">
            <button onClick={() => setSidebarOpen(true)} className="lg:hidden text-gray-500 hover:text-gray-700">
              <Menu className="w-6 h-6" />
            </button>
            <div className="flex-1" />
            <div className="flex items-center gap-3">
              {!affiliate?.isActive && (
                <span className="text-xs bg-yellow-100 text-yellow-800 px-2 py-1 rounded-full">Menunggu Persetujuan</span>
              )}
              <div className="flex items-center gap-2">
                <div className="w-8 h-8 bg-emerald-100 rounded-full flex items-center justify-center text-emerald-700 font-medium text-sm">
                  {affiliate?.name?.charAt(0).toUpperCase()}
                </div>
                <span className="hidden sm:block text-sm font-medium text-gray-700">{affiliate?.name}</span>
              </div>
            </div>
          </div>
        </header>
        <main className="p-4 sm:p-6 lg:p-8">{children}</main>
      </div>
    </div>
  )
}

function SidebarContent({ pathname, affiliate, onLogout, onClose }: {
  pathname: string
  affiliate: any
  onLogout: () => void
  onClose?: () => void
}) {
  return (
    <div className="flex flex-col h-full">
      <div className="flex items-center justify-between h-16 px-4 border-b border-gray-200">
        <Link href="/affiliate" className="flex items-center gap-2">
          <UserPlus className="w-8 h-8 text-emerald-600" />
          <span className="text-lg font-bold text-gray-900">Affiliate</span>
        </Link>
        {onClose && (
          <button onClick={onClose} className="lg:hidden text-gray-400 hover:text-gray-600">
            <X className="w-5 h-5" />
          </button>
        )}
      </div>

      {affiliate && (
        <div className="px-4 py-3 border-b border-gray-200 bg-gray-50">
          <p className="text-sm font-medium text-gray-900 truncate">{affiliate.name}</p>
          <p className="text-xs text-gray-500">{affiliate.email}</p>
        </div>
      )}

      <nav className="flex-1 min-h-0 px-3 py-4 space-y-1 overflow-y-auto">
        {navigation.map((item) => {
          const isActive = item.href === '/affiliate'
            ? pathname === '/affiliate'
            : pathname.startsWith(item.href)
          return (
            <Link key={item.href} href={item.href}
              className={`flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ${
                isActive ? 'bg-emerald-50 text-emerald-700' : 'text-gray-600 hover:bg-gray-100 hover:text-gray-900'
              }`}>
              <item.icon className={`w-5 h-5 ${isActive ? 'text-emerald-600' : 'text-gray-400'}`} />
              {item.name}
            </Link>
          )
        })}
      </nav>

      <div className="flex-shrink-0 p-3 border-t border-gray-200">
        <button onClick={onLogout}
          className="flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium text-red-600 hover:bg-red-50 w-full transition-colors">
          <LogOut className="w-5 h-5" /> Keluar
        </button>
      </div>
    </div>
  )
}
