"use client";

import React, {
  useState,
  ChangeEvent,
  useEffect,
  useMemo,
  useRef,
} from "react";
import cross from "../../assets/whitecross.svg";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../store";
import tick from "../../assets/tick.svg";
import { PencilSquareIcon } from "@heroicons/react/24/outline";
import Image from "next/image";
import { Formik, Field, Form } from "formik";
import * as Yup from "yup";
import { useRouter, useSearchParams } from "next/navigation";
// import moment from "moment-timezone";

import {
  categoryApiCall,
  editSeller,
  stateLocation,
  deleteImage,
  repostListing,
} from "../../api/api";
import { toast } from "react-toastify";
import usaFlag from "../../assets/united-states-flag-icon.svg";
import canFlag from "../../assets/canada-flag-icon.svg";
import Link from "next/link";
import { truncateTitle } from "../../utils/commonFunction";
import Modal from "../../components/bayerProfile/pages/components/modal";
import dynamic from "next/dynamic";
const DatePicker = dynamic(() => import("react-datepicker"));

const saleBy = [
  { id: "Owner", title: "Owner" },
  { id: "Business", title: "Business" },
];

const shippingDeliveryData = [
  { id: "Yes", title: "Yes" },
  { id: "No", title: "No" },
];

const productTypeData = [
  { id: "Reserved", title: "Reserved" },
  { id: "Unreserved", title: "Unreserved" },
];
const CountryName = [
  { id: "US", title: "USA" },
  { id: "CAN", title: "Canada" },
];

const timeOut = [
  { id: 12, title: "12 Hrs" },
  { id: 24, title: "24 Hrs" },
  { id: 48, title: "48 Hrs" },
  { id: 72, title: "72 Hrs" },
];

interface FieldErrors {
  description?: any;
  price?: any;
  shipping?: any;
  fuelType?: any;
  vinNumber?: any;
  reservedInput?: any;
  location?: any;
  images?: any;
  titles?: any;
  terms?: any;
  fullAddress?: any;
  taxType?: any;
  taxDetails?: any;
}
const AdDetails: React.FC = () => {
  const [description, setDescription] = useState("");
  const [shipping, setShipping] = useState<any>("");
  const [searchQuery, setSearchQuery] = useState<any>("");
  const [selectedSaleBy, setSelectedSaleBy] = useState<string>("Owner");
  const [shippingDelivery, setShippingDelivery] = useState<string>("No");
  const [timestamp, setTimestamp] = useState<any>(72);
  const [productData, setProductData] = useState<string>("Unreserved");
  const [selectedCategory, setSelectedCategory] = useState<any>({ id: "" });
  const [website, setWebsite] = useState<string>("");
  const [fullAddress, setFullAddress] = useState<string>("");
  const [youtube, setYoutube] = useState<string>("");
  const [tags, setTags] = useState<string[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [modalMessage, setModalMessage] = useState("");
  const [images, setImages] = useState<File[]>([]);
  const [imagePreviews, setImagePreviews] = useState<string[]>([]);
  const [fieldErrors, setFieldErrors] = React.useState<FieldErrors>({});
  const [categoryOptions, setCategoryOptions] = useState<any>([]);
  const [pendingCountryId, setPendingCountryId] = useState<string | null>(null);
  const [pendingCountryValue, setPendingCountryValue] = useState<string | null>(
    null
  );
  const [isDraft, setIsDraft] = useState<any>(0);
  const [isImmediate, setIsImmediate] = useState<any>(1);
  const [product, setProduct] = useState<any>("");
  const [loading, setLoading] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  console.log(loading, isLoading);
  const [fuelType, setFuelType] = useState("");
  const [vinNumber, setVinNumber] = useState("");
  const [reservedInput, setReservedInput] = useState<any>("");
  const [taxType, setTaxType] = useState<string>("no-tax");
  const [taxDetails, setTaxDetails] = useState<string>("");
  const [currency, setCurrency] = useState("CAD");
  const [errorMessage, setErrorMessage] = useState("");
  const [modalOpen, setModalOpen] = useState(false);
  const [location, setLocation] = useState("");
  const [locationLatitude, setLocationLatitude] = useState<any>();
  const [locationLongitude, setLocationLongitude] = useState<any>();
  const [showConfirm, setShowConfirm] = useState(false);
  const [userTimeZone, setUserTimeZone] = useState<string>("");
  const [scheduleStartDate, setScheduleStartDate] = useState<Date | null>(
    new Date()
  );
  const [scheduleSelectedTime, setScheduleSelectedTime] = useState<Date | null>(
    new Date()
  );
  const currencyRates: Record<string, { symbol: string; flag: string }> = {
    USD: { symbol: "US$", flag: usaFlag },
    CAD: { symbol: "C$", flag: canFlag },
  };

  const searchParams = useSearchParams();
  const listingId = searchParams.get("id");
  const MAX_IMAGES = 10;
  const dispatch = useDispatch<any>();
  const router = useRouter();
  const validIds = useMemo(() => [1, 3, 5, 6, 9], []);
  const validIdsForVIN = useMemo(() => [1, 6, 9], []);
  const { categoryId, subcategoryId, title, category, subcategory } =
    useSelector((state: RootState) => state.postAdReducer);
  const [titles, setTitle] = useState<any>(title);

  const { categories } = useSelector(
    (state: RootState) => state.CategoryListing
  );
  const [isCategoryId, setIsCategoryId] = useState<any>(categoryId);
  const [editableTitle, setEditableTitle] = useState(title);
  const [editableCategory, setEditableCategory] = useState(category);
  const [editableSubcategory, setEditableSubcategory] = useState(subcategory);
  const [selectedState, setSelectedState] = useState<any>("");
  const [selectedStateValue, setSelectedStateValue] = useState<string | null>(
    null
  );
  const [isChecked, setIsChecked] = useState(true);
  const [isEditing, setIsEditing] = useState(false);
  const [isEditingTitle, setIsEditingTitle] = useState(false);
  const [isCategory, setCategory] = useState(false);
  const [isCategoryTitle, setCategoryTitle] = useState(false);
  const [isSubCategory, setSubCategory] = useState(false);
  const [isSubCategoryId, setIsSubCategoryId] = useState<any>(subcategoryId);
  console.log(".........", isSubCategoryId);
  const editSellers = useSelector(
    (state: RootState) => state.EditDetailReducer
  );
  const { stateLocationData, loadings } = useSelector(
    (state: RootState) => state.StateLocationReducer
  );

  const selectedCategoryValue = categoryOptions.find(
    (opt: any) => opt.name === (listingId ? product : editableCategory)
  );

  const { incrementData } = useSelector(
    (state: RootState) => state.MessageCountReducer
  );
  const AuctionSellerFee = incrementData?.data?.auctionFee[0]?.boost_fee;

  const selectedRule = incrementData?.data?.auction_fee_rules.find(
    (rule) => rule.hours === timestamp
  );
  const showVinInput = selectedCategoryValue?.vin_option !== "hide";
  const isVinRequired = selectedCategoryValue?.vin_option === "required";
  const today = new Date();
  const maxDate = new Date();
  maxDate.setDate(today.getDate() + 7);
  // Determine minTime based on the selected date
  const isToday = scheduleStartDate?.toDateString() === today.toDateString();
  const minTime = isToday ? new Date() : new Date(today.setHours(0, 0, 0, 0)); // Prevent past times today

  const [isBoostChecked, setIsBoostChecked] = useState(false);

  const handleRadioChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const value = event.target.value === "immediate" ? 1 : 0;
    setIsImmediate(value);

    if (value == 1) {
      setScheduleSelectedTime(new Date());
      setScheduleStartDate(new Date());
    }
  };

  const stateLocationDataListRef = useRef(stateLocationData?.data?.list);

  useEffect(() => {
    stateLocationDataListRef.current = stateLocationData?.data?.list;
  }, [stateLocationData?.data?.list]);

  useEffect(() => {
    const routesToPrefetch = ["/post-ad", "/profile/seller/listing", "/"];

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

  const getFormattedDateTime = () => {
    const pad = (num: number) => String(num).padStart(2, "0");

    if (scheduleStartDate && scheduleSelectedTime) {
      // User selected date & time → format and return
      const datePart = scheduleStartDate.toISOString().split("T")[0];
      const timePart = scheduleSelectedTime.toTimeString().split(" ")[0];
      return `${datePart} ${timePart}`;
    }

    // Otherwise → return current local date & time
    const now = new Date();
    const year = now.getFullYear();
    const month = pad(now.getMonth() + 1);
    const day = pad(now.getDate());
    const hours = pad(now.getHours());
    const minutes = pad(now.getMinutes());
    const seconds = pad(now.getSeconds());

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };

  // const parseAndSetScheduleDateTime = (startDateTime: string) => {
  //   if (!startDateTime) return;

  //   const [datePart, timePartRaw] = startDateTime.split(" ");
  //   const timePart = timePartRaw ?? "00:00:00";

  //   const fixDateFormat = (dateStr: string) => {
  //     if (dateStr.includes(" ") && !dateStr.includes("T")) {
  //       return dateStr.replace(" ", "T");
  //     }
  //     return dateStr;
  //   };

  //   const fullDateTime = new Date(fixDateFormat(`${datePart}T${timePart}`));

  //   if (isNaN(fullDateTime.getTime())) {
  //     return;
  //   }

  //   const dateOnly = new Date(fixDateFormat(datePart));

  //   setScheduleStartDate(dateOnly); // Only the date
  //   setScheduleSelectedTime(fullDateTime); // Full datetime with time
  // };

  const handleInputChange = (e: any) => {
    const rawValue = e.target.value.replace(/,/g, "");
    if (rawValue === "") {
      setReservedInput(undefined);
    } else {
      const numberValue = Number(rawValue);
      if (!isNaN(numberValue)) {
        setReservedInput(numberValue);
      } else {
        setReservedInput(undefined);
      }
    }
  };

  const handleAddTag = () => {
    const newTag = searchQuery.trim().toLowerCase(); // Convert to lowercase to prevent case-sensitive duplicates

    if (!newTag) return; // Prevent empty input
    if (tags.includes(newTag)) {
      setErrorMessage("This tag already exists!");
      return;
    }
    if (tags.length < 5) {
      setTags([...tags, newTag]);
      setSearchQuery(""); // Clear input after adding
      setErrorMessage("");
    }
  };

  const handleRemoveTag = (index: any) => {
    const updatedTags = tags.filter((_, i) => i !== index);
    setTags(updatedTags);
  };

  const handleRemove = () => {
    setShowConfirm(true);
  };

  const confirmRemove = () => {
    router.push(listingId ? "/profile/seller/listing" : "/post-ad");
  };

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

  const handleImageChange = (event: ChangeEvent<HTMLInputElement>) => {
    if (event.target.files) {
      const files = Array.from(event.target.files).filter((file) =>
        file.type.startsWith("image/")
      );

      if (files.length === 0) {
        alert("Please select valid image files.");
        return;
      }

      if (images.length + files.length > MAX_IMAGES) {
        alert(`You can only upload up to ${MAX_IMAGES} images.`);
        return;
      }

      setImages((prev) => [...prev, ...files]);

      const previews = files.map((file) => URL.createObjectURL(file));

      setImagePreviews((prev) => [...prev, ...previews]);
    }
  };

  const handleRemoveImage = async (index: number) => {
    const imageToRemove = imagePreviews[index];
    const searchString = "reservitt.com";
    if (imageToRemove.includes(searchString)) {
      const payload = {
        listing_id: listingId && listingId,
        image_url: imageToRemove,
      };
      try {
        await dispatch(deleteImage(payload));
      } catch {
        return null;
      }
    }

    // Remove the preview image
    setImagePreviews((prev) => {
      const updatedImagePreviews = prev.filter((_, i) => i !== index);
      return updatedImagePreviews;
    });

    // Remove the image from the images array and add to imagesToRemove
    setImages((prev) => {
      const updatedImages = prev.filter((_, i) => i !== index);
      return updatedImages;
    });
  };

  const handleCountrySelection = (id: string, value: string) => {
    setPendingCountryId(id);
    setPendingCountryValue(value);
    dispatch(stateLocation(id)); // keep this if it populates the modal list
    setCurrency(value == "USA" ? "USD" : "CAD");
    setModalOpen(true);
  };

  const handleStateChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const [latitude, longitude] = event.target.value.split(",");
    const selectedValue = event.target.value;
    const selectedName = event.target.dataset.name;

    setSelectedStateValue(selectedValue);
    setSelectedState(selectedName);
    setModalOpen(false);
    setLocationLatitude(latitude);
    setLocationLongitude(longitude);

    // Only update location if a country was selected before
    if (pendingCountryId && pendingCountryValue) {
      setLocation(pendingCountryValue);
      dispatch(stateLocation(pendingCountryId));

      // Clear temp values
      setPendingCountryId(null);
      setPendingCountryValue(null);
    }
  };

  // update listing
  const handleBidRepost = (draftValue: any, updateTypeValue?: any) => {
    const errors: FieldErrors = {};
    if (!description) {
      errors.description = "Description is required.";
    }
    if (!fullAddress) {
      errors.fullAddress = "Full Address is required.";
    }
    if (!titles) {
      errors.titles = "Title is required.";
    }
    if (shippingDelivery === "Yes" && !shipping) {
      errors.shipping = "Shipping details are required.";
    }
    if (productData === "Reserved" && !reservedInput) {
      errors.reservedInput = "Reserved input is required.";
    }
    // Validate VIN Number
    if (isVinRequired) {
      if (!vinNumber) {
        errors.vinNumber = "The VIN Number is required.";
      } else if (vinNumber.length !== 17) {
        errors.vinNumber = "The VIN Number must be exactly 17 characters long.";
      } else if (/[^A-HJ-NPR-Z0-9]/i.test(vinNumber)) {
        errors.vinNumber =
          "The VIN must be alphanumeric and must not contain the letters I, O, or Q.";
      }
    } else {
      if (vinNumber && vinNumber != "null" && vinNumber != null) {
        if (vinNumber.length !== 17) {
          errors.vinNumber =
            "The VIN Number must be exactly 17 characters long.";
        } else if (/[^A-HJ-NPR-Z0-9]/i.test(vinNumber)) {
          errors.vinNumber =
            "The VIN must be alphanumeric and must not contain the letters I, O, or Q.";
        }
      }
    }
    if (validIds.includes(isCategoryId)) {
      if (!fuelType) {
        errors.fuelType = "Fuel type is required.";
      }
    }

    // Ensure at least 3 images are uploaded
    // if (images.length < 3) {
    //   errors.images = "You must upload at least three images.";
    // }

    if (!location) {
      errors.location = "Location is required.";
    }
    if (!isChecked) {
      errors.terms = "You must agree to the terms.";
    }
    if (!taxType) {
      errors.taxType = "Please select a tax option.";
    }
    if (taxType === "taxable" && !taxDetails) {
      errors.taxDetails = "Tax details are required when taxable is selected.";
    }
    // If there are errors, set them in state and stop the submission
    if (Object.keys(errors).length > 0) {
      setFieldErrors(errors);
      const errorValues = Object.values(errors);
      if (errorValues?.length === 1) {
        toast.error(errorValues[0]); // show the specific error
      } else {
        toast.error("Please fix the highlighted errors"); // generic message
      }
      return;
    }
    // Clear field errors before proceeding
    setFieldErrors({});

    // Set loading state to true
    {
      if (draftValue == 1 && updateTypeValue == "Save draft") {
        setIsLoading(true);
      }

      if (draftValue == 0 && updateTypeValue == "draft") {
        setLoading(true);
      }

      if (draftValue == 0 && updateTypeValue == "post") {
        setLoading(true);
      }
    }
    // Create FormData object to handle image file uploads

    const formData = new FormData();
    // Append updated data
    formData.append("product_id", listingId ?? "");
    formData.append("product_name", titles);
    formData.append("category_id", selectedCategory?.id || "");
    formData.append("quantity", "1");
    formData.append("shipping_details", shipping);
    {
      if (reservedInput) {
        formData.append("reserve_price", reservedInput);
      }
    }
    formData.append("description", description);
    formData.append("sale_by", selectedSaleBy);
    formData.append("youtube_link", youtube);
    formData.append("website_link", website);
    formData.append("full_address", fullAddress);
    formData.append("location", location);
    formData.append("tags", JSON.stringify(tags));
    formData.append("is_draft", draftValue);
    formData.append("is_immediate", isImmediate);
    formData.append("start_datetime", getFormattedDateTime());
    formData.append("auction_ends_at", timestamp);
    formData.append("fuel_type", fuelType);
    formData.append("vin_number", vinNumber);
    formData.append("shipping_delivery", shippingDelivery);
    formData.append("product_type", productData);
    formData.append("location_latitude", locationLatitude);
    formData.append("location_longitude", locationLongitude);
    formData.append("update_type", updateTypeValue);
    formData.append("sub_location", selectedState);
    formData.append("timezone", userTimeZone);
    formData.append("tax_type", taxType);
    formData.append("tax_details", taxDetails);
    formData.append("product_id", listingId);
    formData.append("is_boosted", isBoostChecked ? "1" : "0");
    formData.append("currency", currency);

    // Append images to be uploaded
    images.forEach((image, index) => {
      formData.append(`images[${index}]`, image);
    });
    // Append existing images (as URLs, in a different field)
    imagePreviews.forEach((imageUrl, index) => {
      formData.append(`existing_images[${index}]`, imageUrl);
    });

    // Dispatch the action with formData
    dispatch(repostListing(formData))
      .unwrap()
      .then(() => {
        toast("Repost successFully");

        setIsDraft(draftValue);
        router.push("/");
      })
      .catch((err: any) => {
        setLoading(false);
        setIsLoading(false);
        // console.error("Update failed:", err);
        setModalMessage(
          err?.message || "Failed to update the listing. Please try again."
        );
        setShowModal(true);
      });
  };

  useEffect(() => {
    const fetchCategoryData = async () => {
      try {
        if (listingId) {
          await dispatch(editSeller(listingId));
        }

        const resultAction = await dispatch(categoryApiCall());
        if (categoryApiCall.fulfilled.match(resultAction)) {
          setCategoryOptions(resultAction.payload?.data);
        }
      } catch {
        return null;
      }
    };

    fetchCategoryData();
  }, [dispatch, listingId]);

  useEffect(() => {
    if (listingId && editSellers) {
      const listing = editSellers?.seller;

      if (listing?.data?.listing?.id == listingId) {
        const websiteLink = listing?.data?.listing?.website_link;
        const youtubeLink = listing?.data?.listing?.youtube_link;
        setDescription(listing?.data?.listing?.description);
        setSelectedState(listing?.data?.listing?.sub_location);
        setFuelType(listing?.data?.listing?.fuel_type);
        setShipping(listing?.data?.listing?.shipping_details);
        setTitle(listing?.data?.listing?.product_name);
        setIsDraft(listing?.data?.listing?.is_draft);
        setVinNumber(listing?.data?.listing?.vin_number);
        setReservedInput(listing?.data?.listing?.reserve_price ?? "");
        try {
          const parsedTags = JSON.parse(listing.data?.listing?.tags);
          setTags(Array.isArray(parsedTags) ? parsedTags : []);
        } catch {
          return null;
        }
        setImagePreviews(listing?.data?.listing?.images || []);
        setIsBoostChecked(listing?.data?.listing?.is_boosted);
        setSelectedSaleBy(listing?.data?.listing?.sale_by);
        setLocationLongitude(listing?.data?.listing?.location_longitude);
        setLocationLatitude(listing?.data?.listing?.location_latitude);
        setProductData(listing?.data?.listing?.product_type);
        setTaxDetails(listing?.data?.listing?.tax_details);
        setTaxType(listing?.data?.listing?.tax_type);
        const matchedState = stateLocationDataListRef?.current?.find(
          (item: any) => {
            const lat = listing?.data?.listing?.location_latitude;
            const lon = listing?.data?.listing?.location_longitude;

            const isMatch = item.latitude == lat && item.longitude == lon;
            return isMatch;
          }
        );

        if (matchedState) {
          setSelectedState(matchedState.name);
        }
        const value =
          listing?.data?.listing?.location_latitude +
          "," +
          listing?.data?.listing?.location_longitude;
        setSelectedStateValue(value);
        // console.log("from here222222222")

        setLocation(listing?.data?.listing?.location);
        setWebsite(
          websiteLink === null || websiteLink === "null" ? "" : websiteLink
        );
        setYoutube(
          youtubeLink === null || youtubeLink === "null" ? "" : youtubeLink
        );
        setFullAddress(listing?.data?.listing?.full_address);
        setSelectedCategory(listing?.data?.listing?.category);
        setProduct(listing?.data?.listing?.category?.name);
        setIsCategoryId(listing?.data?.listing?.category_id);
        setIsImmediate(listing?.data?.listing?.is_immediate);
        // parseAndSetScheduleDateTime(listing?.data?.listing?.start_datetime);
        setTimestamp(listing?.data?.listing?.expiring_hrs);
      }
    }
  }, [listingId, editSellers]);

  useEffect(() => {
    if (!validIds.includes(Number(isCategoryId))) {
      setFuelType("");
    }

    if (!validIdsForVIN.includes(Number(isCategoryId))) {
      setVinNumber("");
    }
  }, [isCategoryId, validIds, validIdsForVIN]);

  useEffect(() => {
    const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
    // console.log("check time", timeZone);
    setUserTimeZone(timeZone);
  }, []);

  return (
    <div className="bg-[#F8F9F9] md:p-6 xs:p-5 flex max-w-7xl m-auto font-system py-5  md:flex-row xs:flex-col gap-5 lg:pt-14">
      {/* left section */}
      <section className="md:w-[29rem] flex flex-col m-10 mt-0 space-y-4 xs:mx-0 xs:w-full">
        <div className="bg-black text-white flex justify-between w-full p-5 rounded-lg">
          <span className="text-xl font-medium">
            {isDraft ? "Edit Draft" : listingId ? "Edit Post" : "Post Ad"}
          </span>
          <button onClick={handleRemove} className="w-4 h-4 relative p-2 pt-4">
            <Image
              unoptimized
              src={cross}
              alt="Remove"
              fill
              style={{ objectFit: "contain" }}
            />
          </button>
          {showConfirm && (
            <div className="fixed inset-0 flex items-center justify-center bg-gray-900 bg-opacity-50 w-full z-50">
              <div className="bg-white p-6 rounded-lg shadow-lg">
                <p className="text-lg font-semibold mb-4 text-black">
                  Are you sure you want to stop{" "}
                  {listingId ? "editing" : "creating"} the ad?
                </p>
                <div className="flex justify-center gap-4">
                  <button
                    className="px-4 py-2 bg-gray-300 rounded-lg hover:bg-gray-400"
                    onClick={() => setShowConfirm(false)}
                  >
                    No
                  </button>
                  <button
                    className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600"
                    onClick={confirmRemove}
                  >
                    Yes
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
        <div className="flex bg-white p-5  rounded-lg gap-3 w-fill">
          <div className="relative w-6 h-6">
            <Image
              unoptimized
              src={tick}
              alt="Tick"
              fill
              style={{ objectFit: "contain" }}
            />
          </div>
          <div className="flex flex-col text-left w-full ">
            <div className="border-b-2 border-gray-400 pb-1 flex justify-between">
              <p className="text-base font-medium text-gray-400">Title </p>
              <div>
                {!isEditing && (
                  <button
                    onClick={() => setIsEditing(true)}
                    className="text-gray-500 hover:text-gray-700 p-0"
                  >
                    <PencilSquareIcon className="h-8 w-8" />
                  </button>
                )}
              </div>
            </div>
            <div className="space-y-2">
              {listingId ? (
                <input
                  type="test"
                  id="Title"
                  name="Title"
                  value={titles}
                  onChange={(e) => setTitle(e.target.value)}
                  className={`flex-1 bg-white capitalize outline-none hover:outline-none rounded  p-2 focus:outline-none focus:ring-0 text-black ${
                    fieldErrors.titles && "border-red-500"
                  }`}
                />
              ) : (
                <>
                  {isEditing ? (
                    <>
                      <input
                        type="text"
                        id="Title"
                        name="Title"
                        value={editableTitle}
                        onChange={(e) => setEditableTitle(e.target.value)}
                        onBlur={() => setIsEditing(false)} // Save and exit edit mode on blur
                        className={`flex-1 bg-white capitalize outline-none border-none hover:outline-none rounded  p-2 mt-1 focus:outline-none focus:ring-0 text-black `}
                      />
                      <div className=" border-b-2 border-black"> </div>
                    </>
                  ) : (
                    <p className="text-black text-lg capitalize font-medium  w-full ">
                      {truncateTitle(editableTitle)}
                    </p>
                  )}
                </>
              )}
              {fieldErrors.titles && (
                <div className="text-red-500 font-semibold p-1">
                  {fieldErrors.titles}
                </div>
              )}
            </div>
          </div>
        </div>
        <div className="flex  bg-white p-5 rounded-lg ">
          <div className="flex gap-3 items-start w-fill ">
            {listingId && (
              <div className="relative w-6 h-6">
                <Image
                  unoptimized
                  src={tick}
                  alt="Tick"
                  fill
                  style={{ objectFit: "contain" }}
                />
              </div>
            )}
            <div className="flex flex-col text-left w-full ">
              {listingId ? (
                <>
                  <div className="border-b-2 border-gray-400 pb-1 w-full flex justify-between">
                    <p className="text-base font-semibold text-gray-400">
                      Category
                    </p>
                    <div>
                      {!isCategory && (
                        <button
                          onClick={() => setCategory(true)}
                          className="text-gray-500 hover:text-gray-700 p-0"
                        >
                          <PencilSquareIcon className="h-8 w-8" />
                        </button>
                      )}
                    </div>
                  </div>
                  <select
                    value={product}
                    onChange={(e) => {
                      setProduct(e.target.value);
                      const selectedCategory = categories?.data?.find(
                        (item: any) => item.name === e.target.value
                      );
                      setIsCategoryId(selectedCategory?.id || null);
                      setSelectedCategory(selectedCategory || null);
                    }}
                    onBlur={() => setCategory(false)}
                    className="p-2 border border-gray-300 text-black rounded-md mt-2 w-72"
                  >
                    <option className="text-black" value="" disabled>
                      Select a category
                    </option>
                    {categories?.data?.map((item: any) => (
                      <option key={item.id} value={item?.name}>
                        <p className="text-black">{item?.name}</p>
                      </option>
                    ))}
                  </select>
                </>
              ) : (
                <>
                  {!subcategory && category && (
                    <div className="flex gap-3">
                      <div className="relative w-6 h-6">
                        <Image
                          unoptimized
                          src={tick}
                          alt="Tick"
                          fill
                          style={{ objectFit: "contain" }}
                        />
                      </div>
                      <div className="w-full">
                        <div className="border-b-2 border-gray-400 pb-1 w-full flex justify-between">
                          <p className="text-base font-semibold text-gray-400 ">
                            Category
                          </p>
                          <div>
                            {!isCategory && (
                              <button
                                onClick={() => setCategory(true)}
                                className="text-gray-500 hover:text-gray-700 p-0"
                              >
                                <PencilSquareIcon className="h-8 w-8" />
                              </button>
                            )}
                          </div>
                        </div>
                        {isCategory ? (
                          <>
                            <select
                              value={editableCategory}
                              onChange={(e) => {
                                setEditableCategory(e.target.value);
                                const selectedCategory = categories?.data?.find(
                                  (item: any) => item.name === e.target.value
                                );
                                setIsCategoryId(selectedCategory?.id || null);
                              }}
                              onBlur={() => setCategory(false)}
                              className="p-2 border border-gray-300 text-black rounded-md mt-2 w-72"
                            >
                              <option className="text-black" value="" disabled>
                                Select a category
                              </option>
                              {categories?.data?.map((item: any) => (
                                <option key={item.id} value={item.name}>
                                  <p className="text-black">{item.name}</p>
                                </option>
                              ))}
                            </select>
                          </>
                        ) : (
                          <p className="text-black text-lg capitalize font-medium w-full">
                            {truncateTitle(editableCategory)}
                          </p>
                        )}
                      </div>
                    </div>
                  )}
                  {subcategory && (
                    <>
                      <div>
                        <div className="border-b-2 border-gray-400 pb-1 w-full flex justify-between">
                          <p className="text-xs font-semibold text-gray-400">
                            Subcategory
                          </p>
                          <div>
                            {!isSubCategory && (
                              <button
                                onClick={() => setSubCategory(true)}
                                className="text-gray-500 hover:text-gray-700 p-0"
                              >
                                <PencilSquareIcon className="h-8 w-8" />
                              </button>
                            )}
                          </div>
                        </div>

                        {isSubCategory ? (
                          <select
                            value={editableSubcategory}
                            onChange={(e) => {
                              setEditableSubcategory(e.target.value);
                              const selectedCategory = categories?.data?.find(
                                (item: any) => item.name === e.target.value
                              );
                              setIsSubCategoryId(selectedCategory?.id || null);
                            }}
                            onBlur={() => setSubCategory(false)}
                            className="p-2 border border-gray-300 rounded-md"
                          >
                            <option value="" disabled>
                              Select a subcategory
                            </option>
                            {categories?.data?.map((item: any) => (
                              <option key={item.id} value={item.name}>
                                {item.name}
                              </option>
                            ))}
                          </select>
                        ) : (
                          <p className="text-black text-lg capitalize font-medium w-full">
                            {truncateTitle(editableSubcategory)}
                          </p>
                        )}
                      </div>
                    </>
                  )}
                </>
              )}
            </div>
          </div>
        </div>
      </section>

      {/* right section */}
      <section className="flex flex-col space-y-2  xs:w-full">
        <section className="bg-white flex flex-col  rounded-lg p-5">
          <div className="border-b text-left pb-3">
            <h2 className="text-[#3D3D3D] text-[30px] font-semibold">
              {isDraft
                ? "Edit Draft Details"
                : listingId
                ? "Edit Details"
                : "Ad Details"}
            </h2>
          </div>
          <div className="flex space-x-6 p-5 xs:px-0 ">
            <div className="text-gray-600 font-semibold w-[9rem] text-left text-lg">
              For Sale By:
              {/* <p className="text-xs text-gray-400 text-justify">(optional)</p> */}
            </div>
            <div className="md:flex md:gap-5">
              {saleBy.map((value) => (
                <div key={value.id} className="flex items-center">
                  <input
                    id={value.id}
                    name="saleby"
                    type="radio"
                    value={value.id}
                    checked={String(selectedSaleBy) === String(value.id)}
                    onChange={(e) => setSelectedSaleBy(e.target.value)}
                    className="h-5 w-5 border-none bg-gray-200 text-[#021F71] focus:ring-white"
                  />

                  <label
                    htmlFor={value.id}
                    className="ml-3 block font-medium leading-6 text-gray-900 text-lg"
                  >
                    {value.title}
                  </label>
                </div>
              ))}
            </div>
          </div>
          {/* category */}
          {listingId ? (
            <div>
              <div className="flex flex-col md:flex-row items-start gap-[16px] ">
                <div className="flex justify-between w-full md:w-auto">
                  <div className="text-black font-semibold md:w-[10rem] xs:w-[10rem] text-lg text-justify pt-1 md:pt-3">
                    Category update:
                  </div>
                  <div className="md:hidden">
                    {!isCategory && (
                      <button
                        onClick={() => setCategory(true)}
                        className="text-gray-500 hover:text-gray-700 p-0 ml-1"
                      >
                        <PencilSquareIcon className="h-8 w-8" />
                      </button>
                    )}
                  </div>
                </div>
                <select
                  value={product}
                  onChange={(e) => {
                    setProduct(e.target.value);
                    const selectedCategory = categories?.data?.find(
                      (item: any) => item.name === e.target.value
                    );
                    setIsCategoryId(selectedCategory?.id || null);
                    setSelectedCategory(selectedCategory || null);
                  }}
                  onBlur={() => setCategory(false)}
                  className="p-2 border border-gray-300 text-black rounded-md mt-2 w-72"
                >
                  <option className="text-black" value="" disabled>
                    Select a category
                  </option>
                  {categories?.data?.map((item: any) => (
                    <option key={item.id} value={item.name}>
                      <p className="text-black">{item.name}</p>
                    </option>
                  ))}
                </select>
                <div className="hidden md:block pt-2">
                  {!isCategory && (
                    <button
                      onClick={() => setCategory(true)}
                      className="text-gray-500 hover:text-gray-700 p-0 ml-1"
                    >
                      <PencilSquareIcon className="h-8 w-8" />
                    </button>
                  )}
                </div>
              </div>
            </div>
          ) : (
            <div className="flex md:py-5  md:space-x-4 md:flex-row xs:px-0 xs:flex-col xs:space-x-0 md:gap-0 xs:gap-2">
              <div className="text-black font-semibold md:w-[9rem] xs:flex justify-between text-left text-lg">
                <p className=" flex">
                  Category: <span className="text-red-600 text-2xl">*</span>
                </p>
                <div className="md:pl-40 ">
                  {!isCategoryTitle && (
                    <button
                      onClick={() => setCategoryTitle(true)}
                      className="text-gray-500 hover:text-gray-700 p-0 md:hidden"
                    >
                      <PencilSquareIcon className="h-8 w-8" />
                    </button>
                  )}
                </div>
              </div>

              <div className="lg:pl-4">
                {isCategoryTitle ? (
                  <select
                    value={editableCategory}
                    onChange={(e) => {
                      setEditableCategory(e.target.value);
                      const selectedCategory = categories?.data?.find(
                        (item: any) => item.name === e.target.value
                      );
                      setIsCategoryId(selectedCategory?.id || null);
                    }}
                    onBlur={() => setCategoryTitle(false)}
                    className="p-2 border text-black  border-gray-300 rounded-md mt-2 w-72"
                  >
                    <option value="" disabled>
                      Select a category
                    </option>
                    {categories?.data?.map((item: any) => (
                      <option
                        className="text-black"
                        key={item.id}
                        value={item.name}
                      >
                        {item.name}
                      </option>
                    ))}
                  </select>
                ) : (
                  <Formik
                    initialValues={{
                      category: "",
                    }}
                    validationSchema={categorySchema}
                    onSubmit={(values: any) => {
                      console.log(values);
                    }}
                  >
                    {(formikProps) => {
                      return (
                        <>
                          <Form className="space-y-4 ">
                            <div>
                              {/* Category Field (Read-Only) */}
                              <Field
                                type="text"
                                id="category"
                                name="category "
                                value={editableCategory} // Show the selected category value
                                readOnly // Make it read-only so the user can't modify it
                                className={`block text-black xs:w-full md:w-[17rem] ${
                                  formikProps.errors.category &&
                                  formikProps.touched.category
                                    ? "border-red-500"
                                    : "border-gray-300"
                                } rounded-md truncate  p-2 form-input`} // Using 'form-input' instead of 'form-select'
                              />
                            </div>
                          </Form>
                        </>
                      );
                    }}
                  </Formik>
                )}
              </div>
              <div className="">
                {!isCategoryTitle && (
                  <button
                    onClick={() => setCategoryTitle(true)}
                    className="hidden md:block text-gray-500 hover:text-gray-700 p-0"
                  >
                    <PencilSquareIcon className="h-8 w-8" />
                  </button>
                )}
              </div>
            </div>
          )}

          {/* Title */}
          <div className="md:flex md:flex-row p-5 xs:flex-col px-0">
            <div
              className="text-black font-semibold md:w-[11rem] xs:w-[6rem] text-lg text-justify    
             "
            >
              Ad Title:<span className="text-red-600 text-2xl">*</span>
              {/* <p className="text-xs text-gray-400 text-justify">(optional)</p> */}
            </div>
            <div className="flex md:w-[323px] xs:w-full xs:justify-between xs:pt-1">
              <div className="max-w-[14rem]">
                {listingId ? (
                  <input
                    type="test"
                    id="Title"
                    name="Title"
                    value={titles}
                    onChange={(e) => setTitle(e.target.value)}
                    className={`flex-1  capitalize  bg-white outline-none hover:outline-none rounded lg p-2 focus:outline-none focus:ring-0 text-black${
                      fieldErrors.titles && "border-red-500"
                    }`}
                  />
                ) : (
                  <>
                    {isEditingTitle ? (
                      <>
                        <input
                          type="text"
                          id="Title"
                          name="Title"
                          value={editableTitle}
                          onChange={(e) => setEditableTitle(e.target.value)}
                          onBlur={() => setIsEditingTitle(false)} // Save and exit edit mode on blur
                          className={`flex-1 bg-white break-words capitalize border-none  outline-none hover:outline-none rounded  p-2 mt-1 focus:outline-none focus:ring-0 text-black w-full ${
                            fieldErrors.titles && "border-red-500"
                          }`}
                        />
                        <div className=" border-b-2 border-black"> </div>
                      </>
                    ) : (
                      <p className="text-black text-lg capitalize font-medium break-words text-justify ">
                        {truncateTitle(editableTitle)}
                      </p>
                    )}
                  </>
                )}
                {fieldErrors.titles && (
                  <div className="text-red-500 font-semibold p-1">
                    {fieldErrors.titles}
                  </div>
                )}
              </div>
              <div className="">
                {!isEditingTitle && (
                  <button
                    className="text-gray-500 hover:text-gray-700 p-0"
                    onClick={() => setIsEditingTitle(true)}
                  >
                    <PencilSquareIcon className="h-8 w-8" />
                  </button>
                )}
              </div>
            </div>
          </div>
          {/* Description */}
          <div className="flex md:py-5 md:space-x-8 md:flex-row xs:space-x-0 xs:px-0 xs:flex-col md:gap-0 xs:gap-2">
            <div className="text-black font-semibold w-[9rem] text-left text-lg">
              <p className="flex">
                Description: <span className="text-red-600 text-2xl">*</span>
              </p>
            </div>
            <div>
              <div className="space-y-2">
                <textarea
                  id="description"
                  name="description"
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                  placeholder="Enter Description..."
                  className={`w-full text-black border border-gray-300 p-2 rounded-md ${
                    fieldErrors.description ? "border-red-500" : ""
                  }`}
                  rows={6}
                  cols={50}
                />
              </div>
              {fieldErrors.description && (
                <div className="text-red-500 font-semibold p-1">
                  {fieldErrors.description}
                </div>
              )}
            </div>
          </div>
          {/* Tag */}
          <div>
            <div className="flex md:space-x-8 md:py-5 mt-2 md:flex-row xs:flex-col xs:space-x-0 xs:p-0 xs:gap-4">
              <div className="text-gray-600 font-semibold w-[8rem] text-left text-lg">
                Tags:
                <p className="text-xs text-gray-400 text-justify">(optional)</p>
              </div>
              <div>
                <p className="font-medium text-lg text-black text-start">
                  Increase your ad exposure.<br></br>
                  Enter up to 5 keywords someone could search to find your ad.
                </p>
              </div>
            </div>
            <div className="flex gap-2 lg:pl-[11rem]">
              <div className="flex items-center border border-gray-300 rounded-md p-1 md:w-72 xs:m-0 xs:w-full">
                <input
                  type="text"
                  placeholder="Enter Keywords..."
                  value={searchQuery}
                  onChange={(e) => {
                    setSearchQuery(e.target.value);
                    setErrorMessage(""); // Clear error when typing
                  }}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      handleAddTag();
                    }
                  }}
                  disabled={tags.length >= 5}
                  className="flex-1 border-none outline-none focus:outline-none focus:ring-0 text-black placeholder:text-gray-600 xs:w-full"
                />
              </div>
              <button
                onClick={handleAddTag}
                className="bg-black text-xl font-medium rounded-md text-white px-8 cursor-pointer"
              >
                Add
              </button>
            </div>

            <div className=" flex flex-wrap space-x-2 lg:pl-[10.9rem]">
              {tags.map((tag, index) => (
                <div
                  key={index}
                  className="bg-[#F8CB1F] text-white font-medium rounded-full text-lg px-3 py-1 mt-2 flex gap-2"
                >
                  {tag}

                  <button
                    onClick={() => handleRemoveTag(index)}
                    className=" text-white text-start p-0 "
                  >
                    ×
                  </button>
                </div>
              ))}
            </div>
            {errorMessage && (
              <p className="text-red-500 mt-2 text-lg text-start lg:pl-[11rem]">
                {errorMessage}
              </p>
            )}

            {/* Display warning if max tags reached */}
            {tags.length > 5 && (
              <p className="text-red-500 mt-2 text-lg text-start lg:pl-[11rem]">
                Maximum of 5 tags allowed.
              </p>
            )}
          </div>
          {/* Time out */}
          <div className="flex space-x-6 p-5 xs:px-0">
            <div className="text-gray-600 font-semibold xs:w-[9rem] md:w-[10rem] text-left text-lg">
              Auction Duration
            </div>
            <div className="md:flex gap-5">
              {timeOut.map((value: any) => (
                <div key={value.id} className="flex items-center">
                  <input
                    id={value.id}
                    name="timestamp"
                    type="radio"
                    value={value.id}
                    checked={timestamp === value.id}
                    onChange={(e) => setTimestamp(Number(e.target.value))} // Handle change
                    className="h-5 w-5 border-none bg-gray-200 text-[#021F71] focus:ring-white"
                  />
                  <label
                    htmlFor={value.id}
                    className="ml-3 block font-medium leading-6 text-gray-900 text-lg"
                  >
                    {value.title}
                  </label>
                </div>
              ))}
            </div>
          </div>

          {/* auction Duration */}
          <section>
            <div className="flex gap-2 flex-row items-start md:items-center w-full">
              {/* Label with red underline */}
              <div className="text-gray-600 font-semibold xs:w-[9rem] md:w-[11rem] text-left text-lg">
                When to start auction
              </div>
              <div className="flex gap-4 flex-col md:flex-row">
                {/* Radio Buttons and Calendar */}

                <div className="flex items-center">
                  <input
                    type="radio"
                    value="immediate"
                    checked={isImmediate === 1}
                    onChange={handleRadioChange}
                    className="h-5 w-5 border-none bg-gray-200 text-[#021F71] focus:ring-white"
                  />
                  <label
                    htmlFor="immediate"
                    className="ml-3 block font-medium leading-6 text-gray-900 text-lg"
                  >
                    Immediately
                  </label>
                </div>
                <div className="flex items-center">
                  <input
                    type="radio"
                    value="schedule"
                    checked={isImmediate === 0}
                    onChange={handleRadioChange}
                    className="h-5 w-5 border-none bg-gray-200 text-[#021F71] focus:ring-white"
                  />
                  <label
                    htmlFor="schedule"
                    className="ml-3 block font-medium leading-6 text-gray-900 text-lg"
                  >
                    Schedule
                  </label>
                </div>
                {isImmediate === 0 && (
                  <div className="flex flex-col md:flex-row items-start md:items-center gap-4 pt-2">
                    {/* Calendar Input */}
                    <DatePicker
                      selected={scheduleStartDate}
                      onChange={(date: any) =>
                        setScheduleStartDate(date as Date)
                      }
                      className="border border-gray-300 rounded-md px-2 py-1 w-32"
                      dateFormat="MMM d, yyyy"
                      minDate={today} // Disable past dates
                      maxDate={maxDate} // Restrict to the next 7 days
                      popperPlacement="bottom-start"
                    />
                    <DatePicker
                      selected={scheduleSelectedTime}
                      onChange={(date: any) => setScheduleSelectedTime(date)}
                      showTimeSelect
                      showTimeSelectOnly
                      timeFormat="hh:mm aa"
                      dateFormat="h:mm aa"
                      minTime={minTime} // Prevent selecting past time on today's date
                      maxTime={new Date(today.setHours(23, 59, 59, 999))} // Max time set to end of the day
                      className="border rounded h-8 p-2 w-24"
                    />
                  </div>
                )}
              </div>
            </div>
          </section>

          {/* Shipping Delivery */}
          <div className="flex space-x-6 p-5 xs:px-0">
            <div className="text-black font-semibold w-[10rem] text-left text-lg">
              Shipping delivery available:
            </div>
            <div className="md:flex md:gap-5 md:items-center">
              {shippingDeliveryData.map((value: any) => (
                <div key={value.id} className="flex items-center">
                  <input
                    id={value.id}
                    name="shippingDelivery"
                    type="radio"
                    value={value.id}
                    checked={shippingDelivery === value.id} // Manage checked state
                    onChange={(e) => setShippingDelivery(e.target.value)} // Handle change
                    className="h-5 w-5 border-none bg-gray-200 text-[#021F71] focus:ring-white"
                  />
                  <label
                    htmlFor={value.id}
                    className="ml-3 block font-medium leading-6 text-gray-900 text-lg"
                  >
                    {value.title}
                  </label>
                </div>
              ))}
            </div>
          </div>

          {/* Conditionally Render Shipping Details Field */}
          {shippingDelivery === "Yes" && (
            <div className="flex flex-col items-start md:py-5 mt-5 xs:px-0">
              <div className="flex md:flex-row xs:flex-col md:gap-0 xs:gap-2">
                <label className="text-gray-600 font-semibold w-[11rem] text-left text-lg">
                  Shipping Details{" "}
                  <span className="text-red-600 text-2xl">*</span>
                </label>
                <div>
                  <input
                    type="text"
                    id="shipping"
                    name="shipping"
                    value={shipping}
                    onChange={(e) => setShipping(e.target.value)}
                    placeholder="Shipping Detail..."
                    className={`border-gray-300 text-black placeholder:text-gray-600 rounded-md md:w-64 xs:w-full resize-none ${
                      fieldErrors.shipping && "border-red-500"
                    }`}
                  />
                  {fieldErrors.shipping && (
                    <div>
                      <p className="text-red-500 text-sm mt-2 font-semibold text-start">
                        {fieldErrors.shipping}
                      </p>
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* fuel type with static id */}
          {/* {validIds.includes(Number(isCategoryId)) && ( */}
          <div className="flex flex-col items-start md:py-5 mt-5 xs:px-0">
            <div className="flex md:flex-row xs:flex-col md:gap-0 xs:gap-2">
              <label className="text-gray-600 font-semibold w-[11rem] text-left text-lg">
                Fuel Type <span className="text-red-600 text-2xl">*</span>
              </label>
              <div>
                <select
                  id="fuelType"
                  name="fuelType"
                  value={fuelType}
                  onChange={(e) => setFuelType(e.target.value)}
                  className={`border-gray-300 text-black rounded-md md:w-64 xs:w-full resize-none ${
                    fieldErrors.fuelType && "border-red-500"
                  }`}
                >
                  <option value="">Select fuel type</option>
                  <option value="gas">Gas</option>
                  <option value="diesel">Diesel</option>
                  <option value="electric">Electric</option>

                  <option value="propane">Propane</option>
                  <option value="none">none</option>
                </select>
                {fieldErrors.fuelType && (
                  <div>
                    <p className="text-red-500 text-sm mt-2 font-semibold text-start">
                      {fieldErrors.fuelType}
                    </p>
                  </div>
                )}
              </div>
            </div>
          </div>
          {/* )} */}

          {/* Vin number for specific id's */}
          {showVinInput && (
            <div className="flex flex-col items-start md:py-5 mt-5 xs:px-0">
              <div className="flex md:flex-row xs:flex-col md:gap-0 xs:gap-2">
                <label className="text-gray-600 font-semibold w-[11rem] text-left text-lg">
                  VIN Number{" "}
                  {isVinRequired && (
                    <span className="text-red-600 text-2xl">*</span>
                  )}
                </label>
                <div className=" flex flex-col gap-1">
                  <input
                    type="text"
                    id="vinNumber"
                    name=""
                    value={vinNumber}
                    onChange={(e) => setVinNumber(e.target.value.toUpperCase())}
                    placeholder="Enter 17 character VIN Number..."
                    className={`border-gray-300 text-black rounded-md md:w-64 xs:w-full resize-none ${
                      fieldErrors.vinNumber && "border-red-500"
                    }`}
                  />
                  {fieldErrors.vinNumber && (
                    <div className="text-wrap">
                      <p className="text-red-500 text-left text-sm mt-2 font-semibold text-wrap">
                        {fieldErrors.vinNumber}
                      </p>
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}
        </section>
        {/* Media */}
        <section className="bg-white flex flex-col rounded-lg p-5 space-y-4">
          <h1 className="text-[#3D3D3D] text-[45px] font-semibold text-left">
            Media
          </h1>
          <hr />
          <div className="text-justify font-semibold md:pt-5 xs:p-0">
            <p className="text-black text-xl">
              Add photos to attract interest to your ad
              <span className="text-red-600 text-2xl">*</span>
            </p>
            <br />
            <p className="text-[#3D3D3D] text-lg font-medium">
              Include pictures with different angles and details.
            </p>
            <p className="text-[#3D3D3D] text-lg font-medium.">
              You can upload a maximum of 10 photos, that are at least 300px
              wide or tall (we recommend at least 1000px).
            </p>
          </div>
          <div className="flex flex-wrap gap-2">
            {imagePreviews.map((preview, index) => (
              <div
                key={index}
                className="relative w-[7rem] h-[7rem] rounded-lg overflow-hidden"
              >
                <Image
                  unoptimized
                  src={preview}
                  alt={`Preview ${index + 1}`}
                  fill
                  style={{ objectFit: "cover" }}
                  className="rounded-lg"
                />
                <div
                  onClick={() => handleRemoveImage(index)}
                  className="absolute top-1 right-1 bg-yellow-500 h-6 w-6 rounded-full text-white flex items-center justify-center cursor-pointer"
                >
                  X
                </div>
              </div>
            ))}
          </div>
          {fieldErrors.images && (
            <div>
              <p className="text-red-500 text-sm mt-2 font-semibold text-start">
                {fieldErrors.images}
              </p>
            </div>
          )}
          <label className="bg-black text-xl font-medium text-white md:px-2 py-2 xs:px-7 m-5  md:w-4/12 cursor-pointer rounded-lg flex items-center justify-center xs:w-full xs:m-0">
            Select Images
            <input
              type="File"
              name="images"
              accept="image/*"
              multiple
              onChange={handleImageChange}
              className="hidden"
            />
          </label>
          {/* <button className='bg-black text-white px-10 cursor-pointer w-4/12 m-5'>Select Images</button> */}
          <div className="flex py-5  md:flex-row xs:flex-col md:gap-0 xs:gap-4">
            <div className="text-gray-600 font-semibold md:w-[14rem] text-lg text-left xs:w-full">
              Youtube Video:
              <p className="text-xs text-gray-400 text-justify">(optional)</p>
            </div>
            <div className="md:space-y-2 text-justify m-0 space-x-0 xs:w-full">
              <input
                type="text"
                id="youtube"
                value={youtube}
                onChange={(e) => setYoutube(e.target.value)}
                className="border-gray-300 text-black rounded-md md:w-64 xs:w-full xs:space-x-0"
                placeholder="Link"
              />
            </div>
          </div>
          <div className="flex py-5  md:flex-row xs:flex-col md:gap-0 xs:gap-4">
            <div className="text-gray-600 font-semibold md:w-[14rem] text-lg text-left xs:w-full">
              Website URL:
              <p className="text-xs text-gray-400 text-justify">(optional)</p>
            </div>
            <div className="md:space-y-2 text-justify m-0 space-x-0 xs:w-full">
              <input
                type="text"
                id="website"
                value={website}
                onChange={(e) => setWebsite(e.target.value)}
                className="border-gray-300 text-black rounded-md md:w-64 xs:w-full xs:space-x-0"
                placeholder="Link"
              />
            </div>
          </div>
        </section>

        {/* location */}
        <section className="bg-white ">
          <div className="flex flex-col rounded-lg p-5 space-y-4">
            <h1 className="text-[#3D3D3D] text-[45px] font-semibold text-left ">
              Location
            </h1>
            <hr />
            <div className="flex space-x-6 p-5 xs:px-0">
              <div className="text-gray-600 font-semibold w-[9rem] text-left text-lg">
                Country<span className="text-red-600 text-2xl">*</span>
              </div>
              <div className="">
                <div className=" md:flex mt-2 md:gap-5">
                  {CountryName.map((value) => (
                    <div key={value.id} className="flex">
                      <input
                        id={value.id}
                        name="CountryName"
                        type="radio"
                        value={value.id}
                        checked={location === value.title} // Manage checked state
                        onClick={() =>
                          handleCountrySelection(value.id, value.title)
                        } // Corrected event handler
                        className="h-5 w-5 border-none bg-gray-200 text-[#021F71] focus:ring-white"
                      />
                      <label
                        htmlFor={value.id}
                        className="ml-3 block font-medium leading-6 text-gray-900 text-lg"
                      >
                        {value.title}
                        {location == value.title && selectedState && (
                          <span className="ml-2 text-sm text-gray-600">
                            ({selectedState})
                          </span>
                        )}
                      </label>
                    </div>
                  ))}
                </div>
                {fieldErrors.location && (
                  <div className="text-wrap mt-2 text-start">
                    <p className="text-red-500 text-sm font-semibold text-wrap">
                      {fieldErrors.location}
                    </p>
                  </div>
                )}
              </div>
            </div>
            <div className="flex py-5 md:flex-row xs:flex-col md:gap-0 xs:gap-4">
              <div className="text-gray-600 font-semibold md:w-[14rem] md:pr-1 text-lg text-left xs:w-full ">
                Address, City/Town
                <span className="text-red-600 text-2xl">*</span>
                {/* <p className="text-xs text-gray-400 text-justify">(optional)</p> */}
              </div>
              <div className="md:space-y-2 text-justify m-0 space-x-0 xs:w-full ">
                <input
                  type="text"
                  id="full_address"
                  value={fullAddress}
                  onChange={(e) => setFullAddress(e.target.value)}
                  className="border-gray-300 text-black rounded-md md:w-64 xs:w-full xs:space-x-0"
                  placeholder="Enter Address, City/Town"
                />
                {fieldErrors.fullAddress && (
                  <div className="text-wrap mt-2 text-start">
                    <p className="text-red-500 text-sm font-semibold text-wrap">
                      {fieldErrors.fullAddress}
                    </p>
                  </div>
                )}
              </div>
            </div>
          </div>

          <Modal
            isOpen={modalOpen}
            onClose={() => setModalOpen(false)}
            title={
              loadings
                ? "..."
                : `Select a ${
                    stateLocationData?.data?.type === "states"
                      ? "State"
                      : "Province"
                  }`
            }
          >
            {loadings ? (
              <p className="text-black">Loading...</p>
            ) : (
              <form>
                <div className="grid grid-cols-2 gap-4 text-black">
                  {stateLocationData?.data?.list.map((state: any) => {
                    const stateValue = `${state.latitude},${state.longitude}`;
                    return (
                      <label
                        key={state.code}
                        className="flex items-center gap-4 cursor-pointer"
                      >
                        <input
                          type="radio"
                          name="state"
                          value={stateValue}
                          checked={selectedStateValue === stateValue}
                          data-name={state.name}
                          onChange={handleStateChange} // Update selected state
                          className="form-radio cursor-pointer"
                        />
                        <span className="text-black text-start cursor-pointer">
                          {state.name}
                        </span>
                      </label>
                    );
                  })}
                </div>
              </form>
            )}
          </Modal>
        </section>

        {/* price */}
        <section className="bg-white flex flex-col rounded-lg p-5 space-y-4 ">
          <h1 className="text-[#3D3D3D] text-[45px] font-semibold text-left">
            Price
          </h1>
          <hr />
          <fieldset
          // disabled={isDraft === 1 ? false : !!listingId}
          // className={`${isDraft === 1 ? "" : listingId ? "opacity-50" : ""}`}
          >
            <div className="text-justify font-semibold p-5 xs:px-0">
              <div className="flex">
                <label className="text-gray-600 font-semibold w-[7rem] text-left text-lg">
                  Price <span className="text-red-600 text-2xl">*</span>
                </label>

                <div className="flex gap-6 md:pl-[67px] flex-col md:flex-row">
                  {productTypeData.map((value) => (
                    <div key={value.id} className="flex items-center">
                      <input
                        id={value.id}
                        name="productType"
                        type="radio"
                        value={value.id}
                        checked={productData === value.id}
                        onChange={(e) => {
                          const selectedType = e.target.value;

                          // If switching to Unreserved, clear the reserve price
                          if (selectedType === "Unreserved") {
                            setReservedInput("");
                          }

                          setProductData(selectedType);
                        }}
                        className="h-5 w-5 border-none bg-gray-200 text-[#021F71] focus:ring-white"
                      />
                      <label
                        htmlFor={value.id}
                        className="ml-3 block font-medium leading-6 text-gray-900 text-lg"
                      >
                        {value.title}
                      </label>
                    </div>
                  ))}
                </div>
              </div>

              <div className="pr-6 md:pr-0 md:pl-[63px]">
                {productData === "Reserved" && (
                  <div className="relative md:left-[8.4rem] xs:left-1 md:w-80 xs:w-full py-6">
                    <div className="absolute left-3 flex items-center gap-2 border-r-2">
                      <Image
                        unoptimized
                        src={currencyRates[currency].flag}
                        alt={`${currency} flag`}
                        width={24}
                        height={24}
                        className="rounded-full"
                      />
                      {location ? (
                        location === "Canada" ? (
                          <span className="text-lg text-black py-2 pr-2 font-normal border-0">
                            C$
                          </span>
                        ) : (
                          <select
                            value={currency}
                            onChange={(e) => setCurrency(e.target.value)}
                            className="bg-transparent text-lg font-medium focus:outline-none border-0 pl-0"
                          >
                            {Object.keys(currencyRates).map((curr) => (
                              <option
                                key={curr}
                                value={curr}
                                className="border-0 text-black"
                              >
                                {currencyRates[curr].symbol}
                              </option>
                            ))}
                          </select>
                        )
                      ) : (
                        <span className="text-lg text-black py-2 pr-2 font-normal border-0">
                          C$
                        </span>
                      )}
                    </div>

                    <input
                      type="text"
                      value={
                        reservedInput === undefined
                          ? ""
                          : reservedInput?.toLocaleString("en-US")
                      }
                      onChange={handleInputChange}
                      placeholder="Enter price"
                      className={`border border-gray-300 rounded-md text-black pl-40 pr-3 py-2 w-full xs:w-full text-lg ${
                        fieldErrors.reservedInput && "border-red-500"
                      }`}
                    />

                    {fieldErrors.reservedInput && (
                      <p className="text-red-500 text-sm mt-2">
                        {fieldErrors.reservedInput}
                      </p>
                    )}
                  </div>
                )}
              </div>
            </div>
          </fieldset>

          {/* Tax Configuration */}
          <div className="flex flex-col items-start md:py-5 mt-1 xs:px-0">
            <div className="flex md:flex-row xs:flex-col md:gap-0 xs:gap-2">
              <label className="text-gray-600 font-semibold w-[11rem] text-left text-lg">
                Tax <span className="text-red-600 text-2xl">*</span>
              </label>
              <div className="flex flex-col gap-3">
                <div className="flex items-center gap-4">
                  <div className="flex items-center">
                    <input
                      id="taxable"
                      name="taxType"
                      type="radio"
                      value="taxable"
                      checked={taxType === "taxable"}
                      onChange={(e) => setTaxType(e.target.value)}
                      className="h-5 w-5 border-none bg-gray-200 text-[#021F71] focus:ring-white"
                    />
                    <label
                      htmlFor="taxable"
                      className="ml-3 block font-medium leading-6 text-gray-900 text-lg"
                    >
                      Taxable
                    </label>
                  </div>
                  <div className="flex items-center">
                    <input
                      id="no-tax"
                      name="taxType"
                      type="radio"
                      value="no-tax"
                      checked={taxType === "no-tax"}
                      onChange={(e) => {
                        setTaxType(e.target.value);
                        setTaxDetails(""); // clear tax details if "No Tax" selected
                      }}
                      className="h-5 w-5 border-none bg-gray-200 text-[#021F71] focus:ring-white"
                    />
                    <label
                      htmlFor="no-tax"
                      className="ml-3 block font-medium leading-6 text-gray-900 text-lg"
                    >
                      No Tax
                    </label>
                  </div>
                </div>
                {taxType === "taxable" && (
                  <input
                    type="text"
                    id="taxDetails"
                    name="taxDetails"
                    value={taxDetails}
                    onChange={(e) => setTaxDetails(e.target.value)}
                    placeholder="Tax name and %"
                    className={`border-gray-300 text-black rounded-md md:w-64 xs:w-full resize-none ${
                      fieldErrors.taxDetails && "border-red-500"
                    }`}
                  />
                )}
                {fieldErrors.taxType && (
                  <div>
                    <p className="text-red-500 text-sm mt-2 font-semibold text-start">
                      {fieldErrors.taxType}
                    </p>
                  </div>
                )}
                {fieldErrors.taxDetails && (
                  <div>
                    <p className="text-red-500 text-sm mt-2 font-semibold text-start">
                      {fieldErrors.taxDetails}
                    </p>
                  </div>
                )}
              </div>
            </div>
          </div>
        </section>

        {/* table */}
        <section className="bg-white flex flex-col rounded-lg p-5 space-y-4">
          {/* {!!isDraft || !locationId ? ( */}
          <div className="py-5 ">
            <p className="text-lg text-justify text-black font-semibold">
              By posting your ad, you are agreeing to our{" "}
              <Link href={"/terms"} className="text-blue-700 font-semibold">
                {" "}
                Terms of Use{" "}
              </Link>
              and
              <Link href={"/privacy"} className="text-blue-700 font-semibold">
                {" "}
                Privacy Policy.{" "}
              </Link>
              <br />
              Please do not post duplicate ads.
            </p>
            <div className="flex gap-2 items-start py-4">
              <input
                type="checkbox"
                className={`h-4 w-4 rounded border-gray-300 text-blue-700 focus:ring-indigo-500 mt-[5px] ${
                  fieldErrors.terms && "border-red-500"
                }`}
                checked={isChecked}
                onChange={(e) => setIsChecked(e.target.checked)}
              />
              <span className="text-lg text-black  font-semibold flex">
                I agree to pay the{" "}
                <Link href={"/terms"} className="text-blue-700 cursor-pointer">
                  auction fee
                </Link>{" "}
                {selectedRule && (
                  <span className="rounded-lg px-2">
                    ${selectedRule.seller_fee}
                  </span>
                )}
                for posting this ad.
              </span>
            </div>
            {fieldErrors.terms && (
              <div className="text-red-500 font-semibold p-1 text-start pl-6">
                {fieldErrors.terms}
              </div>
            )}
            <div className="flex gap-2 items-start py-4">
              <input
                type="checkbox"
                className={`h-4 w-4 rounded border-gray-300 text-blue-700 focus:ring-indigo-500 mt-[5px] ${
                  fieldErrors.terms && "border-red-500"
                }`}
                checked={isBoostChecked}
                onChange={(e) => setIsBoostChecked(e.target.checked)}
              />
              <span className="text-lg text-black  font-semibold">
                Boost My Listing to the Top for only ${AuctionSellerFee} Be the
                first one buyers see!
              </span>
            </div>
            <div className="flex flex-wrap gap-3 mt-3"></div>
          </div>
          {/* ) : ( */}
          <div>
            <button
              disabled={loading}
              className={`border-none bg-yellow-400 rounded-md text-black px-10 w-1/2 transition ease-in-out hover:-translate-y-1 hover:scale-110 duration-300 flex items-center justify-center ${
                loading && "opacity-70 cursor-not-allowed"
              }`}
              onClick={() => handleBidRepost(0, "post")}
            >
              {loading ? (
                <span className="loader"></span> // your loader
              ) : (
                "Repost"
              )}
            </button>
          </div>

          {/* )} */}

          {showModal && (
            <div className="fixed inset-0 flex items-center justify-center bg-gray-800 bg-opacity-50">
              <div className="bg-white rounded-lg p-4 max-w-sm w-full">
                <h2 className="text-lg font-semibold mb-4">Error</h2>
                <p className="text-black">{modalMessage}</p>
                <button
                  onClick={() => setShowModal(false)}
                  className="bg-red-500 text-white mt-4 py-2 px-4 rounded"
                >
                  Close
                </button>
              </div>
            </div>
          )}
        </section>
      </section>
    </div>
  );
};

export default AdDetails;
