"use client";

import { useState, useRef, useEffect, use } from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { set, z } from "zod";
import { useForm } from "react-hook-form";
import { useRouter } from "next/navigation";
import { Separator } from "@/components/ui/separator";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Plus, Trash } from "lucide-react";
import Image from "next/image";
import { createProductSchema } from "@/lib/zodSchemas";
import Delete from "@/components/admin/custom ui/Delete";
import MultiText from "@/components/admin/custom ui/Multitext";
import MultiSelect from "@/components/admin/custom ui/MultiSelect";
import MultiSelectQuantity from "@/components/admin/custom ui/MultiSelectQuantity";

import ToastMessage from "@/components/common/ToastMessage";
import DeleteConfirmationModal from "@/components/admin/custom ui/ImageDeleteMOdal";
import axios from "axios";
import Tiptap from "@/components/TipTap/tiptap";

interface ProductFormProps {
  initialData?: ProductType | null;
}

interface SubSubCategory {
  id: string;
  name: string;
}

interface SubCategory {
  id: string;
  name: string;
  children: SubSubCategory[];
}

interface Category {
  id: string;
  uuid: string;
  name: string;
  children: SubCategory[];
}

interface ProductImages {
  id: string;
  uuid: string;
  file_name: string;
  file_url: string;
}

const ProductForm: React.FC<ProductFormProps> = ({ initialData }) => {
  const [loading, setLoading] = useState(false);
  const router = useRouter();
  // const editor = useRef(null);
  // const [content, setContent] = useState("");

  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  // const editor = useRef(null)

  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const [uploadedImageURLs, setUploadedImageURLs] = useState<ProductImages[]>(
    []
  );
  const [collections, setCollections] = useState<ProductCollectionType[]>([]);
  const [selectCollections, setSelectCollections] = useState(false);
  const [selectedMainCategory, setSelectedMainCategory] = useState<string>("");
  const [selectedSubCategory, setSelectedSubCategory] = useState<string>("");
  const [selectedSubSubCategory, setSelectedSubSubCategory] =
    useState<string>("");
  const [regularPrice, setRegularPrice] = useState<Number>(0);
  const [purchaseCost, setPurchaseCost] = useState<Number>(0);
  const [specialPrice, setSpecialPrice] = useState<Number>(0);
  const [quantity, setQuantity] = useState<string>("");
  const [brand, setBrand] = useState<string>("");

  const [selectedCollections, setSelectedCollections] = useState<Object[]>([]);
  const [selectedCollectionId, setSelectedCollectionId] = useState<string>("");

  const [mainCategories, setMainCategories] = useState<Category[]>([]);

  const [subcategoriesArray, setSubCategoriesArray] = useState<SubCategory[]>(
    []
  );
  const [subSubCategoriesArray, setSubSubCategoriesArray] = useState<
    SubSubCategory[]
  >([]);

  const [deletedImages, setDeletedImages] = useState<string[]>([]);

  const [confirmationModal, setConfirmationModal] = useState<{
    show: boolean;
    url: string | null;
  }>({ show: false, url: null });

  const getCollection = async () => {
    setLoading(true);
    try {
      const response = await fetch("/api/admin/collections", {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      });
      const data = await response.json();

      // console.log(data)

      const data2 = [
        ...data.data.map(
          (collection: CollectionType) => `${collection.id}.${collection.title}`
        ),
      ];

      setCollections(data.data);
      setLoading(false);
    } catch (error: any) {
      setLoading(false);
      console.error("Error fetching collections");
      ToastMessage("Error fetching collections", "error");
    }
  };
  const getCategorie = async () => {
    setLoading(true);
    try {
      const response = await fetch("/api/admin/categories/type/MAIN_CATEGORY", {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      });
      const data = await response.json();

      setMainCategories(data.data);
      setLoading(false);
    } catch (error) {
      setLoading(false);
      ToastMessage("Error fetching categories", "error");
    }
  };

  useEffect(() => {
    getCategorie();
    getCollection();
  }, []);

  useEffect(() => {
    if (initialData && mainCategories.length > 0) {
      console.log("Initial data", initialData);
      console.log(`TAGS - ${initialData.tags}`);

      form.setValue("tags", initialData.tags || []);
      form.setValue("product_name", initialData.product_name || "");
      form.setValue("description", initialData.description || "");
      form.setValue("category", initialData.category.name || "");

      setSelectedMainCategory(initialData.category.name || "");

      const subCategories =
        mainCategories.find((cat) => cat.name === initialData.category.name)
          ?.children || [];

      console.log(`Sub categories ${subCategories}`);

      setSubCategoriesArray(subCategories);

      console.log(`Selected sub categories ${mainCategories}`);

      setSelectedSubCategory(initialData.sub_category.name || "");

      const subSubCategories =
        subCategories.find((cat) => cat.name === initialData.sub_category.name)
          ?.children || [];

      setSubSubCategoriesArray(subSubCategories);

      setSelectedSubSubCategory(initialData.sub_sub_category?.name || "");

      setDescription(initialData.description || "");

      form.setValue("brand", initialData.brand || "");
      setBrand(initialData.brand || "");

      setTitle(initialData.product_name || "");
      setSelectedCollectionId(initialData?.collection?.id || "");

      console.log(`Selected main category = ${initialData.sub_category.name}`);
    } else {
      setUploadedImageURLs([]);
      setSelectedMainCategory("");
      setSelectedSubCategory("");
      setSelectedSubSubCategory("");
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [mainCategories]);

  const form = useForm<z.infer<typeof createProductSchema>>({
    resolver: zodResolver(createProductSchema),
    defaultValues: {
      product_name: initialData?.product_name || "",
      description: initialData?.description || "",
      category: initialData?.category?.name || "",
      sub_category: initialData?.sub_category?.name || "",
      sub_sub_category: initialData?.sub_sub_category?.name || "",
      collection: initialData?.collection?.id || "",
      tags: initialData?.tags || [],
    },
  });

  const handleKeyPress = (
    e:
      | React.KeyboardEvent<HTMLInputElement>
      | React.KeyboardEvent<HTMLTextAreaElement>
  ) => {
    if (e.key === "Enter") {
      e.preventDefault();
    }
  };

  const onSubmit = async (event: any) => {
    event.preventDefault();

    setLoading(true);
    const apiUrl = initialData
      ? `/api/admin/products/${initialData.id}`
      : "/api/admin/products";

    console.log("Form Submitted");


    try {
      const formData = new FormData();

      const mainCategoryId = mainCategories.find(
        (cat) => cat.name === selectedMainCategory
      )?.id;
      const subCategoryId = subcategoriesArray.find(
        (cat) => cat.name === selectedSubCategory
      )?.id;
      const subSubCategoryId = subSubCategoriesArray.find(
        (cat) => cat.name === selectedSubSubCategory
      )?.id;

      formData.append("title", title);
      formData.append("description", description);
      formData.append("mainCategoryId", mainCategoryId as string);
      formData.append("subCategoryId", subCategoryId as string);
      formData.append("subSubCategoryId", subSubCategoryId as string);

      formData.append("category", selectedMainCategory);
      formData.append("subCategory", selectedSubCategory);
      formData.append("subSubCategory", selectedSubSubCategory);

      formData.append("tags", JSON.stringify(form.getValues("tags")));
      // formData.append('colors', JSON.stringify(form.getValues('color')))
      formData.append("collectionId", selectedCollectionId);
      formData.append("brand", brand);

      var response;

      if (initialData) {
        response = await axios.put(apiUrl, formData);
      } else {
        response = await axios.post(apiUrl, formData);
      }
      
      console.log(response)

      if (response.status == 200) {
        setLoading(false);
        initialData
          ? ToastMessage("Product updated successfully", "success")
          : ToastMessage("Product created successfully", "success");

        router.push("/admin/products");
      }
      // console.log(response);
    } catch (error: any) {
    if (axios.isAxiosError(error) && error.response) {
      console.error("API Error:", error.response);

      if (error.response.status === 400) {
        ToastMessage(error.response.data?.message || "A product with this name already exists !", "error");
      } else {
        ToastMessage(error.response.data?.message || "Error creating product", "error");
      }
    } else {
      console.error("Unexpected Error:", error);
      ToastMessage("Unexpected error occurred", "error");
    }
  } finally {
    setLoading(false);
  }
  };

  const handleMainCategoryChange = (
    event: React.ChangeEvent<HTMLSelectElement>
  ) => {
    const category = event.target.value;
    setSelectedMainCategory(event.target.value);

    form.setValue("category", event.target.value);

    if (event.target.value != "" && event.target.value != undefined) {
      const selectedCategory = mainCategories.find(
        (cat) => cat.name === category
      );

      console.log(selectedCategory?.children);

      setSelectedSubCategory("");
      form.setValue("sub_category", "");
      setSelectedSubSubCategory("");
      form.setValue("sub_sub_category", "");

      setSubCategoriesArray([]);
      setSubSubCategoriesArray([]);

      if (selectedCategory) {
        setSubCategoriesArray(selectedCategory?.children);
      }
    }
  };

  const handleSubCategoryChange = (
    event: React.ChangeEvent<HTMLSelectElement>
  ) => {
    setSelectedSubCategory(event.target.value);
    form.setValue("sub_sub_category", event.target.value);

    if (event.target.value != "" && event.target.value != undefined) {
      const selectedCategory = mainCategories.find(
        (cat) => cat.name === selectedMainCategory
      );

      const selectedSubCategory = selectedCategory?.children.find(
        (cat) => cat.name === event.target.value
      );

      console.log(selectedSubCategory?.children);

      setSelectedSubSubCategory("");
      form.setValue("sub_sub_category", "");

      setSubSubCategoriesArray([]);

      if (selectedSubCategory) {
        setSubSubCategoriesArray(selectedSubCategory.children);
      }
    }
  };

  const handleSubSubCategoryChange = (
    event: React.ChangeEvent<HTMLSelectElement>
  ) => {
    setSelectedSubSubCategory(event.target.value);

    // console.log(event.target.value)

    form.setValue("sub_sub_category", event.target.value);

    console.log(selectedMainCategory);
    console.log(selectedSubCategory);
    console.log(selectedSubSubCategory);
  };

  const prevImagesRemove = async (url: string) => {
    uploadedImageURLs.forEach((element) => {
      if (element.file_url === url) {
        setDeletedImages((prev) => [...prev, element.id]);
      }
    });

    setUploadedImageURLs((uploadedImageURLs) =>
      uploadedImageURLs.filter((image) => image.file_url !== url)
    );

    setConfirmationModal({ show: false, url: null });

    console.log(uploadedImageURLs);
  };

  const handelDiscard = () => {
    form.reset();

    setSelectedMainCategory("");
    setSelectedSubCategory("");
    setSelectedSubSubCategory("");
  };

  const setSelected = () => {
    if (selectCollections) {
      setSelectCollections(false);
    }
  };

  const handleDeleteClick = (url: string) => {
    setConfirmationModal({ show: true, url });
    // console.log(uploadedImageURLs)
  };

  const handleCloseModal = () => {
    setConfirmationModal({ show: false, url: null });
  };

  const handleOnUpdate = (editor: string, field: string): void => {
    if (field === "description") {
      console.log("Editor data field:", editor);
      setDescription(editor);
    }
  };

  return (
    <div className="p-10 text-grey-1 max-w-[1400px]" onClick={setSelected}>
      {initialData ? (
        <div className="flex items-center justify-between mx-2">
          <p className="text-heading2-bold max-sm:text-heading3-bold">
            Edit Product
          </p>
          <Delete id={initialData.id} item="products" />
        </div>
      ) : (
        <p className="text-heading2-bold max-sm:text-heading3-bold">
          Add Product
        </p>
      )}
      <Separator className="bg-grey-1 mt-4 mb-7" />
      <Card className="max-w-[1200px] max-sm:max-w-[550px] max-sm:p-8 max-md:p-6 bg-blue-2 shadow-md shadow-black/30 p-16">
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
            <FormField
              control={form.control}
              name="product_name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel htmlFor="title" className="text-[18px]">
                    Title
                  </FormLabel>
                  <FormControl>
                    <Input
                      id="title"
                      placeholder="title"
                      {...field}
                      onKeyUp={(e: any) => setTitle(e.target.value)}
                    />
                  </FormControl>
                  <FormMessage className="text-red-500" />
                </FormItem>
              )}
            />

            <Tiptap
              content={description}
              onUpdate={(newContent) => setDescription(newContent)}
            />

            <div className="md:grid md:grid-cols-3 gap-6">
              <FormField
                control={form.control}
                name="category"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel htmlFor="category" className="text-[18px]">
                      Category
                    </FormLabel>
                    <FormControl>
                      <div>
                        <select
                          id="category"
                          title="category"
                          onChange={handleMainCategoryChange}
                          value={selectedMainCategory}
                          className="w-full p-2 border border-gray-200 rounded-md"
                        >
                          <option value="">--Select--</option>
                          {mainCategories.map((category, index) => (
                            <option
                              key={`${index}-${category.id}`}
                              value={category.name}
                            >
                              {category.name}
                            </option>
                          ))}
                        </select>
                      </div>
                    </FormControl>
                    <FormMessage className="text-red-500" />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="sub_category"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel htmlFor="subCategory" className="text-[18px]">
                      Subcategory
                    </FormLabel>
                    <FormControl>
                      <div>
                        <select
                          id="subCategory"
                          title="subCategory"
                          onChange={handleSubCategoryChange}
                          value={selectedSubCategory}
                          className="w-full p-2 border border-gray-200 rounded-md"
                        >
                          {selectedMainCategory ? (
                            <>
                              <option value="">--Select--</option>
                              {subcategoriesArray.map(
                                (subcategory: SubCategory, index) => (
                                  <option key={index} value={subcategory.name}>
                                    {subcategory.name}
                                  </option>
                                )
                              )}
                            </>
                          ) : (
                            <option value="">Choose A Category First</option>
                          )}
                        </select>
                      </div>
                    </FormControl>
                    <FormMessage className="text-red-500" />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="sub_sub_category"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel htmlFor="subSubCategory" className="text-[18px]">
                      Sub-subcategory
                    </FormLabel>
                    <FormControl>
                      <div>
                        <select
                          id="subSubCategory"
                          title="subSubCategory"
                          onChange={handleSubSubCategoryChange}
                          value={selectedSubSubCategory}
                          className="w-full p-2 border border-gray-200 rounded-md"
                        >
                          {selectedSubCategory ? (
                            <>
                              <option value="">--Select--</option>
                              {subSubCategoriesArray.map(
                                (subSubcategory, index) => (
                                  <option
                                    key={index}
                                    value={subSubcategory.name}
                                  >
                                    {subSubcategory.name}
                                  </option>
                                )
                              )}
                            </>
                          ) : (
                            <option value="">Choose A SubCategory First</option>
                          )}
                        </select>
                      </div>
                    </FormControl>
                    <FormMessage className="text-red-500" />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="tags"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel htmlFor="tags" className="text-[18px]">
                      Tags (Optional)
                    </FormLabel>
                    <FormControl>
                      <MultiText
                        id="tags"
                        placeholder="Tags"
                        value={field.value.filter(
                          (item): item is any => item !== undefined
                        )}
                        onChange={(tag) =>
                          field.onChange([...field.value, tag])
                        }
                        onRemove={(tagToRemove) =>
                          field.onChange([
                            ...field.value.filter((tag) => tag !== tagToRemove),
                          ])
                        }
                      />
                    </FormControl>
                    <FormMessage className="text-red-500" />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="collection"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel htmlFor="collection" className="text-[18px]">
                      Collections (Optional)
                    </FormLabel>
                    <FormControl>
                      <div
                        className={`rounded-lg p-[1.5px] ${
                          selectCollections ? "border-2 border-blue-300" : ""
                        }`}
                        onClick={() => setSelectCollections(!selectCollections)}
                      >
                        <select
                          value={selectedCollectionId}
                          onChange={(e) =>
                            setSelectedCollectionId(e.target.value)
                          }
                          name="collection"
                          id=""
                        >
                          <option value="">Select a collection</option>
                          {collections.map((collection, index) => (
                            <option key={index} value={collection.id}>
                              {collection.title}
                            </option>
                          ))}
                        </select>
                      </div>
                    </FormControl>
                    <FormMessage className="text-red-500" />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="brand"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel htmlFor="brand" className="text-[18px]">
                      Brand Name
                    </FormLabel>
                    <FormControl>
                      <Input
                        id="brand"
                        type="text"
                        placeholder="brand"
                        {...field}
                        onKeyDown={(e: any) => setBrand(e.target.value)}
                      />
                    </FormControl>
                    <FormMessage className="text-red-500" />
                  </FormItem>
                )}
              />
            </div>

            <div className="flex gap-10">
              <Button
                onClick={(e: any) => onSubmit(e)}
                type="submit"
                className="bg-blue-1 text-white"
              >
                {loading ? "Loading..." : initialData ? "Update" : "Submit"}
              </Button>
              {!initialData && (
                <Button
                  type="button"
                  onClick={handelDiscard}
                  className="bg-blue-1 text-white"
                >
                  Discard
                </Button>
              )}
            </div>
          </form>
        </Form>
      </Card>
      <DeleteConfirmationModal
        show={confirmationModal.show}
        onConfirm={() => prevImagesRemove(confirmationModal.url!)}
        onCancel={handleCloseModal}
        message="Are you absolutely sure?"
      />
    </div>
  );
};

export default ProductForm;
