import { StyleSheet, Text, TextInput , View } from 'react-native';
import { useState, useEffect } from 'react'
import { handleGetNote, handleCreateNote, handleEditNote } from '../helpers';
import Menu from './Menu'

const Edit = ({ edit: note, setEdit, session, setSession, showError }) => {
  const [saving, setSaving] = useState()
  const [title, setTitle] = useState(note ? note.title : '')
  const [content, setContent] = useState()

  const saveNote = () => note._id
    ? handleEditNote({ note, title, content, setSaving, setEdit, session, showError })
    : handleCreateNote({ title, content, setSaving, setEdit, session, showError })

  useEffect(() => {
    if (note?._id) {
      handleGetNote({ note, setContent, setEdit, session, showError })
    } else {
      setContent('')
    }
  }, [])

  return (
    <>
      <Menu
        session={session}
        setSession={setSession}
        showError={showError}
        setEdit={setEdit}
        saveNote={saveNote}
      />
      <View style={styles.container}>
        <TextInput
          placeholder="Title"
          placeholderTextColor="#BBB"
          style={styles.title}
          value={title}
          onChange={e => setTitle(e.nativeEvent.text)}
        />
        {
          content === undefined || saving
            ? <Text style={styles.text}>{saving ? 'Saving...' : 'Loading content...'}</Text>
            : (
              <TextInput
                placeholder="Content"
                placeholderTextColor="#BBB"
                multiline={true}
                textAlignVertical="top"
                style={styles.content}
                value={content}
                onChange={e => setContent(e.nativeEvent.text)}
              />
            )
        }
      </View>
    </>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 15,
    marginBottom: 50,
  },
  title: {
    color: 'white',
    borderBottomColor: 'white',
    borderBottomWidth: 1,
    paddingBottom: 15,
    marginBottom: 10,
    fontWeight: 'bold',
  },
  content: {
    color: 'white',
    flexGrow: 1,
    paddingVertical: 10,
  },
  text: {
    color: 'white',
  }
});

export default Edit
