import { redirect, unstable_createFileUploadHandler, unstable_parseMultipartFormData } from "@remix-run/node";
import { useLoaderData, Form } from "@remix-run/react";
import prisma from "~/utils/db.server";

export async function action({ request, params }) {
  const threadId = params.threadId;

  const clonedData = request.clone();
  const formData = await clonedData.formData();
  const post = formData.get("post");

  const fileUploadHandler = unstable_createFileUploadHandler({
    directory: './public/uploads/',
    maxPartSize: 500000,
    file: ({ filename }) => filename,
  });

  const multiPartformdata = await unstable_parseMultipartFormData(request, fileUploadHandler);
  let imageName;
  multiPartformdata.get("image") !== null ? imageName = multiPartformdata.get("image").name : imageName = null;

  const createPost = await prisma.post.create({
    data: {
      comment: post,
      imageName: imageName,
      postId: parseInt(threadId),
    },
  });

  return redirect(`/threads/${threadId}`);
};

export async function loader({ params }) {
  const threadId = params.threadId;
  const thread = await prisma.thread.findUnique({
    where: {
      id: Number(threadId),
    },
    include: {
      posts: true,
    },
  });

  return thread;
}

export default function Thread() {
  const data = useLoaderData();

  return (
    <div>
      <div>
        <span><strong>{data.title}</strong> Post id: <strong>{data.id}</strong> Created at: <strong>{data.createdAt}</strong> Reply count: <strong>{data.posts.length}</strong></span>
        <br />
        <a href={`/${data.imageName}`} target="_blank"><img src={`/uploads/${data.imageName}`} alt="post image" width={240} /></a>
        <p>{data.post}</p>
        <hr />
        <ul>
          {data.posts.map(post => 
            <li key={post.id}>
              <span>Reply id: <strong>{post.id}</strong> Replied at: <strong>{post.createdAt}</strong></span>
              <br />
              {post.imageName !== 'null' ? <img width={240} src={`/uploads/${post.imageName}`} alt="post image" /> : ''}
              <p>{post.comment}</p>
            </li>
          )}
        </ul>
      </div>
      <Form method="post" encType="multipart/form-data">
        <label htmlFor="text-input">
          Post: <input required minLength={3} name="post" type="text" />
        </label>
        <label htmlFor="image-upload">
          Image: <input type="file" name="image" id="image-upload" />
        </label>
        <button type="submit">Submit</button>
      </Form>
    </div>
  );
}
  