import React, { 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 memeEditorStyles = {
  image: {
    marginBottom: 15,
    borderRadius: 5,
  },
  memeTagSelector: {
    marginBottom: 10,
  },
  description: {
    marginBottom: 10,
  },
};

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 } = useDimensions();

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

  Image.getSize(imageUri, (width, height) => {
    const paddedWidth = dimensions.width * 0.92;
    setImageWidth(paddedWidth);
    setImageHeight((paddedWidth / width) * height);
  });

  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 }}
        style={[
          {
            width: imageWidth,
            height: imageHeight,
          },
          memeEditorStyles.image,
        ]}
      />
      <MemeTagSelector
        memeTags={memeTags}
        setMemeTags={setMemeTags}
        style={memeEditorStyles.memeTagSelector}
      />
      <TextInput
        mode="outlined"
        label="Description"
        multiline
        numberOfLines={6}
        value={memeDescription.raw}
        style={memeEditorStyles.description}
        onChangeText={description =>
          setMemeDescription(validateMemeDescription(description))
        }
        error={!memeDescription.valid}
      />
    </>
  );
};

export default MemeEditor;
