import { useState } from "react";
import { Form, useActionData, useNavigate } from "react-router";
import { useLocation } from "react-router";
import { redirect, type ActionFunctionArgs } from "react-router";


// server-side action so we don't have to use clearnet for front-backend comms
// praise cloudflare
export async function action({ request, context }: ActionFunctionArgs) {
  const formData = await request.formData();
  const env = context.cloudflare.env as { API: Fetcher };
  
  const postTitle = formData.get("title") as string;
  const postContent = formData.get("content") as string;
  const parentId = formData.get("parentId") as string;

  // internal url uses ternary operator
  const path = parentId 
    ? `/posts/${parentId}/reply`
    : "/posts/add";
  
  const response = await env.API.fetch(new Request(`http://internal${path}`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      // forward cookies or auth won't work
      "Cookie": request.headers.get("Cookie") || "",
    },
    body: JSON.stringify({
      title: postTitle,
      content: postContent,
    }),
  }));

  if (!response.ok) {
    const error = await response.text();
    return { error: `Failed to create post: ${response.status} - ${error}` };
  }

  return redirect("/");
}

export default function CreatePostPage() {
  const location = useLocation();
  const stateParentId = location.state?.parentId;
  const [parentId, setParentId] = useState(stateParentId || "");

  console.log(stateParentId);
  console.log(parentId);

  return (
    <div className="w-[92vw] md:w-[60vw] min-h-[60vh] md:min-h-0 md:h-[50vh] flex flex-col absolute top-1/2 left-1/2 p-4 md:p-8 -translate-x-1/2 -translate-y-1/2 shadow-black/40 shadow-2xl rounded-2xl bg-[#171717] text-[#fafafa] transition ease-in-out duration-300">
      <h1 className="text-xl md:text-2xl font-black text-center mb-4">Create Post</h1>

      <Form className="flex-1 flex flex-col gap-4" method="post">
        <div className="flex flex-col md:flex-row gap-2 md:items-center">
          <label htmlFor="title" className="px-1 font-semibold">Post Title</label>
          <input
            type="text"
            name="title"
            className="bg-transparent border-[1px] border-white/40 rounded-xl p-2 focus:border-white outline-none flex-1 hover:border-white/60 transition ease-in-out duration-200"
            required 
          />
        </div>

        <div className="flex-1 flex flex-col gap-2">
          <label htmlFor="content" className="px-1 font-semibold">Post Contents</label>
          <textarea
            name="content"
            className="flex-1 min-h-[120px] md:min-h-0 bg-transparent border-[1px] border-white/40 rounded-xl p-3 focus:border-white outline-none resize-none hover:border-white/60 transition ease-in-out duration-200"
            required
          />
        </div>

        <div className="flex flex-col md:flex-row gap-2 md:items-center">
          <label htmlFor="parentId" className="px-1 font-semibold">Parent Post ID (leave empty if none)</label>
          <input
            type="text"
            name="parentId"
            className="bg-transparent border-[1px] border-white/40 rounded-xl p-2 focus:border-white outline-none hover:border-white/60 transition ease-in-out duration-200"
            value={parentId}
            onChange={(e) => setParentId(e.target.value)}
          />

          <button className="bg-white text-black font-bold rounded-xl p-2 md:ml-auto w-full md:w-auto transition ease-in-out duration-300 hover:scale-125" type="submit">Create Post</button>
        </div>
      </Form>
    </div>
  );
}
