import { useRouter } from 'expo-router';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Controller, useForm } from 'react-hook-form';
import { Book } from './Book';
import { Button } from 'react-native';

import {
  Container,
  Title,
  FieldWrapper,
  Label,
  StyledInput,
  ButtonWrapper,
} from './Form.styles';
import { useEffect } from 'react';

type Props = {
  id: number;
};

const Form: React.FC<Props> = ({ id }) => {
  const router = useRouter();

  const { control, handleSubmit, reset } = useForm<Book>({
    defaultValues: {
      id: 0,
      title: '',
      author: '',
      isbn: '',
      rating: 0,
    },
  });

  useEffect(() => {
    async function load() {
      const res = await fetch(`http://localhost:3001/books/${id}`);
      const data = await res.json();
      reset(data);
    }
    load();
  }, [id, reset]);

  async function onSubmit(values: Book) {
    await fetch(`http://localhost:3001/books/${values.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(values),
    });

    router.push('/');
  }

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <Container>
        <Title>Buch bearbeiten</Title>

        {/* Titel */}
        <FieldWrapper>
          <Label>Titel</Label>
          <Controller
            control={control}
            name="title"
            render={({ field: { onChange, value } }) => (
              <StyledInput
                placeholder="Titel"
                value={value}
                onChangeText={onChange}
              />
            )}
          />
        </FieldWrapper>

        {/* Autor */}
        <FieldWrapper>
          <Label>Autor</Label>
          <Controller
            control={control}
            name="author"
            render={({ field: { onChange, value } }) => (
              <StyledInput
                placeholder="Autor"
                value={value}
                onChangeText={onChange}
              />
            )}
          />
        </FieldWrapper>

        {/* ISBN */}
        <FieldWrapper>
          <Label>ISBN</Label>
          <Controller
            control={control}
            name="isbn"
            render={({ field: { onChange, value } }) => (
              <StyledInput
                placeholder="ISBN"
                value={value}
                onChangeText={onChange}
              />
            )}
          />
        </FieldWrapper>

        <ButtonWrapper>
          <Button title="Speichern" onPress={handleSubmit(onSubmit)} />
          <Button title="Abbrechen" onPress={() => router.push('/')} />
        </ButtonWrapper>
      </Container>
    </SafeAreaView>
  );
};

export default Form;
