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,
  validateMemeDescription,
  validateMemeTitle,
} from '../../utilities';

const MemeEditor = ({
  imageUri,
  memeTitle,
  setMemeTitle,
  memeDescription,
  setMemeDescription,
  memeTags,
  setMemeTags,
}: {
  imageUri: string[];
  memeTitle: StringValidationResult;
  setMemeTitle: (name: StringValidationResult) => void;
  memeDescription: StringValidationResult;
  setMemeDescription: (description: StringValidationResult) => void;
  memeTags: Map<string, Tag>;
  setMemeTags: (tags: Map<string, Tag>) => void;
}) => {
  const { dimensions, fixed, responsive } = useDimensions();

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

  useEffect(() => {
    Image.getSize(imageUri[0], (width, height) => {
      const paddedWidth = dimensions.width - dimensions.width * 0.08;
      setImageWidth(paddedWidth);
      setImageHeight((paddedWidth / width) * height);
    });
  }, [dimensions.width, imageUri]);

  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: imageUri[0] }}
        style={{
          width: imageWidth,
          height: imageHeight,
          marginBottom: fixed.verticalScale(10),
          borderRadius: fixed.verticalScale(5),
        }}
      />
      <MemeTagSelector
        memeTags={memeTags}
        setMemeTags={setMemeTags}
        style={{
          marginBottom: responsive.verticalScale(10),
        }}
      />
      <TextInput
        mode="outlined"
        label="Description"
        multiline
        numberOfLines={6}
        style={{
          marginBottom: responsive.verticalScale(15),
        }}
        value={memeDescription.raw}
        onChangeText={description =>
          setMemeDescription(validateMemeDescription(description))
        }
      />
    </>
  );
};

export default MemeEditor;
