"use client";

import React, { useEffect, useState } from "react";
import { Formik, Field, Form } from "formik";
import * as Yup from "yup";
import tick from "../../assets/tick.svg";
import { AppDispatch } from "../../store";
import { useDispatch, useSelector } from "react-redux";
import { setValues } from "../../slice/PostAdSlice";
import { RootState } from "../../store";
import { categoryApiCall } from "../../api/api";
import { truncateTitle } from "../../utils/commonFunction";
import Image from "next/image"; // Importing Next.js Image component
import { useRouter } from "next/navigation";

// Define types for category and form values
interface Category {
  id: number;
  name: string;
  icon: string;
  created_at: string;
  updated_at: string;
  parent_id: number | null;
  all_childrens?: Category[];
}

interface FormValues {
  title: string;
  category: string;
  subcategory?: string;
}

// Validation schemas
const titleSchema = Yup.object({
  title: Yup.string().required("Title is required").trim(),
});

const categorySchema = Yup.object({
  category: Yup.string().required("Category is required"),
});

const PostAd: React.FC = () => {
  const { categories } = useSelector(
    (state: RootState) => state.CategoryListing
  );

  const [showForm2, setShowForm2] = useState(false);
  const [showForm1, setShowForm1] = useState(true);
  const [selectedCategory, setSelectedCategory] = useState<Category | null>(
    null
  );
  const [title, setTitle] = useState("");

  const dispatch: AppDispatch = useDispatch();
  const router = useRouter();

  useEffect(() => {
    const routesToPrefetch = ["/ad-details", "/"];

    routesToPrefetch.forEach((route) => {
      router.prefetch(route);
    });
  }, [router]);

  const handleCategoryChange = (
    event: React.ChangeEvent<HTMLSelectElement>
  ) => {
    const selectedCategoryName = event.target.value;
    const category = categories.data.find(
      (cat: Category) => cat.name === selectedCategoryName
    );
    setSelectedCategory(category || null);
  };

  useEffect(() => {
    dispatch(categoryApiCall());
  }, [dispatch]);

  return (
    <div className="max-w-xl mx-auto md:p-8 md:px-10 font-system text-gray-800">
      <div className=" relative md:p-8 p-5 bg-white rounded-xl">
        <div className="flex justify-between items-center">
          <span className="text-3xl font-semibold">Post Ad</span>
        </div>
        <span
          onClick={() => router.push("/")}
          className="absolute top-0 right-3 text-black cursor-pointer hover:text-gray-800 text-4xl font-normal p-0"
        >
          &times;
        </span>
        {showForm2 && (
          <div className="flex justify-between mt-5 gap-3 items-start xs:items-center">
            <Image
              unoptimized
              src={tick}
              alt="Success"
              width={20}
              height={20}
            />
            <h1 className="text-2xl font-medium mb-4 text-justify break-words overflow-hidden capitalize">
              {truncateTitle(title)}
            </h1>
          </div>
        )}
        <div className="border-gray-700 border-[1px] text-center mt-5 p-5">
          {showForm1 ? (
            <>
              <h1 className="text-3xl font-bold mb-4">Add Title</h1>
              <p className="text-sm font-semibold text-center mb-10">
                Descriptive titles are the best fuel for high performing ads!
              </p>
              <Formik
                initialValues={{ title: "" }}
                validationSchema={titleSchema}
                onSubmit={(values) => {
                  setShowForm2(true);
                  setShowForm1(false);
                  setTitle(values.title);
                }}
              >
                {(formikProps) => (
                  <Form className="space-y-4">
                    <div>
                      <Field
                        type="text"
                        id="title"
                        name="title"
                        className={`block w-full ${
                          formikProps.errors.title && formikProps.touched.title
                            ? "border-red-500"
                            : "border-gray-300"
                        } rounded-md p-2 form-input text-black`}
                        placeholder="Title"
                      />
                    </div>
                    <div>
                      <button type="submit" className="custom-button w-full">
                        Next
                      </button>
                    </div>
                  </Form>
                )}
              </Formik>
            </>
          ) : (
            <>
              <h1 className="text-2xl font-medium mb-4 mt-4">
                Select A Category
              </h1>
              <Formik
                initialValues={{ title, category: "", subcategory: "" }}
                validationSchema={categorySchema}
                onSubmit={(values: FormValues) => {
                  const selectedCategoryId = categories?.data.find(
                    (category: Category) => category.name === values.category
                  )?.id;

                  const selectedSubcategoryId =
                    selectedCategory?.all_childrens?.find(
                      (child: Category) => child.name === values.subcategory
                    )?.id;

                  const finalValues = {
                    title,
                    category: values.category,
                    categoryId: selectedCategoryId || null,
                    subcategory: values.subcategory || null,
                    subcategoryId: selectedSubcategoryId || null,
                  };

                  dispatch(setValues(finalValues));
                  router.push("/ad-details");
                }}
              >
                {(formikProps) => (
                  <Form className="space-y-4">
                    <div>
                      <Field
                        as="select"
                        id="category"
                        name="category"
                        value={formikProps.values.category}
                        onChange={(e: React.ChangeEvent<HTMLSelectElement>) => {
                          formikProps.handleChange(e);
                          handleCategoryChange(e);
                        }}
                        className={`block w-full ${
                          formikProps.errors.category &&
                          formikProps.touched.category
                            ? "border-red-500"
                            : "border-gray-300"
                        } rounded-md p-2 form-select`}
                      >
                        <option value="" disabled>
                          Select
                        </option>
                        {categories?.data.map((category: Category) => (
                          <option key={category.id} value={category.name}>
                            {category.name}
                          </option>
                        ))}
                      </Field>
                    </div>
                    {/* 
                    {selectedCategory?.all_childrens?.length ? (
                      <div>
                        <Field
                          as="select"
                          id="subcategory"
                          name="subcategory"
                          className="block w-full border-gray-300 rounded-md p-2 form-select"
                        >
                          <option value="" disabled>
                            Select Subcategory
                          </option>
                          {selectedCategory.all_childrens.map(
                            (child: Category) => (
                              <option key={child.id} value={child.name}>
                                {child.name}
                              </option>
                            )
                          )}
                        </Field>
                      </div>
                    ) : null} */}

                    <div>
                      <button type="submit" className="custom-button w-full">
                        Next
                      </button>
                    </div>
                  </Form>
                )}
              </Formik>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

export default PostAd;
