/**
 * Typography Editor — compact list item with inline expand-to-edit
 *
 * Shows font name + weight preview row by default.
 * Pencil icon appears on hover. Clicking the row expands the full editor inline.
 */

import { useState } from 'react'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover'
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '@/components/ui/command'
import { Check, ChevronsUpDown, Pencil, ChevronUp, Trash2 } from 'lucide-react'
import { cn } from '@/lib/utils'
import { fontFamilyOptions } from '@/lib/google-fonts'
import { getAllGoogleFontsPreviewUrls } from '@/lib/google-fonts'
import {
  GlobalTypography,
  fontWeightOptions,
  textTransformOptions,
} from '../config'

interface TypographyEditorProps {
  typography: GlobalTypography
  onChange: (updated: GlobalTypography) => void
  onDelete?: () => void
  isOpen?: boolean
  onToggle?: () => void
}

export function TypographyEditor({ typography, onChange, onDelete, isOpen, onToggle }: TypographyEditorProps) {
  const [fontOpen, setFontOpen] = useState(false)

  // Find current font label
  const currentFont = fontFamilyOptions.find((f) => f.value === typography.fontFamily)
  const weightLabel = fontWeightOptions.find((w) => w.value === typography.fontWeight)?.label ?? typography.fontWeight

  return (
    <div className={cn(
      'rounded-lg border transition-colors',
      isOpen ? 'bg-card border-border' : 'bg-card/50 hover:bg-card border-transparent hover:border-border'
    )}>
      {/* Google Fonts preview stylesheet */}
      {getAllGoogleFontsPreviewUrls().map((url, i) => (
        <link key={i} rel="stylesheet" href={url} />
      ))}

      {/* ── Compact row ── */}
      <button
        type="button"
        onClick={onToggle}
        className="flex items-center gap-3 w-full px-3 py-2.5 text-left group"
      >
        {/* Font preview letter */}
        <span
          className="h-7 w-7 rounded-md border border-border/60 bg-muted/50 flex items-center justify-center shrink-0 text-sm font-semibold"
          style={{
            fontFamily: typography.fontFamily || 'inherit',
            fontWeight: Number(typography.fontWeight) || 400,
          }}
        >
          Aa
        </span>
        {/* Name + font info */}
        <span className="flex-1 min-w-0">
          <span className="text-sm font-medium leading-tight block truncate">
            {typography.name}
          </span>
          <span className="text-[11px] text-muted-foreground leading-tight">
            {currentFont?.label || 'System'} · {weightLabel}
          </span>
        </span>
        {/* Pencil / Chevron icon */}
        {isOpen ? (
          <ChevronUp className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
        ) : (
          <Pencil className="h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity shrink-0" />
        )}
      </button>

      {/* ── Expanded editor ── */}
      {isOpen && (
        <div className="px-3 pb-3 space-y-3 border-t">
          {/* Name */}
          <div className="space-y-1.5 pt-3">
            <Label className="text-xs text-muted-foreground">Name</Label>
            <Input
              value={typography.name}
              onChange={(e) => onChange({ ...typography, name: e.target.value })}
              placeholder="Typography name"
              className="h-8 text-sm"
            />
          </div>

          {/* Font Family — searchable combobox */}
          <div className="space-y-1.5">
            <Label className="text-xs text-muted-foreground">Font Family</Label>
            <Popover open={fontOpen} onOpenChange={setFontOpen}>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  role="combobox"
                  aria-expanded={fontOpen}
                  className="w-full justify-between h-8 font-normal text-sm"
                  style={currentFont?.value ? { fontFamily: currentFont.value } : undefined}
                >
                  {currentFont?.label || 'Select font…'}
                  <ChevronsUpDown className="ml-2 h-3.5 w-3.5 shrink-0 opacity-50" />
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-[250px] p-0" align="start">
                <Command>
                  <CommandInput placeholder="Search fonts…" />
                  <CommandList>
                    <CommandEmpty>No font found.</CommandEmpty>
                    <CommandGroup>
                      {fontFamilyOptions.map((font) => (
                        <CommandItem
                          key={font.value || '__default'}
                          value={font.label}
                          onSelect={() => {
                            onChange({ ...typography, fontFamily: font.value })
                            setFontOpen(false)
                          }}
                          style={font.value ? { fontFamily: font.value } : undefined}
                        >
                          <Check
                            className={cn(
                              'mr-2 h-3.5 w-3.5',
                              typography.fontFamily === font.value ? 'opacity-100' : 'opacity-0',
                            )}
                          />
                          {font.label}
                        </CommandItem>
                      ))}
                    </CommandGroup>
                  </CommandList>
                </Command>
              </PopoverContent>
            </Popover>
          </div>

          {/* Weight + Size row */}
          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1.5">
              <Label className="text-xs text-muted-foreground">Weight</Label>
              <Select
                value={typography.fontWeight}
                onValueChange={(v) => onChange({ ...typography, fontWeight: v })}
              >
                <SelectTrigger className="h-8 text-sm">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {fontWeightOptions.map((w: { value: string; label: string }) => (
                    <SelectItem key={w.value} value={w.value}>
                      {w.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs text-muted-foreground">Size (px)</Label>
              <Input
                type="number"
                value={typography.fontSize}
                onChange={(e) => onChange({ ...typography, fontSize: e.target.value })}
                placeholder="Inherit"
                className="h-8 text-sm"
                min={8}
                max={96}
              />
            </div>
          </div>

          {/* Line Height + Letter Spacing row */}
          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1.5">
              <Label className="text-xs text-muted-foreground">Line Height</Label>
              <Input
                value={typography.lineHeight}
                onChange={(e) => onChange({ ...typography, lineHeight: e.target.value })}
                placeholder="1.5"
                className="h-8 text-sm"
              />
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs text-muted-foreground">Letter Spacing</Label>
              <Input
                value={typography.letterSpacing}
                onChange={(e) => onChange({ ...typography, letterSpacing: e.target.value })}
                placeholder="Normal"
                className="h-8 text-sm"
              />
            </div>
          </div>

          {/* Text Transform */}
          <div className="space-y-1.5">
            <Label className="text-xs text-muted-foreground">Transform</Label>
            <Select
              value={typography.textTransform}
              onValueChange={(v) =>
                onChange({ ...typography, textTransform: v as GlobalTypography['textTransform'] })
              }
            >
              <SelectTrigger className="h-8 text-sm">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {textTransformOptions.map((t: { value: string; label: string }) => (
                  <SelectItem key={t.value} value={t.value}>
                    {t.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* Delete (only for user-added tokens) */}
          {!typography.isDefault && onDelete && (
            <Button
              variant="ghost"
              size="sm"
              onClick={onDelete}
              className="text-destructive hover:text-destructive hover:bg-destructive/10 w-full justify-center gap-2 h-7 text-xs"
            >
              <Trash2 className="h-3 w-3" />
              Remove
            </Button>
          )}
        </div>
      )}
    </div>
  )
}
