import { AlertCircle, AlertTriangle, CheckCircle2, Info } from 'lucide-react';
import type { ReactNode } from 'react';

import { cn } from '@/lib/utils';

export function FormField({
  id,
  label,
  hint,
  error,
  labelAction,
  children,
  className,
}: {
  id: string;
  label: string;
  hint?: string;
  error?: ReactNode;
  /** Optional element shown at the right end of the label row (e.g. a "Forgot password" link). */
  labelAction?: ReactNode;
  children: ReactNode;
  className?: string;
}) {
  const describedBy = [hint === undefined ? null : `${id}-hint`, error === undefined ? null : `${id}-error`]
    .filter((value): value is string => value !== null)
    .join(' ');
  return (
    <div className={cn('grid gap-1.5', className)}>
      <div className="flex items-center justify-between gap-3">
        <label htmlFor={id} className="text-small font-semibold text-foreground">
          {label}
        </label>
        {labelAction}
      </div>
      <div data-describedby={describedBy} className="grid">
        {children}
      </div>
      {hint === undefined ? null : (
        <p id={`${id}-hint`} className="text-caption text-muted-foreground">
          {hint}
        </p>
      )}
      {error === undefined ? null : <FieldError id={`${id}-error`}>{error}</FieldError>}
    </div>
  );
}

export function FieldError({ id, children }: { id: string; children: ReactNode }) {
  return (
    <p id={id} className="flex items-start gap-1.5 text-caption text-danger motion-safe:animate-[field-error_180ms_cubic-bezier(0.2,0.8,0.2,1)]" role="alert">
      <AlertCircle className="mt-px h-3.5 w-3.5 shrink-0" aria-hidden="true" />
      <span>{children}</span>
    </p>
  );
}

export const describedBy = (id: string, hint?: string, error?: unknown): string | undefined => {
  const ids = [hint === undefined ? null : `${id}-hint`, error === undefined || error === null || error === false ? null : `${id}-error`].filter(
    (value): value is string => value !== null,
  );
  return ids.length === 0 ? undefined : ids.join(' ');
};

const alertTones = {
  error: { box: 'border-danger/25 bg-danger-soft text-foreground', icon: 'text-danger', Icon: AlertCircle },
  warning: { box: 'border-warning/30 bg-warning-soft text-foreground', icon: 'text-warning', Icon: AlertTriangle },
  info: { box: 'border-info/25 bg-info-soft text-foreground', icon: 'text-info', Icon: Info },
  success: { box: 'border-success/25 bg-success-soft text-foreground', icon: 'text-success', Icon: CheckCircle2 },
} as const;

export function FormAlert({
  children,
  className,
  tone = 'error',
  title,
  icon,
  action,
}: {
  children: ReactNode;
  className?: string;
  tone?: keyof typeof alertTones;
  title?: ReactNode;
  /** Overrides the default icon for the tone. */
  icon?: ReactNode;
  /** Optional link or button shown on the right. */
  action?: ReactNode;
}) {
  const style = alertTones[tone];
  const Icon = style.Icon;
  return (
    <div
      role={tone === 'error' || tone === 'warning' ? 'alert' : 'status'}
      className={cn(
        'flex items-start gap-3 rounded-lg border px-4 py-3 text-small',
        style.box,
        tone === 'error' && 'motion-safe:animate-[shake_300ms_cubic-bezier(0.2,0.8,0.2,1)_1]',
        className,
      )}
    >
      <span className={cn('mt-0.5 shrink-0 [&>svg]:h-[18px] [&>svg]:w-[18px]', style.icon)} aria-hidden="true">
        {icon ?? <Icon />}
      </span>
      <div className="min-w-0 flex-1">
        {title === undefined ? null : <p className="font-semibold">{title}</p>}
        <div className={cn(title !== undefined && 'mt-0.5 text-muted-foreground')}>{children}</div>
      </div>
      {action === undefined ? null : <div className="shrink-0 self-center">{action}</div>}
    </div>
  );
}
