'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { usePathname, useRouter } from 'next/navigation'
import { useAuthStore } from '@/store/auth-store'
import { useTheme } from 'next-themes'
import {
  UtensilsCrossed, LayoutDashboard, BookOpen, Store, Users,
  ShoppingCart, QrCode, BarChart3, Settings, LogOut, Menu, X, ChevronDown,
  ChefHat, User, Bell, CreditCard, LifeBuoy, Wallet, Lock, ArrowUpCircle,
  Moon, Sun, Package, Tag, UserCheck, Trophy, CalendarClock, Receipt, Clock,
  MessageSquare, TrendingUp, ClipboardList
} from 'lucide-react'

const navigation = [
  { name: 'Dashboard', href: '/dashboard', icon: LayoutDashboard },
  { name: 'Menu', href: '/dashboard/menu', icon: BookOpen },
  { name: 'Pesanan', href: '/dashboard/orders', icon: ShoppingCart },
  { name: 'Cabang', href: '/dashboard/stores', icon: Store, feature: 'multi_branch' },
  { name: 'Staff', href: '/dashboard/staff', icon: Users },
  { name: 'QR & Meja', href: '/dashboard/tables', icon: QrCode, feature: 'qr_menu' },
  { name: 'Laporan', href: '/dashboard/reports', icon: BarChart3, feature: 'reports' },
  { name: 'Inventori', href: '/dashboard/inventory', icon: Package, feature: 'inventory' },
  { name: 'Promo', href: '/dashboard/promotions', icon: Tag, feature: 'promos' },
  { name: 'Pelanggan', href: '/dashboard/customers', icon: UserCheck, feature: 'customers' },
  { name: 'Loyalti', href: '/dashboard/loyalty', icon: Trophy, feature: 'loyalty' },
  { name: 'Reservasi', href: '/dashboard/reservations', icon: CalendarClock, feature: 'reservations' },
  { name: 'Pengeluaran', href: '/dashboard/expenses', icon: Receipt, feature: 'expenses' },
  { name: 'Absensi', href: '/dashboard/attendance', icon: Clock, feature: 'attendance' },
  { name: 'Feedback', href: '/dashboard/feedback', icon: MessageSquare, feature: 'feedback' },
  { name: 'Analitik', href: '/dashboard/analytics', icon: TrendingUp, feature: 'advanced_analytics' },
  { name: 'Dompet', href: '/dashboard/wallet', icon: Wallet, feature: 'online_payment' },
  { name: 'Langganan', href: '/dashboard/subscription', icon: CreditCard },
  { name: 'Bantuan', href: '/dashboard/tickets', icon: LifeBuoy },
  { name: 'Stasiun Dapur', href: '/dashboard/kitchen-stations', icon: ChefHat, feature: 'kitchen_display' },
  { name: 'Audit Log', href: '/dashboard/audit-log', icon: ClipboardList },
  { name: 'Pengaturan', href: '/dashboard/settings', icon: Settings },
]

const quickLinks = [
  { name: 'Kitchen Display', href: '/kitchen', icon: ChefHat, color: 'text-red-600', feature: 'kitchen_display' },
  { name: 'Waiter View', href: '/waiter', icon: User, color: 'text-blue-600', feature: undefined as string | undefined },
]

const FREE_PLAN_FEATURES = ['pos', 'qr_menu']

// Route prefixes that require specific subscription features
const ROUTE_FEATURE_MAP: { prefix: string; feature: string; label: string }[] = [
  { prefix: '/dashboard/stores', feature: 'multi_branch', label: 'Multi Cabang' },
  { prefix: '/dashboard/tables', feature: 'qr_menu', label: 'QR Menu & Meja' },
  { prefix: '/dashboard/reports', feature: 'reports', label: 'Laporan & Analitik' },
  { prefix: '/dashboard/wallet', feature: 'online_payment', label: 'Pembayaran Online & Dompet' },
  { prefix: '/dashboard/inventory', feature: 'inventory', label: 'Manajemen Inventori' },
  { prefix: '/dashboard/promotions', feature: 'promos', label: 'Promo & Diskon' },
  { prefix: '/dashboard/customers', feature: 'customers', label: 'Manajemen Pelanggan' },
  { prefix: '/dashboard/loyalty', feature: 'loyalty', label: 'Program Loyalti' },
  { prefix: '/dashboard/reservations', feature: 'reservations', label: 'Reservasi Meja' },
  { prefix: '/dashboard/expenses', feature: 'expenses', label: 'Manajemen Pengeluaran' },
  { prefix: '/dashboard/attendance', feature: 'attendance', label: 'Absensi & Shift' },
  { prefix: '/dashboard/feedback', feature: 'feedback', label: 'Feedback & Rating' },
  { prefix: '/dashboard/analytics', feature: 'advanced_analytics', label: 'Analitik Lanjutan' },
  { prefix: '/dashboard/kitchen-stations', feature: 'kitchen_display', label: 'Kitchen Station' },
]

function getBlockedFeature(pathname: string, features: string[]): { feature: string; label: string } | null {
  for (const route of ROUTE_FEATURE_MAP) {
    if (pathname === route.prefix || pathname.startsWith(route.prefix + '/')) {
      if (!features.includes(route.feature)) {
        return { feature: route.feature, label: route.label }
      }
    }
  }
  return null
}

export default function DashboardLayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname()
  const router = useRouter()
  const { user, setUser, logout } = useAuthStore()
  const [sidebarOpen, setSidebarOpen] = useState(false)
  const [loading, setLoading] = useState(true)
  const [features, setFeatures] = useState<string[]>([])

  useEffect(() => {
    // Fetch auth and subscription in parallel
    const authPromise = fetch('/api/auth/me')
      .then(async (res) => {
        if (res.status === 403) {
          const data = await res.json()
          if (data.error === 'STORE_INACTIVE') {
            router.push('/store-inactive')
            return null
          }
        }
        return res.json()
      })
      .then(data => {
        if (!data) return null
        if (data.user) {
          setUser(data.user)
          return data.user
        } else {
          router.push('/login')
          return null
        }
      })
      .catch(() => {
        router.push('/login')
        return null
      })

    const subPromise = fetch('/api/tenant/subscription')
      .then(res => res.json())
      .then(data => {
        if (data.subscription?.plan?.features) {
          setFeatures(data.subscription.plan.features)
        } else {
          setFeatures(FREE_PLAN_FEATURES)
        }
      })
      .catch(() => setFeatures(FREE_PLAN_FEATURES))

    Promise.all([authPromise, subPromise]).finally(() => setLoading(false))
  }, [setUser, router])

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

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

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900">
      {/* Mobile sidebar overlay */}
      {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 dark:bg-gray-800 shadow-xl z-50">
            <SidebarContent pathname={pathname} user={user} features={features} onLogout={handleLogout} onClose={() => setSidebarOpen(false)} />
          </div>
        </div>
      )}

      {/* Desktop sidebar */}
      <div className="hidden lg:fixed lg:inset-y-0 lg:flex lg:w-64 lg:flex-col">
        <div className="flex flex-col h-full bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700">
          <SidebarContent pathname={pathname} user={user} features={features} onLogout={handleLogout} />
        </div>
      </div>

      {/* Main content */}
      <div className="lg:pl-64">
        {/* Top bar */}
        <header className="sticky top-0 z-30 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
          <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 dark:text-gray-400 dark:hover:text-gray-200">
              <Menu className="w-6 h-6" />
            </button>
            <div className="flex-1" />
            <div className="flex items-center gap-4">
              {(!user?.role || ['owner', 'admin', 'manager', 'chef'].includes(user.role)) && features.includes('kitchen_display') && (
                <Link href="/kitchen" className="btn-ghost text-sm flex items-center gap-1">
                  <ChefHat className="w-4 h-4" /> Kitchen
                </Link>
              )}
              {(!user?.role || ['owner', 'admin', 'manager', 'waiter'].includes(user.role)) && (
                <Link href="/waiter" className="btn-ghost text-sm flex items-center gap-1">
                  <User className="w-4 h-4" /> Waiter
                </Link>
              )}
              {(!user?.role || ['owner', 'admin', 'manager', 'cashier'].includes(user.role)) && features.includes('pos') && (
                <Link href="/pos" className="btn-primary text-sm">
                  Buka POS
                </Link>
              )}
              <div className="flex items-center gap-2">
                <div className="w-8 h-8 bg-primary-100 dark:bg-primary-900/30 rounded-full flex items-center justify-center text-primary-700 dark:text-primary-400 font-medium text-sm">
                  {user?.name?.charAt(0).toUpperCase()}
                </div>
                <span className="hidden sm:block text-sm font-medium text-gray-700 dark:text-gray-200">{user?.name}</span>
              </div>
            </div>
          </div>
        </header>

        <main className="p-4 sm:p-6 lg:p-8">
          {(() => {
            const blocked = getBlockedFeature(pathname, features)
            if (blocked) {
              return (
                <div className="flex items-center justify-center min-h-[60vh]">
                  <div className="text-center max-w-md mx-auto">
                    <div className="w-16 h-16 bg-orange-100 dark:bg-orange-900/30 rounded-full flex items-center justify-center mx-auto mb-4">
                      <Lock className="w-8 h-8 text-orange-500" />
                    </div>
                    <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-2">Fitur Tidak Tersedia</h2>
                    <p className="text-gray-600 dark:text-gray-300 mb-6">
                      Plan yang sedang berjalan tidak diizinkan mengakses fitur <strong>{blocked.label}</strong>. Silahkan upgrade untuk membuka fitur ini.
                    </p>
                    <Link
                      href="/dashboard/subscription"
                      className="inline-flex items-center gap-2 bg-primary-600 text-white px-6 py-3 rounded-lg font-medium hover:bg-primary-700 transition-colors"
                    >
                      <ArrowUpCircle className="w-5 h-5" />
                      Upgrade Plan
                    </Link>
                  </div>
                </div>
              )
            }
            return children
          })()}
        </main>
      </div>
    </div>
  )
}

function SidebarContent({ pathname, user, features, onLogout, onClose }: any) {
  const { theme, setTheme } = useTheme()
  const [mounted, setMounted] = useState(false)

  useEffect(() => setMounted(true), [])

  // Filter navigation based on user role
  const filteredNavigation = (() => {
    if (!user) return navigation
    const role = user.role
    if (role === 'waiter' || role === 'chef') {
      return navigation.filter(item => item.href === '/dashboard')
    }
    if (role === 'cashier') {
      return navigation.filter(item => ['/dashboard', '/dashboard/orders'].includes(item.href))
    }
    if (role === 'finance') {
      return navigation.filter(item => ['/dashboard', '/dashboard/orders', '/dashboard/reports', '/dashboard/expenses', '/dashboard/attendance'].includes(item.href))
    }
    // Hide settings, wallet and audit log from non-owner/admin roles
    if (!['owner', 'admin'].includes(role)) {
      return navigation.filter(item => item.href !== '/dashboard/settings' && item.href !== '/dashboard/wallet' && item.href !== '/dashboard/audit-log')
    }
    return navigation
  })()

  // Filter by subscription features
  const visibleNavigation = filteredNavigation.filter(item => {
    if (!item.feature) return true
    return features.includes(item.feature)
  })

  // Filter quick links based on role + features
  const filteredQuickLinks = (() => {
    if (!user) return quickLinks
    const role = user.role
    let links = quickLinks
    if (role === 'chef') links = quickLinks.filter(l => l.href === '/kitchen')
    else if (role === 'waiter') links = quickLinks.filter(l => l.href === '/waiter')
    else if (role === 'cashier' || role === 'finance') links = []
    // Filter by subscription features
    return links.filter(l => !l.feature || features.includes(l.feature))
  })()

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="flex items-center justify-between h-16 px-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
        <Link href="/dashboard" className="flex items-center gap-2">
          <UtensilsCrossed className="w-8 h-8 text-primary-600" />
          <span className="text-lg font-bold text-gray-900 dark:text-white">RestoMenu</span>
        </Link>
        {onClose && (
          <button onClick={onClose} className="lg:hidden text-gray-400 hover:text-gray-600 dark:hover:text-gray-200">
            <X className="w-5 h-5" />
          </button>
        )}
      </div>

      {/* Tenant info */}
      {user?.tenant && (
        <div className="px-4 py-3 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50 flex-shrink-0">
          <p className="text-sm font-medium text-gray-900 dark:text-white truncate">{user.tenant.name}</p>
          <p className="text-xs text-gray-500 dark:text-gray-400 capitalize">{user.role}</p>
        </div>
      )}

      {/* Scrollable area: nav + quick links */}
      <div className="flex-1 min-h-0 overflow-y-auto">
        <nav className="px-3 py-4 space-y-1">
          {visibleNavigation.map((item) => {
            const isActive = pathname === item.href || (item.href !== '/dashboard' && 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-primary-50 text-primary-700 dark:bg-primary-900/30 dark:text-primary-400'
                    : 'text-gray-600 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-700 dark:hover:text-white'
                }`}
              >
                <item.icon className={`w-5 h-5 ${isActive ? 'text-primary-600 dark:text-primary-400' : 'text-gray-400 dark:text-gray-500'}`} />
                {item.name}
              </Link>
            )
          })}
        </nav>

        {filteredQuickLinks.length > 0 && (
          <div className="px-3 pb-4 space-y-1">
            <p className="px-3 text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider mb-2">Quick Access</p>
            {filteredQuickLinks.map((item) => (
              <Link
                key={item.href}
                href={item.href}
                className="flex items-center gap-3 px-3 py-2 rounded-lg text-sm font-medium text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700 transition-colors"
              >
                <item.icon className={`w-5 h-5 ${item.color}`} />
                {item.name}
              </Link>
            ))}
          </div>
        )}
      </div>

      {/* Pinned footer: theme toggle + logout */}
      <div className="flex-shrink-0 border-t border-gray-200 dark:border-gray-700">
        {/* Theme toggle */}
        {mounted && (
          <div className="px-3 pt-3">
            <button
              onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
              className="flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700 w-full transition-colors"
            >
              {theme === 'dark' ? <Sun className="w-5 h-5 text-yellow-500" /> : <Moon className="w-5 h-5 text-gray-400" />}
              {theme === 'dark' ? 'Mode Terang' : 'Mode Gelap'}
            </button>
          </div>
        )}
        {/* Logout */}
        <div className="p-3">
          <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 dark:text-red-400 dark:hover:bg-red-900/20 w-full transition-colors"
          >
            <LogOut className="w-5 h-5" />
            Keluar
          </button>
        </div>
      </div>
    </div>
  )
}
