'use client'
import { usePathname, useParams, useRouter } from 'next/navigation'
import Box from '@mui/material/Box'
import Drawer from '@mui/material/Drawer'
import List from '@mui/material/List'
import ListItem from '@mui/material/ListItem'
import ListItemButton from '@mui/material/ListItemButton'
import ListItemIcon from '@mui/material/ListItemIcon'
import ListItemText from '@mui/material/ListItemText'
import Typography from '@mui/material/Typography'
import Divider from '@mui/material/Divider'
import Avatar from '@mui/material/Avatar'
import IconButton from '@mui/material/IconButton'
import Tooltip from '@mui/material/Tooltip'
import Button from '@mui/material/Button'
import Menu from '@mui/material/Menu'
import MenuItem from '@mui/material/MenuItem'
import useMediaQuery from '@mui/material/useMediaQuery'
import { useTheme } from '@mui/material/styles'
import { useState } from 'react'
import { useThemeMode } from '@/contexts/ThemeMode'
import { LangProvider, useT } from '@/contexts/LangContext'

const DRAWER_WIDTH = 240

const NAV_ITEMS: { key: 'dashboard' | 'clients' | 'matters' | 'annualCompliance' | 'calendar' | 'documents' | 'billing' | 'communications' | 'agentActivity' | 'compare' | 'migrate' | 'formTemplates' | 'workflows'; icon: string; path: string }[] = [
  { key: 'dashboard',        icon: 'ri-layout-grid-line',         path: 'dashboard' },
  { key: 'clients',          icon: 'ri-folder-user-line',         path: 'clients' },
  { key: 'matters',          icon: 'ri-briefcase-line',           path: 'matters' },
  { key: 'annualCompliance', icon: 'ri-building-2-line',          path: 'annual-compliance' },
  { key: 'calendar',         icon: 'ri-calendar-line',            path: 'calendar' },
  { key: 'documents',        icon: 'ri-file-text-line',           path: 'documents' },
  { key: 'billing',          icon: 'ri-money-dollar-circle-line', path: 'billing' },
  { key: 'communications',   icon: 'ri-chat-3-line',              path: 'comms' },
  { key: 'workflows',        icon: 'ri-list-check-3',             path: 'workflows' },
  { key: 'formTemplates',    icon: 'ri-file-edit-line',           path: 'form-templates' },
  { key: 'agentActivity',    icon: 'ri-robot-line',               path: 'agent-activity' },
  { key: 'compare',          icon: 'ri-bar-chart-horizontal-line',path: 'compare' },
  { key: 'migrate',          icon: 'ri-arrow-left-right-line',    path: 'migrate' },
]

const LANGUAGES = [
  { code: 'en', label: 'English', flag: '🇬🇧' },
  { code: 'th', label: 'ภาษาไทย', flag: '🇹🇭' },
]

const CURRENT_USER = { name: 'Patchara S.', initials: 'PS', role: 'Managing Attorney' }

function SidebarContents({ lang, pathname, mode, onNavClick }: {
  lang: string
  pathname: string
  mode: string
  onNavClick?: () => void
}) {
  const t = useT()
  return (
    <>
      {/* Logo */}
      <Box sx={{ p: 3, pb: 2 }}>
        <Typography variant='h6' sx={{ color: '#0D9394', fontWeight: 700, letterSpacing: '-0.5px' }}>
          {t.nav.firmName}
        </Typography>
        <Typography variant='caption' sx={{ color: mode === 'dark' ? 'rgba(255,255,255,0.4)' : 'rgba(47,51,73,0.45)' }}>
          Practice Management
        </Typography>
      </Box>

      <Divider sx={{ borderColor: mode === 'dark' ? 'rgba(255,255,255,0.08)' : 'rgba(47,51,73,0.1)', mx: 2 }} />

      {/* Nav items */}
      <List sx={{ px: 1.5, pt: 1.5, flex: 1 }}>
        {NAV_ITEMS.map(item => {
          const active = pathname.includes(`/${item.path}`)
          return (
            <ListItem key={item.key} disablePadding sx={{ mb: 0.5 }}>
              <ListItemButton href={`/${lang}/${item.path}`} selected={active} onClick={onNavClick} sx={{
                borderRadius: '8px',
                '&.Mui-selected': { bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } },
                '&:hover': { bgcolor: mode === 'dark' ? 'rgba(255,255,255,0.06)' : 'rgba(13,147,148,0.08)' },
                py: 1,
              }}>
                <ListItemIcon sx={{ minWidth: 36 }}>
                  <i className={item.icon} style={{
                    fontSize: '1.1rem',
                    color: active ? '#fff' : mode === 'dark' ? 'rgba(255,255,255,0.55)' : 'rgba(47,51,73,0.5)',
                  }} />
                </ListItemIcon>
                <ListItemText primary={t.nav[item.key]} sx={{
                  '& .MuiListItemText-primary': {
                    fontSize: '0.875rem', fontWeight: active ? 600 : 400,
                    color: active ? '#fff' : mode === 'dark' ? 'rgba(255,255,255,0.65)' : 'rgba(47,51,73,0.75)',
                  },
                }} />
              </ListItemButton>
            </ListItem>
          )
        })}
      </List>

      <Divider sx={{ borderColor: mode === 'dark' ? 'rgba(255,255,255,0.08)' : 'rgba(47,51,73,0.1)', mx: 2 }} />

      {/* User profile */}
      <Box sx={{ p: 2, display: 'flex', alignItems: 'center', gap: 1.5 }}>
        <Avatar sx={{ bgcolor: '#0D9394', width: 36, height: 36, fontSize: '0.85rem' }}>
          {CURRENT_USER.initials}
        </Avatar>
        <Box>
          <Typography variant='body2' sx={{ color: mode === 'dark' ? '#fff' : '#2F3349', fontWeight: 600, lineHeight: 1.2 }}>
            {CURRENT_USER.name}
          </Typography>
          <Typography variant='caption' sx={{ color: mode === 'dark' ? 'rgba(255,255,255,0.4)' : 'rgba(47,51,73,0.5)' }}>
            {CURRENT_USER.role}
          </Typography>
        </Box>
      </Box>
    </>
  )
}

function LayoutInner({ children }: { children: React.ReactNode }) {
  const pathname  = usePathname()
  const params    = useParams()
  const router    = useRouter()
  const lang      = (params?.lang as string) ?? 'en'
  const t         = useT()
  const { mode, toggle } = useThemeMode()
  const theme     = useTheme()
  const isMobile  = useMediaQuery(theme.breakpoints.down('md'))
  const [mobileOpen, setMobileOpen] = useState(false)
  const [langAnchor, setLangAnchor] = useState<null | HTMLElement>(null)

  const switchLang = (code: string) => {
    setLangAnchor(null)
    const newPath = pathname.replace(/^\/[a-z]{2}/, `/${code}`)
    router.push(newPath)
  }

  const currentLang = LANGUAGES.find(l => l.code === lang) ?? LANGUAGES[0]

  const drawerSx = {
    '& .MuiDrawer-paper': {
      width: DRAWER_WIDTH, boxSizing: 'border-box', border: 'none',
      bgcolor: mode === 'dark' ? '#1A1F36' : '#FFFFFF',
      color:   mode === 'dark' ? '#fff' : '#2F3349',
      borderRight: mode === 'light' ? '1px solid #DDE1F5' : 'none',
      display: 'flex', flexDirection: 'column',
    },
  }

  return (
    <Box sx={{ display: 'flex', minHeight: '100vh' }}>

      {/* ── Sidebar — permanent on desktop ── */}
      {!isMobile && (
        <Drawer variant='permanent' sx={{ width: DRAWER_WIDTH, flexShrink: 0, ...drawerSx }}>
          <SidebarContents lang={lang} pathname={pathname} mode={mode} />
        </Drawer>
      )}

      {/* ── Sidebar — temporary on mobile ── */}
      {isMobile && (
        <Drawer variant='temporary' open={mobileOpen} onClose={() => setMobileOpen(false)}
          ModalProps={{ keepMounted: true }} sx={{ ...drawerSx }}>
          <SidebarContents lang={lang} pathname={pathname} mode={mode} onNavClick={() => setMobileOpen(false)} />
        </Drawer>
      )}

      {/* ── Main column ── */}
      <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: '100vh', bgcolor: 'background.default', minWidth: 0 }}>

        {/* Top bar */}
        <Box component='header' sx={{
          display: 'flex', alignItems: 'center',
          px: { xs: 1.5, md: 3 }, height: 56, gap: 1,
          bgcolor: 'background.paper',
          borderBottom: '1px solid', borderColor: 'divider',
          flexShrink: 0,
        }}>
          {/* Hamburger — mobile only */}
          {isMobile && (
            <IconButton onClick={() => setMobileOpen(true)} size='small' sx={{ color: 'text.secondary', mr: 0.5 }}>
              <i className='ri-menu-line' style={{ fontSize: '1.3rem' }} />
            </IconButton>
          )}

          {/* Page title on mobile */}
          {isMobile && (
            <Typography variant='subtitle2' sx={{ fontWeight: 700, color: '#0D9394', flex: 1 }}>
              {t.nav.firmName}
            </Typography>
          )}

          <Box sx={{ ml: 'auto', display: 'flex', alignItems: 'center', gap: 1 }}>
            {/* Language switcher */}
            <Button size='small' onClick={e => setLangAnchor(e.currentTarget)}
              sx={{ fontSize: '0.78rem', color: 'text.secondary', minWidth: 0, gap: 0.5, px: 1 }}>
              <span style={{ fontSize: '1rem' }}>{currentLang.flag}</span>
              <span>{currentLang.code.toUpperCase()}</span>
              <i className='ri-arrow-down-s-line' style={{ fontSize: '0.85rem' }} />
            </Button>
            <Menu anchorEl={langAnchor} open={Boolean(langAnchor)} onClose={() => setLangAnchor(null)}
              anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
              transformOrigin={{ vertical: 'top', horizontal: 'right' }}>
              {LANGUAGES.map(l => (
                <MenuItem key={l.code} selected={l.code === lang} onClick={() => switchLang(l.code)}
                  sx={{ gap: 1, fontSize: '0.85rem', minWidth: 130 }}>
                  <span style={{ fontSize: '1rem' }}>{l.flag}</span>
                  <span>{l.label}</span>
                </MenuItem>
              ))}
            </Menu>

            {/* Dark / light toggle */}
            <Tooltip title={mode === 'dark' ? t.nav.lightMode : t.nav.darkMode}>
              <IconButton onClick={toggle} size='small' sx={{ color: 'text.secondary' }}>
                <i className={mode === 'dark' ? 'ri-sun-line' : 'ri-moon-line'} style={{ fontSize: '1.1rem' }} />
              </IconButton>
            </Tooltip>

            {/* User avatar */}
            <Tooltip title={`${CURRENT_USER.name} · ${CURRENT_USER.role}`}>
              <Avatar sx={{ bgcolor: '#0D9394', width: 32, height: 32, fontSize: '0.78rem', cursor: 'default' }}>
                {CURRENT_USER.initials}
              </Avatar>
            </Tooltip>
          </Box>
        </Box>

        {/* Page content */}
        <Box component='main' sx={{ flex: 1, p: { xs: 2, md: 3 } }}>
          {children}
        </Box>

      </Box>
    </Box>
  )
}

export default function DashboardLayout({ children }: { children: React.ReactNode }) {
  const params = useParams()
  const lang   = (params?.lang as string) ?? 'en'

  return (
    <LangProvider lang={lang}>
      <LayoutInner>{children}</LayoutInner>
    </LangProvider>
  )
}
