import { Form, redirect, useActionData, useNavigation } from 'react-router-dom';

function NewPost() {
  const validationErrors = useActionData();

  const navigation = useNavigation();

  const isSubmitting = navigation.state !== 'idle';

  return (
    <Form method="post" id="post-form">
      <p>
        <label htmlFor="title">Tytuł</label>
        <input type="text" id="title" name="title" />
      </p>
      <p>
        <label htmlFor="text">Tekst</label>
        <textarea id="text" name="text" rows={3} />
      </p>
      <ul>
        {validationErrors &&
          validationErrors.map((err) => <li key={err}>{err}</li>)}
      </ul>
      <button disabled={isSubmitting}>
        {isSubmitting ? 'Zapisywanie w toku...' : 'Zapisz artykuł'}
      </button>
    </Form>
  );
}

export default NewPost;

export async function action({ request }) {
  const formData = await request.formData();
  const postData = Object.fromEntries(formData);

  let validationErrors = [];

  if (postData.title.trim().length === 0) {
    validationErrors.push('Błędny tytuł artykułu.');
  }
  if (postData.text.trim().length === 0) {
    validationErrors.push('Błędny tekst artykułu.');
  }

  if (validationErrors.length > 0) {
    return validationErrors;
  }

  await fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    body: JSON.stringify(postData),
    headers: { 'Content-Type': 'application/json' },
  });
  return redirect('/posts');
}
