/**
 * Globals Sidebar — sliding drill-down navigation for the Globals feature
 *
 * Rendered inside AppSidebar when currentPage === 'globals' && isPro.
 *
 * Three panels slide horizontally:
 *   Level 0 (home):       Colors & Typography nav items + info note
 *   Level 1 (colors):     Color token editors
 *   Level 1 (typography): Typography token editors
 *
 * A sticky footer with Save / Reset buttons is always visible.
 */

import { ScrollArea } from '@/components/ui/scroll-area'
import { Button } from '@/components/ui/button'
import {
  ArrowLeft,
  ChevronRight,
  Info,
  Loader2,
  Palette,
  Plus,
  RotateCcw,
  Save,
  Type,
} from 'lucide-react'
import { useState } from 'react'
import { cn } from '@/lib/utils'
import { useGlobalsContext } from '../contexts/globals-context'
import { useNavigation } from '@/contexts/navigation-context'
import { GlobalColor, GlobalTypography } from '../config'
import { ColorEditor } from './color-editor'
import { TypographyEditor } from './typography-editor'
import { toast } from 'sonner'
import {
  SidebarGroup,
  SidebarGroupLabel,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
} from '@/components/ui/sidebar'

/* ── Helpers ──────────────────────────────────────────────── */

function slugify(name: string): string {
  return (
    name
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/^-|-$/g, '') || `token-${Date.now()}`
  )
}

/* ── Component ────────────────────────────────────────────── */

export function GlobalsSidebar() {
  const { navigateTo } = useNavigation()
  const {
    settings,
    loading,
    setSettings,
    saving,
    hasChanges,
    saveSettings,
    resetToDefaults,
    globalsView,
    setGlobalsView,
  } = useGlobalsContext()

  // Track which single item is expanded (accordion-style, one at a time)
  const [expandedItem, setExpandedItem] = useState<string | null>(null)
  const toggleItem = (id: string) => setExpandedItem((prev) => (prev === id ? null : id))

  /* ── CRUD — Colors ──────────────────────────────────── */

  const updateColor = (index: number, updated: GlobalColor) => {
    const next = [...settings.colors]
    next[index] = updated
    setSettings({ ...settings, colors: next })
  }

  const addColor = () => {
    const newColor: GlobalColor = {
      id: slugify(`custom-${settings.colors.length + 1}`),
      name: `Custom ${settings.colors.length + 1}`,
      value: '#6366f1',
      isDefault: false,
    }
    setSettings({ ...settings, colors: [...settings.colors, newColor] })
  }

  const deleteColor = (index: number) => {
    const next = settings.colors.filter((_: GlobalColor, i: number) => i !== index)
    setSettings({ ...settings, colors: next })
  }

  /* ── CRUD — Typography ──────────────────────────────── */

  const updateTypography = (index: number, updated: GlobalTypography) => {
    const next = [...settings.typography]
    next[index] = updated
    setSettings({ ...settings, typography: next })
  }

  const addTypography = () => {
    const newTypo: GlobalTypography = {
      id: slugify(`custom-font-${settings.typography.length + 1}`),
      name: `Custom Font ${settings.typography.length + 1}`,
      fontFamily: '',
      fontWeight: '400',
      fontSize: '',
      lineHeight: '',
      letterSpacing: '',
      textTransform: 'none',
      isDefault: false,
    }
    setSettings({ ...settings, typography: [...settings.typography, newTypo] })
  }

  const deleteTypography = (index: number) => {
    const next = settings.typography.filter(
      (_: GlobalTypography, i: number) => i !== index,
    )
    setSettings({ ...settings, typography: next })
  }

  /* ── Actions ────────────────────────────────────────── */

  const handleSave = async () => {
    const ok = await saveSettings()
    if (ok) toast.success('Global styles saved')
    else toast.error('Failed to save')
  }

  const handleReset = () => {
    resetToDefaults()
    toast.info('Reset to defaults — save to apply')
  }

  /* ── Loading skeleton ───────────────────────────────── */

  if (loading) {
    return (
      <div className="flex flex-col flex-1 min-h-0 p-4 space-y-4">
        {[...Array(5)].map((_, i: number) => (
          <div key={i} className="animate-pulse space-y-2">
            <div className="h-3 bg-sidebar-accent rounded w-2/3" />
            <div className="h-9 bg-sidebar-accent rounded" />
          </div>
        ))}
      </div>
    )
  }

  /* ── Render ─────────────────────────────────────────── */

  return (
    <div className="flex flex-col flex-1 min-h-0">
      {/* ── Sliding panels ─────────────────────────────── */}
      <div className="relative flex-1 min-h-0 overflow-hidden">
        {/* ▸ Panel 0 — Home */}
        <div
          className={cn(
            'absolute inset-0 flex flex-col transition-transform duration-300 ease-in-out',
            globalsView === 'home' ? 'translate-x-0' : '-translate-x-full',
          )}
        >
          {/* Back to dashboard */}
          <div className="px-4 pt-3 pb-1">
            <button
              onClick={() => navigateTo('dashboard')}
              className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors"
            >
              <ArrowLeft className="h-3 w-3" />
              Back to Dashboard
            </button>
          </div>

          {/* Info note */}
          <div className="px-3 py-3">
            <div className="rounded-lg bg-[#00226b]/[0.06] border border-[#00226b]/10 p-3">
              <div className="flex gap-2.5">
                <Info className="h-4 w-4 shrink-0 mt-0.5" style={{ color: '#00226b' }} />
                <p className="text-[11px] leading-relaxed text-muted-foreground">
                  Control your global design tokens from here.
                  Changes apply across all Swift Commerce features.
                </p>
              </div>
            </div>
          </div>

          {/* Nav items */}
          <SidebarGroup>
            <SidebarGroupLabel>Design Tokens</SidebarGroupLabel>
            <SidebarMenu>
              <SidebarMenuItem>
                <SidebarMenuButton
                  onClick={() => setGlobalsView('colors')}
                  className="cursor-pointer"
                >
                  <Palette className="h-4 w-4" />
                  <span className="flex-1">Colors</span>
                  <span className="text-[11px] text-muted-foreground tabular-nums">
                    {settings.colors.length}
                  </span>
                  <ChevronRight className="h-3.5 w-3.5 text-muted-foreground" />
                </SidebarMenuButton>
              </SidebarMenuItem>
              <SidebarMenuItem>
                <SidebarMenuButton
                  onClick={() => setGlobalsView('typography')}
                  className="cursor-pointer"
                >
                  <Type className="h-4 w-4" />
                  <span className="flex-1">Typography</span>
                  <span className="text-[11px] text-muted-foreground tabular-nums">
                    {settings.typography.length}
                  </span>
                  <ChevronRight className="h-3.5 w-3.5 text-muted-foreground" />
                </SidebarMenuButton>
              </SidebarMenuItem>
            </SidebarMenu>
          </SidebarGroup>
        </div>

        {/* ▸ Panel 1a — Colors */}
        <div
          className={cn(
            'absolute inset-0 flex flex-col transition-transform duration-300 ease-in-out',
            globalsView === 'colors' ? 'translate-x-0' : 'translate-x-full',
          )}
        >
          <div className="px-4 pt-3 pb-2 shrink-0">
            <button
              onClick={() => setGlobalsView('home')}
              className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors"
            >
              <ArrowLeft className="h-3 w-3" />
              <Palette className="h-3.5 w-3.5" />
              Colors
            </button>
          </div>
          <ScrollArea className="flex-1 min-h-0">
            <div className="space-y-1 px-3 pb-3">
              {settings.colors.map((color: GlobalColor, index: number) => (
                <ColorEditor
                  key={color.id}
                  color={color}
                  onChange={(updated: GlobalColor) => updateColor(index, updated)}
                  onDelete={
                    !color.isDefault ? () => deleteColor(index) : undefined
                  }
                  isOpen={expandedItem === `color-${color.id}`}
                  onToggle={() => toggleItem(`color-${color.id}`)}
                />
              ))}
              <Button
                variant="outline"
                size="sm"
                onClick={addColor}
                className="w-full gap-2"
              >
                <Plus className="h-3.5 w-3.5" />
                Add Color
              </Button>
            </div>
          </ScrollArea>
        </div>

        {/* ▸ Panel 1b — Typography */}
        <div
          className={cn(
            'absolute inset-0 flex flex-col transition-transform duration-300 ease-in-out',
            globalsView === 'typography' ? 'translate-x-0' : 'translate-x-full',
          )}
        >
          <div className="px-4 pt-3 pb-2 shrink-0">
            <button
              onClick={() => setGlobalsView('home')}
              className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors"
            >
              <ArrowLeft className="h-3 w-3" />
              <Type className="h-3.5 w-3.5" />
              Typography
            </button>
          </div>
          <ScrollArea className="flex-1 min-h-0">
            <div className="space-y-1 px-3 pb-3">
              {settings.typography.map(
                (typo: GlobalTypography, index: number) => (
                  <TypographyEditor
                    key={typo.id}
                    typography={typo}
                    onChange={(updated: GlobalTypography) =>
                      updateTypography(index, updated)
                    }
                    onDelete={
                      !typo.isDefault
                        ? () => deleteTypography(index)
                        : undefined
                    }
                    isOpen={expandedItem === `typo-${typo.id}`}
                    onToggle={() => toggleItem(`typo-${typo.id}`)}
                  />
                ),
              )}
              <Button
                variant="outline"
                size="sm"
                onClick={addTypography}
                className="w-full gap-2"
              >
                <Plus className="h-3.5 w-3.5" />
                Add Typography
              </Button>
            </div>
          </ScrollArea>
        </div>
      </div>

      {/* ── Save / Reset footer ────────────────────────── */}
      <div className="shrink-0 border-t p-3 space-y-2 bg-sidebar">
        <Button
          size="sm"
          onClick={handleSave}
          disabled={!hasChanges || saving}
          className="w-full gap-1.5"
          style={{
            backgroundColor: hasChanges ? '#00226b' : undefined,
            borderColor: hasChanges ? '#00226b' : undefined,
          }}
        >
          {saving ? (
            <Loader2 className="h-3.5 w-3.5 animate-spin" />
          ) : (
            <Save className="h-3.5 w-3.5" />
          )}
          {saving ? 'Saving…' : 'Save Changes'}
        </Button>
        <Button
          variant="ghost"
          size="sm"
          onClick={handleReset}
          className="w-full gap-1.5 text-muted-foreground"
        >
          <RotateCcw className="h-3.5 w-3.5" />
          Reset to Defaults
        </Button>
      </div>
    </div>
  )
}
