import type { ReactNode } from 'react';
import { Input } from '@rutatiina/ui/components/ui/input';
import { Label } from '@rutatiina/ui/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@rutatiina/ui/components/ui/select';
import { Switch } from '@rutatiina/ui/components/ui/switch';
import { Textarea } from '@rutatiina/ui/components/ui/textarea';
import { useTrans } from '@rutatiina/ui/lib/translations';
import { cn } from '@rutatiina/ui/lib/utils';
import type { Option } from '@nugsoft/members/types';

export type Errors = Record<string, string>;

/**
 * A labelled input with its hint and error.
 */
export function Field({
  id,
  label,
  error,
  hint,
  required,
  className,
  children,
}: {
  id: string;
  label: string;
  error?: string;
  hint?: ReactNode;
  required?: boolean;
  className?: string;
  children: ReactNode;
}) {
  return (
    <div className={cn('flex min-w-0 flex-col gap-2', className)}>
      <Label htmlFor={id}>
        {label}
        {required && <span className="text-destructive"> *</span>}
      </Label>
      {children}
      {hint && !error && (
        <p className="text-muted-foreground text-xs">{hint}</p>
      )}
      {error && <p className="text-destructive text-sm">{error}</p>}
    </div>
  );
}

export function TextField({
  id,
  label,
  value,
  onChange,
  error,
  hint,
  required,
  className,
  ...props
}: {
  id: string;
  label: string;
  value: string | number | null | undefined;
  onChange: (value: string) => void;
  error?: string;
  hint?: ReactNode;
  required?: boolean;
  className?: string;
} & Omit<React.ComponentProps<typeof Input>, 'value' | 'onChange' | 'id'>) {
  return (
    <Field
      id={id}
      label={label}
      error={error}
      hint={hint}
      required={required}
      className={className}
    >
      <Input
        id={id}
        value={value ?? ''}
        aria-invalid={!!error}
        required={required}
        onChange={(event) => onChange(event.target.value)}
        {...props}
      />
    </Field>
  );
}

export function TextAreaField({
  id,
  label,
  value,
  onChange,
  error,
  hint,
  required,
  className,
  rows = 3,
}: {
  id: string;
  label: string;
  value: string | null | undefined;
  onChange: (value: string) => void;
  error?: string;
  hint?: ReactNode;
  required?: boolean;
  className?: string;
  rows?: number;
}) {
  return (
    <Field
      id={id}
      label={label}
      error={error}
      hint={hint}
      required={required}
      className={className}
    >
      <Textarea
        id={id}
        rows={rows}
        value={value ?? ''}
        aria-invalid={!!error}
        required={required}
        onChange={(event) => onChange(event.target.value)}
      />
    </Field>
  );
}

export function SelectField({
  id,
  label,
  value,
  onChange,
  options,
  error,
  hint,
  required,
  className,
  placeholder,
  disabled,
  clearable,
}: {
  id: string;
  label: string;
  value: string | null | undefined;
  onChange: (value: string) => void;
  options: Option[];
  error?: string;
  hint?: ReactNode;
  required?: boolean;
  className?: string;
  placeholder?: string;
  disabled?: boolean;
  /** Offer a "None" choice that clears the value. */
  clearable?: boolean;
}) {
  const __ = useTrans();

  return (
    <Field
      id={id}
      label={label}
      error={error}
      hint={hint}
      required={required}
      className={className}
    >
      <Select
        value={value || (clearable ? '__none' : undefined)}
        onValueChange={(next) => onChange(next === '__none' ? '' : next)}
        disabled={disabled}
      >
        <SelectTrigger id={id} aria-invalid={!!error}>
          <SelectValue placeholder={placeholder ?? __('Select')} />
        </SelectTrigger>
        <SelectContent>
          {clearable && (
            <SelectItem value="__none">
              <span className="text-muted-foreground">{__('None')}</span>
            </SelectItem>
          )}
          {options.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </Field>
  );
}

export function SwitchField({
  id,
  label,
  description,
  checked,
  onChange,
  disabled,
}: {
  id: string;
  label: string;
  description?: ReactNode;
  checked: boolean;
  onChange: (checked: boolean) => void;
  disabled?: boolean;
}) {
  return (
    <div className="flex items-start gap-3">
      <Switch
        id={id}
        checked={checked}
        disabled={disabled}
        onCheckedChange={onChange}
      />
      <div className="flex flex-col gap-1">
        <Label htmlFor={id}>{label}</Label>
        {description && (
          <p className="text-muted-foreground text-xs">{description}</p>
        )}
      </div>
    </div>
  );
}

/**
 * The errors under a prefix, without it: errorsAt({'contacts.0.value': 'x'}, 'contacts.0.') → {value: 'x'}.
 */
export function errorsAt(errors: Errors, prefix: string): Errors {
  return Object.fromEntries(
    Object.entries(errors)
      .filter(([key]) => key.startsWith(prefix))
      .map(([key, message]) => [key.slice(prefix.length), message]),
  );
}
