import React, { useState } from 'react';
import { ScrollView, View } from 'react-native';
import { Appbar, Button, useTheme } from 'react-native-paper';
import { useNavigation } from '@react-navigation/native';
import { useRealm } from '@realm/react';
import styles from '../styles';
import {
  generateRandomColor,
  validateColor,
  validateTagName,
} from '../utilities';
import { ORIENTATION, useDimensions } from '../contexts';
import { Tag } from '../database';
import { TagEditor } from '../components';

const AddTag = () => {
  const { goBack } = useNavigation();
  const { colors } = useTheme();
  const { orientation } = useDimensions();
  const realm = useRealm();

  const [tagName, setTagName] = useState(validateTagName('newTag'));
  const [tagColor, setTagColor] = useState(
    validateColor(generateRandomColor()),
  );

  const handleSave = () => {
    realm.write(() => {
      realm.create(Tag.schema.name, {
        name: tagName.parsed,
        color: tagColor.parsed,
      });
    });

    goBack();
  };

  return (
    <>
      <Appbar.Header>
        <Appbar.BackAction onPress={() => goBack()} />
        <Appbar.Content title={'Add Tag'} />
      </Appbar.Header>
      <ScrollView
        contentContainerStyle={[
          orientation === ORIENTATION.PORTRAIT
            ? styles.paddingVertical
            : styles.smallPaddingVertical,
          styles.paddingHorizontal,
          styles.flexGrow,
          styles.flexColumnSpaceBetween,
          { backgroundColor: colors.background },
        ]}>
        <View style={[styles.flex, styles.justifyStart]}>
          <TagEditor
            tagName={tagName}
            setTagName={setTagName}
            tagColor={tagColor}
            setTagColor={setTagColor}
          />
        </View>
        <View style={[styles.flex, styles.justifyEnd]}>
          <Button
            mode="contained"
            icon="floppy"
            onPress={handleSave}
            disabled={!tagName.valid || !tagColor.valid}>
            Save
          </Button>
        </View>
      </ScrollView>
    </>
  );
};

export default AddTag;
