import React, { useCallback, useState } from 'react';
import { ScrollView, View } from 'react-native';
import { Appbar, Button, useTheme } from 'react-native-paper';
import { useNavigation } from '@react-navigation/native';
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { BSON } from 'realm';
import { useObject, useRealm } from '@realm/react';
import { TagEditor } from '../components';
import styles from '../styles';
import { ORIENTATION, useDimensions } from '../contexts';
import { ROUTE, RootStackParamList } from '../types';
import { Tag } from '../database';
import { deleteTag, validateColor, validateTagName } from '../utilities';

const EditTag = ({
  route,
}: NativeStackScreenProps<RootStackParamList, ROUTE.EDIT_TAG>) => {
  const { goBack } = useNavigation();
  const { colors } = useTheme();
  const { orientation } = useDimensions();
  const realm = useRealm();

  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  const tag = useObject<Tag>(
    Tag.schema.name,
    BSON.UUID.createFromHexString(route.params.id),
  )!;

  const [tagName, setTagName] = useState(validateTagName(tag.name));
  const [tagColor, setTagColor] = useState(validateColor(tag.color));

  const handleSave = useCallback(() => {
    realm.write(() => {
      tag.name = tagName.parsed;
      tag.color = tagColor.parsed;
      tag.dateModified = new Date();
    });
  }, [realm, tag, tagColor.parsed, tagName.parsed]);

  return (
    <>
      <Appbar.Header>
        <Appbar.BackAction onPress={() => goBack()} />
        <Appbar.Content title={'Edit Tag'} />
        <Appbar.Action
          icon="delete"
          onPress={() => {
            deleteTag(realm, tag);
            goBack();
          }}
        />
      </Appbar.Header>
      <ScrollView
        contentContainerStyle={[
          orientation === ORIENTATION.PORTRAIT
            ? styles.paddingVertical
            : styles.smallPaddingVertical,
          styles.paddingHorizontal,
          styles.flexGrow,
          styles.flexColumnSpaceBetween,
          { backgroundColor: colors.background },
        ]}
        nestedScrollEnabled>
        <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();
              goBack();
            }}
            disabled={!tagName.valid || !tagColor.valid}>
            Save
          </Button>
        </View>
      </ScrollView>
    </>
  );
};

export default EditTag;
