import { useState } from 'react';
import {
  TextInput,
  UnstyledButton,
  rem,
  type TextInputProps,
} from '@mantine/core';

export interface BilingualValue {
  en: string;
  am: string;
}

interface BilingualInputProps
  extends Omit<TextInputProps, 'value' | 'onChange' | 'rightSection' | 'rightSectionWidth'> {
  value: BilingualValue;
  onChange: (value: BilingualValue) => void;
}

export function BilingualInput({
  label,
  value,
  onChange,
  required,
  placeholder,
  ...rest
}: BilingualInputProps) {
  const [lang, setLang] = useState<'en' | 'am'>('en');

  const toggle = () => setLang((l) => (l === 'en' ? 'am' : 'en'));

  return (
    <TextInput
      label={label}
      required={required}
      placeholder={placeholder ?? (lang === 'en' ? 'Enter in English' : 'በአማርኛ ያስገቡ')}
      value={value[lang]}
      onChange={(e) => onChange({ ...value, [lang]: e.currentTarget.value })}
      rightSection={
        <UnstyledButton
          onClick={toggle}
          aria-label={`Switch to ${lang === 'en' ? 'Amharic' : 'English'}`}
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            width: rem(28),
            height: rem(20),
            borderRadius: rem(4),
            fontSize: rem(10),
            fontWeight: 700,
            letterSpacing: '0.05em',
            background:
              lang === 'en'
                ? 'var(--mantine-color-blue-1)'
                : 'var(--mantine-color-teal-1)',
            color:
              lang === 'en'
                ? 'var(--mantine-color-blue-7)'
                : 'var(--mantine-color-teal-7)',
            cursor: 'pointer',
            transition: 'background 150ms ease',
          }}
        >
          {lang === 'en' ? 'EN' : 'AM'}
        </UnstyledButton>
      }
      styles={{
        input: {
          paddingRight: rem(42),
        },
      }}
      {...rest}
    />
  );
}
