import { useCallback, useState } from 'react';

import InputLabel from '~/src/components/InputLabel';
import Text from '~/src/components/Text';
import TextInput from '~/src/components/TextInput';
import useTheme from '~/src/hooks/useTheme';
import { useI18n } from '~/src/lib/i18n';
import { isValidIsrc, isValidUpc } from '~/src/lib/lookup';
import { isUrl } from '~/src/lib/utils/url';

interface ReleaseIdentifierInputProps {
  initialUpc?: string | null;
  initialIsrc?: string | null;
  initialUrl?: string | null;
  required?: boolean;
  error?: string;
  onChange(): void;
}

export const ReleaseIdentifierInput = ({
  initialUpc,
  initialIsrc,
  initialUrl,
  required,
  error,
  onChange,
}: ReleaseIdentifierInputProps) => {
  const { t } = useI18n('prerelease');
  const theme = useTheme();

  const [value, setValue] = useState<{
    isrc?: string | null;
    upc?: string | null;
    url?: string | null;
  }>({
    isrc: initialIsrc,
    upc: initialUpc,
    url: initialUrl,
  });

  return (
    <InputLabel value={t('labels.upcIsrc')} description={t('upcIsrcInputHelp')}>
      {error && (
        <Text size="1.3rem" color={theme.colorDanger} margin="0 0 0.7rem">
          {error}
        </Text>
      )}
      <TextInput
        testId="releaseIdentifierInput"
        height="5rem"
        name="releaseIdentifier"
        maxLength={500}
        placeholder={t('upcIsrcPlaceholder')}
        borderColor={error ? theme.colorDanger : undefined}
        defaultValue={initialUpc || initialIsrc || initialUrl || ''}
        required={required}
        onChange={onChange}
        toValidationMessage={useCallback(({ value }) => {
          if (!value) {
            setValue({ upc: undefined, isrc: undefined, url: undefined });
            return;
          }

          const isrc = isValidIsrc(value) ? value : undefined;
          const upc = isValidUpc(value) ? value : undefined;
          const url = isUrl(value) ? value : undefined;

          const updatedValue = upc ?? isrc ?? url;

          setValue({ upc, isrc, url });

          if (!updatedValue) {
            return t('invalidUpcIsrc');
          }
        }, [])}
      />
      <input type="hidden" name="isrc" value={value.isrc ?? ''} />
      <input type="hidden" name="upc" value={value.upc ?? ''} />
      <input type="hidden" name="url" value={value.url ?? ''} />
    </InputLabel>
  );
};
