import { useRef, useState } from 'react';

import type { ImagePickerApi } from '~/src/components/ImagePicker';

import { locales } from '~/locales/fragments/contentLink';
import Box from '~/src/components/Box';
import { Clickable } from '~/src/components/Clickable';
import ImagePicker from '~/src/components/ImagePicker';
import InputLabel from '~/src/components/InputLabel';
import TextInput from '~/src/components/TextInput';
import useIsLargeScreen from '~/src/hooks/useIsLargeScreen';
import useTheme from '~/src/hooks/useTheme';
import { useI18nStatic } from '~/src/lib/i18n';
import { LinkInput } from './LinkInput';

export const DetailsForm = ({
  initialValues: { imageUrl, title, domainId, path },
  artistId,
  artistPath,
  isLoading,
  onImageReset,
}: {
  initialValues: {
    imageUrl?: string;
    title?: string;
    domainId?: number;
    path?: string;
  };
  artistId: number;
  artistPath: string;
  isLoading: boolean;
  onImageReset?(): Promise<void>;
}) => {
  const { t } = useI18nStatic<'contentLink'>(locales);

  const [isImageEmpty, setIsImageEmpty] = useState(!imageUrl);
  const imageApiRef = useRef<ImagePickerApi>(null);
  const isLargeScreen = useIsLargeScreen();
  const theme = useTheme();

  return (
    <Box flexBox alignStart flexColumn={!isLargeScreen} gap="2.85rem">
      <Box flexColumn gap="1rem" justifyCenter>
        <ImagePicker
          apiRef={imageApiRef}
          name="image"
          defaultImage={imageUrl}
          accept={['png', 'jpeg']}
          width="15rem"
          height="15rem"
          noFlexShrink
          isRequired={false}
          label={t('actions.uploadImage')}
          isLoading={isLoading}
          onChange={({ imageSrc }) => {
            setIsImageEmpty(!imageSrc);
          }}
        />
        {!isImageEmpty && (
          <Clickable
            isInline
            isDisabled={isLoading}
            style={{ color: theme.colorDanger }}
            onClick={async () => {
              imageApiRef.current?.clear();

              await onImageReset?.();
              setIsImageEmpty(true);
            }}
          >
            {t('detailsForm.clearImage')}
          </Clickable>
        )}
      </Box>
      <Box
        flexColumn
        width={isLargeScreen ? 'calc(100% - 17.85rem)' : '100%'}
        gap="1.8rem"
      >
        <InputLabel value={t('detailsForm.titleLabel')}>
          <TextInput
            name="title"
            autoFocus
            required
            height="5rem"
            maxLength={75}
            defaultValue={title}
            placeholder={t('detailsForm.titlePlaceholder')}
            isDisabled={isLoading}
          />
        </InputLabel>
        <LinkInput
          isLoading={isLoading}
          artistId={artistId}
          artistPath={artistPath}
          defaultDomainId={domainId}
          defaultPath={path}
        />
      </Box>
    </Box>
  );
};
