import React, { useEffect, useState } from 'react';
import { HelperText, TextInput } from 'react-native-paper';
import { Image } from 'react-native';
import { useDimensions } from '../../contexts';
import LoadingView from '../loadingView';
import { MemeTagSelector } from '.';
import { Tag } from '../../database';
import { StringValidationResult, validateMemeTitle } from '../../utilities';

const memeEditorStyles = {
  image: {
    marginBottom: 15,
    borderRadius: 5,
  },
  memeTagSelector: {
    marginBottom: 10,
  },
  description: {
    marginBottom: 10,
  },
};

const MemeEditor = ({
  memeUri,
  memeTitle,
  setMemeTitle,
  memeTags,
  setMemeTags,
}: {
  memeUri: string;
  memeTitle: StringValidationResult;
  setMemeTitle: (name: StringValidationResult) => void;
  memeTags: Map<string, Tag>;
  setMemeTags: (tags: Map<string, Tag>) => void;
}) => {
  const { dimensions } = useDimensions();

  const [imageWidth, setImageWidth] = useState<number>();
  const [imageHeight, setImageHeight] = useState<number>();

  useEffect(() => {
    // eslint-disable-next-line unicorn/no-useless-undefined
    setImageWidth(undefined);
    // eslint-disable-next-line unicorn/no-useless-undefined
    setImageHeight(undefined);

    Image.getSize(memeUri, (width, height) => {
      const paddedWidth = dimensions.width * 0.92;
      const paddedHeight = Math.max(
        Math.min((paddedWidth / width) * height, 500),
        100,
      );

      setImageWidth(paddedWidth);
      setImageHeight(paddedHeight);
    });
  }, [memeUri, dimensions.width]);

  if (!imageWidth || !imageHeight) return <LoadingView />;

  return (
    <>
      <TextInput
        mode="outlined"
        label="Title"
        value={memeTitle.raw}
        onChangeText={title => setMemeTitle(validateMemeTitle(title))}
        error={!memeTitle.valid}
        selectTextOnFocus
      />
      <HelperText type="error" visible={!memeTitle.valid}>
        {memeTitle.error}
      </HelperText>
      <Image
        source={{ uri: memeUri }}
        style={[
          {
            width: imageWidth,
            height: imageHeight,
          },
          memeEditorStyles.image,
        ]}
        resizeMode="contain"
      />
      <MemeTagSelector
        memeTags={memeTags}
        setMemeTags={setMemeTags}
        style={memeEditorStyles.memeTagSelector}
      />
    </>
  );
};

export default MemeEditor;
