"use client";

import { ReactElement, useEffect, useState } from "react";
import { ActionMenu } from "@/app/components/action-menu";
import { Button } from "@/app/components/ui/button";
import { useToast } from "@/app/components/ui/use-toast";
import { ArrowPathIcon } from "@heroicons/react/16/solid";

export default function Home(): ReactElement {
  const { toast } = useToast();
  const [value, setValue] = useState("");
  const [creating, setCreating] = useState(false);

  /**
   * Uploads the paste to the server.
   */
  async function createPaste() {
    // Ignore empty pastes, we don't want to save them
    if (!value || value.length == 0) {
      toast({
        title: "Paste",
        description: "Paste is empty",
      });
      return;
    }

    setCreating(true);
    // Upload the paste to the server
    const response = await fetch(
      `${process.env.NEXT_PUBLIC_API_ENDPOINT}/upload`,
      {
        method: "POST",
        headers: {
          "Content-Type": "text/plain",
        },
        body: value,
      },
    );

    const data = await response.json();

    if (!response.ok) {
      toast({
        title: "Paste",
        description: data.message,
      });
      setCreating(false);
      return;
    }

    // Redirect to the new paste
    window.location.href = `/${data.id}`;
  }

  useEffect(() => {
    document.getElementById("paste-input")?.focus();
  }, []);

  return (
    <div className="p-3 h-screen w-screen relative">
      <div className="flex gap-2 h-full w-full text-xs">
        {/* > */}
        <p className="hidden md:block">&gt;</p>

        {/* Input */}
        <textarea
          onInput={(event) => {
            setValue((event.target as HTMLTextAreaElement).value);
          }}
          id="paste-input"
          className="w-full h-full bg-background outline-none resize-none"
          placeholder="Paste your code here..."
        />
      </div>

      {/* Action Menu */}
      <ActionMenu>
        <Button onClick={() => createPaste()} className="flex gap-1">
          {creating && (
            <div className="animate-spin">
              <ArrowPathIcon width={16} height={16} />
            </div>
          )}
          Save
        </Button>
      </ActionMenu>
    </div>
  );
}
