import { redirect, unstable_createFileUploadHandler, unstable_parseMultipartFormData, json } from "@remix-run/node";
import { useLocation } from "@remix-run/react";
import { useLoaderData, Form, useActionData, Link } from "@remix-run/react";
import { useEffect, useState } from "react";
import Overlay from "~/components/Overlay";
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 replying = formData.get("replying");

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

  const errors = {};
  let imageName;
  let multiPartformdata;
  try {
    multiPartformdata = await unstable_parseMultipartFormData(request, fileUploadHandler);
    multiPartformdata.get("image") !== null ? imageName = multiPartformdata.get("image").name : imageName = null;
  } catch (err) {
    errors.image = "Image size too big";
  }

  if (typeof post !== "string" || post.length > 50 || post.length < 3) {
    errors.post = "Post too long or short";
  };

  if (Object.keys(errors).length) {
    return json(errors, { status: 422 });
  }

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

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

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

  return thread;
}

export default function Thread() {
  const data = useLoaderData();
  const actionData = useActionData();
  const [replying, setReplying] = useState();

  return (
    <Overlay>
      <div className="flex flex-col p-12 bg-ctp-crust outline rounded">
        <div className="bg-ctp-base rounded p-4">
          <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={`/uploads/${data.imageName}`} target="_blank" referrerPolicy="no-referrer"><img src={`/uploads/${data.imageName}`} alt="post image" width={240} /></a>
          <p>{data.post}</p>
        </div>
        <ul className="flex flex-col m-8 ">
          {data.posts.map(post => 
            <li id={`${post.id}`} className="rounded shadow p-4 m-4 odd:bg-ctp-mantle even:bg-ctp-base" key={post.id}>
              <div className="flex">
                <span>Reply id: <strong>{post.id}</strong> Replied at: <strong>{post.createdAt} </strong></span>
                <Link className="mx-2 text-ctp-rosewater hover:text-ctp-maroon hover:underline" onClick={(event) => {
                  event.preventDefault();
                  document.getElementById(`bottom`).scrollIntoView(true);
                  setReplying(post.id);
                  }} to={`#bottom`} 
                  >Reply
                </Link>
                <ul className="flex flex-wrap space-x-1">
                  {post?.replies?.map(reply => 
                    <li key={reply.id}>
                      <Link onClick={event => {
                        event.preventDefault();
                        document.getElementById(`${reply.id}`).scrollIntoView(true);
                      }} className="text-ctp-teal hover:text-ctp-sky hover:underline" to={`#${reply.id}`}>{reply.id}</Link>
                    </li>    
                  )}
                </ul>
              </div>
              {post.replyingTo ? <Link onClick={event => {
                event.preventDefault();
                document.getElementById(`${post.replyingTo}`).scrollIntoView(true);
              }} className="font-semibold text-sm hover:underline" to={`#${post.replyingTo}`}>Replying to id: {post.replyingTo}</Link> : ''}
              {post.imageName !== null ? <a href={`/uploads/${post.imageName}`} target="_blank" referrerPolicy="no-referrer"><img width={240} src={`/uploads/${post.imageName}`} alt="post image" /></a> : ''}
              <p>{post.comment}</p>
            </li>
          )}
        </ul>
      </div>
      <Form id="bottom" className=" bg-ctp-crust p-4 space-y-2 shadow-ctp-flamingo shadow-lg outline m-16 rounded flex flex-col justify-center items-center" method="post" encType="multipart/form-data">
        <label className="flex flex-col m-2 space-y-2" htmlFor="text-input">
          {replying ? <p className="text-center font-semibold text-ctp-black" >Replying to reply id: {replying}</p> : ''}
          <span className="font-semibold text-center text-ctp-subtext0" >Post</span> <textarea className=" bg-ctp-surface0 m-1 p-1 rounded shadow shadow-ctp-overlay0" required minLength={3} name="post" type="text" />
          {actionData ? <p>{actionData.post}</p> : ''}
        </label>
        <label className="flex flex-col m-2" htmlFor="image-upload"><span className="font-semibold text-center text-ctp-subtext0">Image</span>
          <input className="block w-full px-3 py-1.5 text-base font-semibold text-ctp-text bg-ctp-surface0 bg-clip-padding rounded transition ease-in-out m-0" accept="image/*" type="file" id="image-upload" name="image" />
          <p>{actionData?.image}</p>
        </label>
        <input className="hidden" type="number" name="replying" value={replying} />
        <button className="bg-white px-4 py-2 shadow rounded-full" type="submit">Submit</button>
      </Form>
    </Overlay>
  );
}
  