"use client";
import * as React from "react";
import Image from "next/image";
import MenuCard from "../components/ui/MenuCard/MenuCard";
import Product from "../../public/batch1/files_list.json";
import { Button } from "../components/ui/button";
import Modal from "../components/Modal/Modal";
import ClientPortal from "@/components/ClientPortal/ClientPortal";
import styles from "@/styles/Home.module.css";
import { Poppins } from "next/font/google";
import { sendEmail } from "./actions/sendEmail";
import { sendEmails } from "@/lib/mail.utils";

const Popp = Poppins({ weight: "400", subsets: ["latin"] });

// improve to drag & drop side cart for more fun

export default function Home() {
  const [email, setEmail] = React.useState<string>("");
  const [order, setOrder] = React.useState<string>("");
  const [records, setRecords] = React.useState<any>([]);
  const [formValues, setFormValues] = React.useState({
    emails: "",
    orders: "",
  });

  async function newOrder(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const formData = new FormData(event.currentTarget);
    const payload = Object.fromEntries(formData);
    // console.log(payload)
    // console.log(JSON.stringify(payload))
    // console.log({email:formData.get("email"), order:formData.get("order")})

    // Send client email
    await sendEmail(formData);

    // Send new order email to self
    const clientEmail = formData.get('senderEmail') as string
    // console.log(JSON.stringify({"senderEmail":clientEmail}))
    await fetch("/api/emails", {
      method: "POST",
      headers: {
        "Content-type": "application/json",
      },
      body: JSON.stringify({"senderEmail":clientEmail}),
    })
      .catch((error) => {
        console.error(error);
      });


    const response = await fetch("/backend/new-order", {
    // const response = await fetch("http://localhost:5080/new-order", {
      method: "POST",
      headers: {
        "Content-type": "application/json",
      },
      body: JSON.stringify(payload),
    })
      .then((response) => response.json())
      .catch((error) => {
        console.error(error);
      });

    setRecords([...records, formValues]);
    setFormValues({
      emails: "",
      orders: "",
    });
    alert("Order Placed! Please check your email.")
  }

  return (
    <main className="flex min-h-screen flex-col px-20">
      {/* Title */}
      <div className="text-4xl w-full justify-center text-center items-center flex flex-col gap-4 py-12 font-medium text-orange-600">
        <span className={`${Popp.className}`}>Kevo&#39;s Attire</span>
        <div className={`${Popp.className} text-orange-600 text-center`}>
          <p>All sizes - $25</p>
        </div>
        <div className={`${Popp.className} text-orange-600 text-center`}>
          <p>Youth-S/M/L/2XL - Adult-S/M/L/2XL</p>
        </div>
      </div>

      {/* Body */}
      <div className="w-full h-content">
        <MenuCard Menu={Product} />
      </div>

      <form
        className="mt-10 flex flex-col w-full items-center gap-4"
        // action={async (formData) => {
        //   await sendEmail(formData);
        // }}
        onSubmit={newOrder}
      >
        <div className="text-orange-600 flex flex-col text-2xl pb-4 text-center gap-2">
          <h3>Example Order</h3>
          <div className="text-green-500"><p>example@example.com</p></div>
          <div className="flex flex-col text-green-500">
            <p>1 blue Terminator Youth M</p>
            <p>1 black Bear-Relax Adult XL</p>
          </div>
        </div>
        <h2 className="text-orange-600 text-2xl">Order Form</h2>
        <input
          className="h-14 px-4 rounded-lg border-black bg-slate-600 lg:w-1/3 md:w-1/2 text-[#EEEEEE]"
          type="email"
          // onChange={(e) => setEmail(e.target.value)}
          value={formValues.emails}
          onChange={(e) =>
            setFormValues({ ...formValues, emails: e.target.value })
          }
          required
          maxLength={500}
          placeholder="Your PayPal email"
          name="senderEmail"
          // name="email"
        />

        <textarea
          className="h-52 my-3 rounded-lg lg:w-1/3 md:w-1/2 bg-slate-600 p-4 text-[#EEEEEE]"
          name="order"
          // onChange={(e) => setOrder(e.target.value)}
          value={formValues.orders}
          onChange={(e) =>
            setFormValues({ ...formValues, orders: e.target.value })
          }
          placeholder="Your order"
          required
          maxLength={500}
        />

        <button
          className="w-[8rem] flex items-center justify-center gap-2 h-[3rem] bg-slate-600 rounded-full outline-none transition-all text-white hover:bg-slate-500 hover:scale-110 hover:focus:scale-110 active:scale-105"
          type="submit"
          value="Submit"
        >
          Submit
        </button>
      </form>
      {/* Add that we will send a paypal invoice to confirm the order and items  */}

      {/* Footer */}
      <div className="flex w-full h-[250px] items-center text-gray-400">
        <div className="font-bold ">
          Email us at&nbsp;
          <a href="mailto:kevosattire@gmail.com" className="text-emerald-500">
            kevosattire@gmail.com
          </a>
          &nbsp;for any questions!
        </div>
        <div></div>
      </div>
    </main>
  );
}
