'use client'

import { useState } from 'react'
import { useAppStore, type AppView } from '@/store/app-store'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Separator } from '@/components/ui/separator'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
  Sheet,
  SheetContent,
  SheetTrigger,
  SheetTitle,
} from '@/components/ui/sheet'
import {
  LayoutDashboard,
  Users,
  Package,
  Receipt,
  FileText,
  CreditCard,
  HelpCircle,
  UserCog,
  MapPin,
  Wifi,
  Server,
  BarChart3,
  Settings,
  ScrollText,
  MessageSquare,
  User,
  Menu,
  Moon,
  Sun,
  LogOut,
  ChevronLeft,
  Globe,
} from 'lucide-react'
import DashboardView from '@/views/dashboard-view'
import ClientsView from '@/views/clients-view'
import PlansView from '@/views/plans-view'
import BillingView from '@/views/billing-view'
import InvoicesView from '@/views/invoices-view'
import PaymentsView from '@/views/payments-view'
import TicketsView from '@/views/tickets-view'
import ResellersView from '@/views/resellers-view'
import AreasView from '@/views/areas-view'
import ONUView from '@/views/onu-view'
import OLTView from '@/views/olt-view'
import ReportsView from '@/views/reports-view'
import LogsView from '@/views/logs-view'
import WhatsAppView from '@/views/whatsapp-view'
import SettingsView from '@/views/settings-view'
import UserPortalView from '@/views/user-portal-view'

const NAV_ITEMS: { view: AppView; label: string; icon: React.ElementType; group: string }[] = [
  { view: 'dashboard', label: 'Dashboard', icon: LayoutDashboard, group: 'Main' },
  { view: 'clients', label: 'Clients', icon: Users, group: 'Main' },
  { view: 'plans', label: 'Plans', icon: Package, group: 'Main' },
  { view: 'billing', label: 'Billing', icon: Receipt, group: 'Main' },
  { view: 'invoices', label: 'Invoices', icon: FileText, group: 'Finance' },
  { view: 'payments', label: 'Payments', icon: CreditCard, group: 'Finance' },
  { view: 'resellers', label: 'Resellers', icon: UserCog, group: 'Finance' },
  { view: 'reports', label: 'Reports', icon: BarChart3, group: 'Finance' },
  { view: 'tickets', label: 'Support Tickets', icon: HelpCircle, group: 'Support' },
  { view: 'whatsapp', label: 'WhatsApp', icon: MessageSquare, group: 'Support' },
  { view: 'logs', label: 'Activity Logs', icon: ScrollText, group: 'System' },
  { view: 'areas', label: 'Areas', icon: MapPin, group: 'Network' },
  { view: 'onu', label: 'ONU Management', icon: Wifi, group: 'Network' },
  { view: 'olt', label: 'OLT Devices', icon: Server, group: 'Network' },
  { view: 'settings', label: 'Settings', icon: Settings, group: 'System' },
  { view: 'user-portal', label: 'User Portal', icon: User, group: 'System' },
]

const GROUPS = ['Main', 'Finance', 'Support', 'Network', 'System']

function ViewRouter({ view }: { view: AppView }) {
  switch (view) {
    case 'dashboard': return <DashboardView />
    case 'clients': return <ClientsView />
    case 'plans': return <PlansView />
    case 'billing': return <BillingView />
    case 'invoices': return <InvoicesView />
    case 'payments': return <PaymentsView />
    case 'tickets': return <TicketsView />
    case 'resellers': return <ResellersView />
    case 'areas': return <AreasView />
    case 'onu': return <ONUView />
    case 'olt': return <OLTView />
    case 'reports': return <ReportsView />
    case 'logs': return <LogsView />
    case 'whatsapp': return <WhatsAppView />
    case 'settings': return <SettingsView />
    case 'user-portal': return <UserPortalView />
    default: return <DashboardView />
  }
}

function SidebarNav({
  collapsed,
  onNavigate,
}: {
  collapsed: boolean
  onNavigate?: () => void
}) {
  const { currentView, setCurrentView } = useAppStore()

  const grouped = GROUPS.map((group) => ({
    group,
    items: NAV_ITEMS.filter((item) => item.group === group),
  })).filter((g) => g.items.length > 0)

  return (
    <div className="flex flex-col h-full">
      {/* Brand */}
      <div className={cn('flex items-center gap-3 px-4 h-14 border-b shrink-0', collapsed && 'justify-center px-2')}>
        <div className="flex size-8 items-center justify-center rounded-lg bg-primary text-primary-foreground shrink-0">
          <Globe className="size-4" />
        </div>
        {!collapsed && (
          <div className="min-w-0">
            <p className="text-sm font-bold tracking-tight truncate">ISP Billing Pro</p>
            <p className="text-[10px] text-muted-foreground truncate">Enterprise Management</p>
          </div>
        )}
      </div>

      {/* Navigation */}
      <ScrollArea className="flex-1 py-2">
        <div className="space-y-1 px-2">
          {grouped.map(({ group, items }) => (
            <div key={group} className="mb-3">
              {!collapsed && (
                <p className="px-3 py-1.5 text-[10px] font-semibold text-muted-foreground uppercase tracking-wider">
                  {group}
                </p>
              )}
              {items.map((item) => {
                const isActive = currentView === item.view
                return (
                  <Button
                    key={item.view}
                    variant={isActive ? 'secondary' : 'ghost'}
                    className={cn(
                      'w-full justify-start gap-3 h-9 text-sm font-normal',
                      isActive && 'bg-primary/10 text-primary font-medium',
                      collapsed && 'justify-center px-2'
                    )}
                    onClick={() => {
                      setCurrentView(item.view)
                      onNavigate?.()
                    }}
                  >
                    <item.icon className={cn('size-4 shrink-0', isActive && 'text-primary')} />
                    {!collapsed && <span className="truncate">{item.label}</span>}
                  </Button>
                )
              })}
            </div>
          ))}
        </div>
      </ScrollArea>
    </div>
  )
}

export function AppShell() {
  const { currentView, currentUser, logout, sidebarOpen, setSidebarOpen, toggleTheme, theme } = useAppStore()
  const [mobileOpen, setMobileOpen] = useState(false)

  const currentPage = NAV_ITEMS.find((item) => item.view === currentView)

  return (
    <div className="flex h-screen overflow-hidden bg-background">
      {/* Desktop Sidebar */}
      <aside
        className={cn(
          'hidden lg:flex flex-col border-r bg-card transition-all duration-300 shrink-0',
          sidebarOpen ? 'w-60' : 'w-16'
        )}
      >
        <SidebarNav collapsed={!sidebarOpen} />
      </aside>

      {/* Mobile Sidebar */}
      <Sheet open={mobileOpen} onOpenChange={setMobileOpen}>
        <SheetContent side="left" className="w-64 p-0">
          <SheetTitle className="sr-only">Navigation</SheetTitle>
          <SidebarNav collapsed={false} onNavigate={() => setMobileOpen(false)} />
        </SheetContent>
      </Sheet>

      {/* Main Area */}
      <div className="flex flex-col flex-1 min-w-0">
        {/* Header */}
        <header className="flex items-center gap-3 h-14 px-4 border-b bg-card/50 backdrop-blur-sm shrink-0">
          {/* Mobile Menu */}
          <Button
            variant="ghost"
            size="icon"
            className="lg:hidden"
            onClick={() => setMobileOpen(true)}
          >
            <Menu className="size-5" />
          </Button>

          {/* Sidebar Toggle */}
          <Button
            variant="ghost"
            size="icon"
            className="hidden lg:flex"
            onClick={() => setSidebarOpen(!sidebarOpen)}
          >
            <ChevronLeft className={cn('size-4 transition-transform', !sidebarOpen && 'rotate-180')} />
          </Button>

          {/* Page Title */}
          <div className="flex items-center gap-2 min-w-0">
            {currentPage && <currentPage.icon className="size-4 text-muted-foreground shrink-0" />}
            <h1 className="text-sm font-semibold truncate">{currentPage?.label || 'Dashboard'}</h1>
          </div>

          <div className="flex-1" />

          {/* Theme Toggle */}
          <Button variant="ghost" size="icon" onClick={toggleTheme} className="shrink-0">
            {theme === 'light' ? <Moon className="size-4" /> : <Sun className="size-4" />}
          </Button>

          {/* User Menu */}
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" className="gap-2 h-8 px-2">
                <Avatar className="size-6">
                  <AvatarFallback className="text-xs bg-primary text-primary-foreground">
                    {currentUser?.name?.charAt(0)?.toUpperCase() || 'A'}
                  </AvatarFallback>
                </Avatar>
                <span className="hidden sm:inline text-sm font-medium truncate max-w-[120px]">
                  {currentUser?.name || 'Admin'}
                </span>
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-56">
              <DropdownMenuLabel>
                <div className="flex flex-col space-y-1">
                  <p className="text-sm font-medium">{currentUser?.name}</p>
                  <p className="text-xs text-muted-foreground">{currentUser?.email}</p>
                </div>
              </DropdownMenuLabel>
              <DropdownMenuSeparator />
              <DropdownMenuItem onClick={() => setCurrentView('settings')}>
                <Settings className="size-4 mr-2" />
                Settings
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => setCurrentView('user-portal')}>
                <User className="size-4 mr-2" />
                User Portal
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem onClick={logout} className="text-destructive focus:text-destructive">
                <LogOut className="size-4 mr-2" />
                Sign Out
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </header>

        {/* Page Content */}
        <main className="flex-1 overflow-auto">
          <ViewRouter view={currentView} />
        </main>
      </div>
    </div>
  )
}
