import AsyncStorage from '@react-native-async-storage/async-storage'
import { Alert } from 'react-native';
import { login, getNote, editNote, createNote, removeNote } from './api'

export const handleLogin = async ({ email, password, setSession, showError }) => {
  try {
    const response = await login({ email, password })
    const cookies = response.headers?.map?.['set-cookie']
    const data = await response.json()
    if (data?.isLoggedIn) {
      await AsyncStorage.setItem('session', JSON.stringify({ ...data, cookies }))
      setSession({ ...data, cookies })
    }
  } catch(e) {
    showError('Error while logging in')
  }
}

export const handleLogout = ({ session, setSession, showError }) => {
  const logout = async () => {
    try {
      await AsyncStorage.clear();
      setSession(null)
    } catch(e) {
      showError('Error while logging out')
    }
  }

  Alert.alert(
    'Are you sure?',
    `Do you want to log out user ${session.email}?`,
    [
      {
        text: 'Logout',
        onPress: logout,
        style: 'destructive',
      },
      {
        text: 'Cancel',
        onPress: () => {},
        style: 'cancel',
      },
    ],
  );
}

export const handleGetNote = async ({ note, setContent, setEdit, session, showError }) => {
  try {
    const response = await getNote({ note, session })
    const { content } = await response.json()
    setContent(content)
  } catch(e) {
    showError('Error while fetching note')
    setEdit(null)
  }
}

export const handleEditNote = async ({ note, title, content, setSaving, setEdit, session, showError }) => {
  try {
    setSaving(true)
    await editNote({ note, title, content, session })
    setSaving(false)
    setEdit(null)
  } catch(e) {
    showError('Error while saving note')
    setSaving(false)
    setEdit(null)
  }
}

export const handleCreateNote = async ({ title, content, setSaving, setEdit, session, showError }) => {
  try {
    setSaving(true)
    await createNote({ title, content, session })
    setSaving(false)
    setEdit(null)
  } catch(e) {
    showError('Error while saving note')
    setSaving(false)
    setEdit(null)
  }
}

export const handleRemove = ({ note, session, fetchNotes, setLoading, showError }) => {
  const deleteNote = async () => {
    setLoading(true)
    try {
      await removeNote({ note, session })
      fetchNotes()
    } catch(e) {
      console.log(e)
      showError('Error while removing note')
      setLoading(false)
    }
  }

  Alert.alert(
    'Are you sure?',
    `Note "${note.title}" will be permanently removed`,
    [
      {
        text: 'Remove',
        onPress: deleteNote,
        style: 'destructive',
      },
      {
        text: 'Cancel',
        onPress: () => {},
        style: 'cancel',
      },
    ],
  );
};

export const SORT = [
  '▼ Updated',
  '▲ Updated',
  '▼ Created',
  '▲ Created',
  '▼ Title',
  '▲ Title',
]


