'use client';

import { Check, ChevronDown, Copy } from 'lucide-react';
import { useId, useState } from 'react';
import { toast } from 'sonner';
import { useTranslations } from '@/components/locale-provider';
import { Button } from '@/components/ui/button';
import {
  PLACEHOLDER_PRESETS,
  type PlaceholderDefinition,
  type PlaceholderPresetId
} from '@/lib/placeholder-presets';
import { cn } from '@/lib/utils';

interface PlaceholderHelpProps {
  preset: PlaceholderPresetId;
  /** Optional extra tokens for one-off fields. */
  extra?: PlaceholderDefinition[];
  className?: string;
  /** Start expanded (default: collapsed). */
  defaultOpen?: boolean;
}

export function PlaceholderHelp({
  preset,
  extra = [],
  className,
  defaultOpen = false
}: PlaceholderHelpProps) {
  const t = useTranslations();
  const panelId = useId();
  const [open, setOpen] = useState(defaultOpen);
  const [copiedToken, setCopiedToken] = useState<string | null>(null);

  const items = [...PLACEHOLDER_PRESETS[preset], ...extra];
  if (items.length === 0) {
    return null;
  }

  async function copyToken(token: string) {
    try {
      await navigator.clipboard.writeText(token);
      setCopiedToken(token);
      toast.success(t('placeholders.copied'));
      window.setTimeout(() => setCopiedToken((current) => (current === token ? null : current)), 1500);
    } catch {
      toast.error(t('placeholders.copyFailed'));
    }
  }

  return (
    <div className={cn('rounded-md border border-border bg-muted/30', className)}>
      <button
        type="button"
        className="flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-xs font-medium text-muted-foreground hover:text-foreground"
        aria-expanded={open}
        aria-controls={panelId}
        onClick={() => setOpen((prev) => !prev)}
      >
        <span>{t('placeholders.toggle')}</span>
        <ChevronDown className={cn('size-4 shrink-0 transition-transform', open && 'rotate-180')} />
      </button>
      {open ? (
        <div id={panelId} className="space-y-2 border-t border-border px-3 py-2">
          <p className="text-xs text-muted-foreground">{t('placeholders.hint')}</p>
          <ul className="space-y-1.5">
            {items.map((item) => {
              const isCopied = copiedToken === item.token;
              return (
                <li
                  key={item.token}
                  className="flex items-start gap-2 rounded-md border border-transparent px-1 py-0.5 hover:border-border hover:bg-background/60"
                >
                  <div className="min-w-0 flex-1">
                    <code className="break-all font-mono text-xs text-foreground">{item.token}</code>
                    <p className="text-[11px] leading-snug text-muted-foreground">{t(item.descriptionKey)}</p>
                  </div>
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    className="size-7 shrink-0"
                    aria-label={t('placeholders.copy')}
                    onClick={() => void copyToken(item.token)}
                  >
                    {isCopied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}
                  </Button>
                </li>
              );
            })}
          </ul>
        </div>
      ) : null}
    </div>
  );
}
