/**
 * GlobalTypographyPicker — font family picker with global token popover
 *
 * Replaces the standard font-family <Select> with a searchable combobox
 * that also shows a Globe icon for selecting global typography tokens.
 *
 * When a global token is active, the field shows the token name + font preview.
 * Users can still search and pick any font from the Google Fonts list.
 *
 * Works for both Free and Pro users:
 * - Free: standard font picker, no globe icon
 * - Pro:  picker + globe popover + global name display
 */

import { useState } from 'react'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover'
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '@/components/ui/command'
import { Globe, Check, ChevronsUpDown } from 'lucide-react'
import { cn } from '@/lib/utils'
import { usePro } from '@/contexts/pro-context'
import { fontFamilyOptions, getAllGoogleFontsPreviewUrls } from '@/lib/google-fonts'
import { GlobalTypography } from '@/features/globals/config'

interface GlobalTypographyPickerProps {
  /** Label shown above the picker */
  label: string
  /** Current font-family CSS value, e.g. "'Poppins', Arial, sans-serif" */
  value: string
  /** Called when the user picks a new font (full CSS font-family string) */
  onChange: (value: string) => void
  /** Which global typography token this maps to (e.g. 'headings', 'body') */
  globalTokenId?: string
  /** The feature's original hardcoded default (used to detect "unchanged") */
  featureDefault?: string
}

/**
 * Get the global typography tokens from the window data (passed from PHP).
 */
function getGlobalTypography(): GlobalTypography[] {
  const data = (window as any).swiftCommerceData
  return data?.globalStyles?.typography ?? []
}

/**
 * Find a global typography token by ID.
 */
function findGlobalById(id: string): GlobalTypography | undefined {
  return getGlobalTypography().find((t: GlobalTypography) => t.id === id)
}

/**
 * Find a global typography token by matching font-family value (case-insensitive).
 */
function findGlobalByFontFamily(fontFamily: string): GlobalTypography | undefined {
  if (!fontFamily || fontFamily === 'inherit') return undefined
  return getGlobalTypography().find(
    (t: GlobalTypography) => t.fontFamily.toLowerCase() === fontFamily.toLowerCase(),
  )
}

/**
 * Extract just the font name from a CSS font-family string for display.
 * e.g. "'Poppins', Arial, sans-serif" → "Poppins"
 */
function extractFontName(cssValue: string): string {
  if (!cssValue || cssValue === 'inherit') return 'Theme Default'
  const first = cssValue.split(',')[0].trim().replace(/['"]/g, '')
  return first || cssValue
}

export function GlobalTypographyPicker({
  label,
  value,
  onChange,
  globalTokenId,
  featureDefault,
}: GlobalTypographyPickerProps) {
  const { isPro } = usePro()
  const [fontOpen, setFontOpen] = useState(false)
  const [globeOpen, setGlobeOpen] = useState(false)

  const globalTokens = getGlobalTypography()
  const hasGlobals = isPro && globalTokens.length > 0

  // Resolve which global token is currently active
  const mappedToken = globalTokenId ? findGlobalById(globalTokenId) : undefined
  const matchedByValue = value ? findGlobalByFontFamily(value) : undefined

  const activeGlobal =
    matchedByValue ||
    (mappedToken &&
      (!value ||
        value === featureDefault ||
        value === 'inherit' ||
        value.toLowerCase() === mappedToken.fontFamily.toLowerCase())
      ? mappedToken
      : undefined)

  // Find the label for the current value from the options list
  const currentFontOption = fontFamilyOptions.find((f) => f.value === value)
  const displayName = activeGlobal
    ? activeGlobal.name
    : currentFontOption?.label || extractFontName(value)

  const handleSelectGlobal = (token: GlobalTypography) => {
    onChange(token.fontFamily)
    setGlobeOpen(false)
  }

  return (
    <div className="space-y-2">
      <Label>{label}</Label>

      {/* Google Fonts preview stylesheets (chunked) */}
      {getAllGoogleFontsPreviewUrls().map((url, i) => (
        <link key={i} rel="stylesheet" href={url} />
      ))}

      <div className="flex gap-2">
        {/* Font family combobox */}
        <Popover open={fontOpen} onOpenChange={setFontOpen}>
          <PopoverTrigger asChild>
            <Button
              variant="outline"
              role="combobox"
              aria-expanded={fontOpen}
              className={cn(
                'flex-1 justify-between h-10 font-normal',
                activeGlobal && 'pr-9',
              )}
              style={{
                fontFamily: value || 'inherit',
              }}
            >
              <span className="truncate">{displayName}</span>
              {activeGlobal && (
                <span className="text-[10px] text-muted-foreground font-mono ml-2 shrink-0" style={{ fontFamily: 'inherit' }}>
                  {extractFontName(activeGlobal.fontFamily)}
                </span>
              )}
              {!activeGlobal && (
                <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
              )}
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-64 p-0" align="start">
            <Command>
              <CommandInput placeholder="Search fonts..." />
              <CommandList>
                <CommandEmpty>No font found.</CommandEmpty>
                <CommandGroup>
                  {fontFamilyOptions.map((font) => (
                    <CommandItem
                      key={font.value}
                      value={font.label}
                      onSelect={() => {
                        onChange(font.value)
                        setFontOpen(false)
                      }}
                    >
                      <Check
                        className={cn(
                          'mr-2 h-4 w-4',
                          value === font.value ? 'opacity-100' : 'opacity-0',
                        )}
                      />
                      <span style={{ fontFamily: font.value }}>{font.label}</span>
                    </CommandItem>
                  ))}
                </CommandGroup>
              </CommandList>
            </Command>
          </PopoverContent>
        </Popover>

        {/* Globe icon — opens global typography popover */}
        {hasGlobals && (
          <Popover open={globeOpen} onOpenChange={setGlobeOpen}>
            <PopoverTrigger asChild>
              <button
                type="button"
                className="flex items-center justify-center w-10 h-10 rounded-md border border-input bg-background hover:bg-muted transition-colors shrink-0"
                title="Choose a global typography"
              >
                <Globe className="h-4 w-4" style={{ color: '#002269' }} />
              </button>
            </PopoverTrigger>
            <PopoverContent className="w-60 p-1.5" align="end" sideOffset={8}>
              <div className="space-y-0.5">
                <p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider px-2 py-1">
                  Global Typography
                </p>
                {globalTokens.map((gt: GlobalTypography) => {
                  const isActive = activeGlobal?.id === gt.id
                  return (
                    <button
                      key={gt.id}
                      type="button"
                      onClick={() => handleSelectGlobal(gt)}
                      className="flex items-center gap-2.5 w-full px-2 py-1.5 rounded-md text-left text-sm hover:bg-muted transition-colors"
                    >
                      {/* Font preview swatch */}
                      <span
                        className="h-7 w-7 rounded-md border border-border/60 bg-muted/50 flex items-center justify-center shrink-0 text-xs font-semibold"
                        style={{
                          fontFamily: gt.fontFamily || 'inherit',
                          fontWeight: Number(gt.fontWeight) || 400,
                        }}
                      >
                        Aa
                      </span>
                      <span className="flex-1 min-w-0">
                        <span className="block truncate text-sm font-medium">{gt.name}</span>
                        <span className="block truncate text-[10px] text-muted-foreground">
                          {extractFontName(gt.fontFamily)} · {gt.fontWeight}
                        </span>
                      </span>
                      {isActive && (
                        <Check className="h-3.5 w-3.5 shrink-0" style={{ color: '#002269' }} />
                      )}
                    </button>
                  )
                })}
                {/* Clear / use custom option */}
                {activeGlobal && (
                  <>
                    <div className="border-t my-1" />
                    <button
                      type="button"
                      onClick={() => {
                        onChange('inherit')
                        setGlobeOpen(false)
                      }}
                      className="flex items-center gap-2.5 w-full px-2 py-1.5 rounded-md text-left text-sm text-muted-foreground hover:bg-muted transition-colors"
                    >
                      <span className="h-7 w-7 rounded-md border border-dashed border-border/60 shrink-0 flex items-center justify-center text-[10px]">
                        Aa
                      </span>
                      <span className="flex-1">Use custom font</span>
                    </button>
                  </>
                )}
              </div>
            </PopoverContent>
          </Popover>
        )}
      </div>
    </div>
  )
}
