"use client";

import { X } from "lucide-react";
import { useEffect, useState } from "react";
import clsx from "clsx";
import { showPost } from "@/lib/actions/productCategoryAction";
import { checkAuthErrorGet } from "@/lib/checkAuthError";
import { useAppDispatch, useAppSelector } from "@/app/store/hooks";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { getStoredLocale } from "@/lib/getLocale";
import { toast } from "react-toastify";
import { AttributeKeys, OtherAttribute } from "../../../types/common-types";
import { getImageUrl } from "@/hooks/useImageUrl";

interface SideDrawerProps {
  isOpen: boolean | null;
  title: string;
  onClose: () => void;
  showSearch?: boolean;
  postId?: string;
  categoryData?: any;
  selectedCategory?: string;
  formType?: string;
}

const translation: Record<string, string> = {};

const ListDetailSidebar = ({
  isOpen,
  title,
  onClose,
  showSearch,
  postId,
  categoryData,
  selectedCategory,
  formType,
}: SideDrawerProps) => {
  const { user } = useAppSelector((state) => state?.auth);
  const locale = getStoredLocale();
  const t = useTranslations();
  const dispatch = useAppDispatch();
  const router = useRouter();

  const [isLoading, setIsLoading] = useState<boolean>(false);

  const [post, setPost] = useState<any>({});
  const [otherAttribute, setOtherAttribute] = useState<
    | OtherAttribute<"mobile_number">
    | OtherAttribute<"vehicle_number_plate">
    | null
  >(null);
  const [productType, setProductType] = useState<
    "product" | AttributeKeys | null
  >(null);

  useEffect(() => {
    if (!postId || !user?.token || !formType || !categoryData) return;

    const fetchPostDetail = async () => {
      setIsLoading(true);
      try {
        const { data, success } = await showPost(user.token, {
          id: postId,
          formType,
        });
        if (success && Array.isArray(data)) {
          let obj = {
            details: {},
            other: {},
            images: {},
          };

          const safeGetValue = (content: any) => {
            if (Array.isArray(content)) {
              if (content.length === 0) return "";
              return typeof content[0] === "object" && content[0]?.value
                ? content[0].value
                : content[0];
            } else if (typeof content === "object" && content !== null) {
              return content.value ?? content.phone ?? content;
            }
            return content ?? "";
          };

          const formatDateTime = (value: any) => {
            if (!value) return "";
            const cleaned = String(value).replace(/^"|"$/g, "");
            const date = new Date(cleaned);
            if (isNaN(date.getTime())) {
              return cleaned;
            }
            return date.toLocaleString("en-US", {
              dateStyle: "medium",
              timeStyle: "short",
            });
          };

          const processValueByType = (attr: any) => {
            const { type, value, key } = attr;
            const content = value?.content;
            const meta = value?.meta || {};
            const options = key?.attributeId?.options || [];

            const imageOptionTypes = [
              "radioimage",
              "radioimagetitle",
              "checkboximage",
              "checkboximagetitle",
            ];

            if (
              type.includes("image") &&
              !imageOptionTypes.some((t) => type === t || type.includes(t))
            ) {
              if (meta.files?.length) {
                return meta.files.map((f: any) => f);
              }
              if (content) return Array.isArray(content) ? content : [content];
              return [];
            }

            if (
              type === "singlevideouploader" ||
              type === "multiplevideouploader"
            ) {
              if (meta.files?.length) return meta.files.map((f: any) => f);
              if (content) return Array.isArray(content) ? content : [content];
              return [];
            }

            switch (type) {
              case "radio":
              case "singleselectdropdown":
              case "singleselectdropdownwithsearch":
              case "boolean": {
                const selected = options.find(
                  (opt: any) => opt?._id === content
                );
                return {
                  displayValue:
                    selected?.value[locale] || selected?.value || content || "",
                };
              }

              case "checkbox":
              case "multipleselectdropdown":
              case "multipleselectdropdownwithsearch": {
                let arr = content;
                if (typeof arr === "string") {
                  try {
                    arr = JSON.parse(arr);
                  } catch {
                    arr = [arr];
                  }
                }
                if (!Array.isArray(arr)) arr = [arr];

                let selected = [];

                if (attr.slug != "select-products") {
                  selected = arr
                    .map((item: any) => {
                      const id = item?.key || item;
                      return options.find((opt: any) => opt._id === id);
                    })
                    .filter(Boolean);
                } else {
                  selected = arr;
                }
                if (attr.slug === "select-products") {
                  const temp = selected.map((s: any) => s.value).join(", ");
                  return {
                    displayValue: selected.map((s: any) => s.value).join(", "),
                  };
                }
                return {
                  displayValue: selected
                    .map((s: any) => s.value?.en || s.value)
                    .join(", "),
                };
              }

              case "radioimage":
              case "checkboximage":
              case "radioimagetitle":
              case "checkboximagetitle": {
                const ids = Array.isArray(content) ? content : [content];
                const selected = ids
                  .map((id: any) => options.find((opt: any) => opt._id === id))
                  .filter(Boolean);

                const displayValue = selected
                  .map((opt: any) => opt.value?.en || opt.value)
                  .join(", ");

                const imageList = selected.map((opt: any) => ({
                  label: opt?.meta?.originalFileName_en,
                  location: opt?.meta?.fileUrl_en?.startsWith("http")
                    ? opt.meta.fileUrl_en
                    : `${process.env.NEXT_PUBLIC_IMAGE_BASE_URL}/${opt.meta.fileUrl_en}`,
                }));

                return { displayValue, imageList };
              }

              case "toggleswitchtitle":
              case "toggleswitchtitleinput": {
                let parsed = [];
                try {
                  parsed = Array.isArray(content)
                    ? content
                    : typeof content === "string"
                    ? JSON.parse(content)
                    : [content];
                } catch {
                  parsed = [];
                }

                if (type === "toggleswitchtitleinput") {
                  const values = parsed
                    .map((obj: any) => {
                      const toggleId = Object.keys(obj).find(
                        (k) => !k.endsWith("_input") && obj[k] === true
                      );
                      if (!toggleId) return null;
                      const inputValue = obj[`${toggleId}_input`] || "";
                      const opt = options.find((o: any) => o._id === toggleId);
                      const label = opt?.value?.en || "";
                      return `${label}${inputValue ? `: ${inputValue}` : ""}`;
                    })
                    .filter(Boolean);

                  return { displayValue: values.join(", ") };
                }

                if (type === "toggleswitchtitle") {
                  const ids = parsed.flatMap((obj: any) =>
                    Object.keys(obj).filter((k) => obj[k] === true)
                  );
                  const selected = ids
                    .map((id: any) =>
                      options.find((opt: any) => opt._id === id)
                    )
                    .filter(Boolean);

                  return {
                    displayValue: selected
                      .map((opt: any) => opt?.value?.en)
                      .join(", "),
                  };
                }
              }

              default:
                return { displayValue: safeGetValue(content) };
            }
          };

          data
            .filter((ele) => {
              const slug = ele?.slug;
              const match = ["select-watermark", "other-attribute"];

              // Set Other Attribute Data
              if (slug === "other-attribute") {
                const otherAttr = ele?.value;
                if (otherAttr?.valueType === "mobile_number") {
                  setOtherAttribute({
                    content: otherAttr?.content,
                    meta: otherAttr?.meta,
                    valueType: "mobile_number",
                  } as OtherAttribute<"mobile_number">);
                  setProductType("mobile_number");
                }
                if (otherAttr?.valueType === "vehicle_number_plate") {
                  setOtherAttribute({
                    content: otherAttr?.content,
                    meta: otherAttr?.meta,
                    valueType: "vehicle_number_plate",
                  } as OtherAttribute<"vehicle_number_plate">);
                  setProductType("vehicle_number_plate");
                }
              }

              if (match.includes(slug)) return false;
              return true;
            })
            .forEach((ele) => {
              const label = ele?.key?.attributeId?.label;
              const labelEn = label?.en?.toLowerCase().replace(/\s+/g, "_");
              const slug = ele?.slug?.replace(/\s+/g, "_");

              const MAIN_FIELDS = [
                "short_description",
                "description",
                "title",
                "price",
                "salary",
              ];

              const isMainField = MAIN_FIELDS.find((k) => labelEn?.includes(k));

              const processed = processValueByType(ele);
              const value =
                processed?.displayValue ??
                processed ??
                safeGetValue(ele.value.content);

              if (isMainField) {
                (obj as any).details[isMainField] = value;
                return;
              }

              if (
                ele.type === "singleimageuploader" ||
                ele.type === "multipleimageuploader"
              ) {
                (obj as any).details.image = processed;
                return;
              }

              if (
                ele.type === "singlevideouploader" ||
                ele.type === "multiplevideouploader"
              ) {
                (obj as any).details.video = processed;
                return;
              }

              if (
                [
                  "radioimage",
                  "checkboximage",
                  "radioimagetitle",
                  "checkboximagetitle",
                ].includes(ele.type)
              ) {
                (obj as any).images[slug] = {
                  label,
                  value: processed.imageList,
                };
                return;
              }

              if (["country", "state", "city"].includes(slug)) {
                (obj as any).other[slug] = {
                  label,
                  value: safeGetValue(ele.value.content),
                };
                return;
              }

              if (slug === "contact" || slug.includes("contact")) {
                const val = ele.value.content;
                const contentObj = Array.isArray(val) ? val[0] : val;
                const phoneValue =
                  contentObj?.phone || safeGetValue(contentObj);
                const fullPhone = `${contentObj?.country_code || ""} ${
                  phoneValue || ""
                }`.trim();
                (obj as any).other[slug] = { label, value: fullPhone };
                return;
              }

              if (slug.includes("date") || slug.includes("time")) {
                (obj as any).other[slug] = {
                  label,
                  value: formatDateTime(value),
                };
                return;
              }

              (obj as any).other[slug] = { label, value };
            });

          setPost(obj);
        }
      } catch (error: any) {
        if (checkAuthErrorGet(error, dispatch, router)) return;

        toast.error(
          error?.response?.data?.message || t("validation.error_msg")
        );
      } finally {
        setIsLoading(false);
      }
    };

    fetchPostDetail();
  }, [postId]);

  const renderOtherAttribute = () => {
    if (productType === null) return null;

    switch (productType) {
      case "mobile_number": {
        const mobileAttr = otherAttribute as OtherAttribute<"mobile_number">;
        const content = mobileAttr.content[0];
        const meta = mobileAttr.meta;
        return (
          <div className="w-full relative max-w-64">
            <img
              src={getImageUrl(content.cardImage)}
              alt={title}
              className="w-full h-[211px] object-cover object-top"
            />
          </div>
        );
        break;
      }

      case "vehicle_number_plate": {
        const vehicleAttr =
          otherAttribute as OtherAttribute<"vehicle_number_plate">;
        const content = vehicleAttr.content[0];
        const meta = vehicleAttr.meta;
        return <img src={getImageUrl(content.cardImage)} />;
        break;
      }

      default:
        return null;
    }
  };

  if (!isOpen) return null;
  return (
    <div
      className={clsx(
        "fixed inset-0 z-50 flex justify-end transition-opacity duration-300",
        isOpen
          ? "pointer-events-auto bg-black/30"
          : "pointer-events-none bg-transparent"
      )}
      onClick={onClose}
    >
      {/* Drawer Content */}
      <div
        className={clsx(
          "w-full max-w-[697px] max-[991px]:max-w-full max-xl:max-w-[500px] h-full bg-white shadow-xl transform transition-transform duration-300 ease-in-out dark:bg-background",
          isOpen ? "translate-x-0" : "translate-x-full rtl:-translate-x-full"
        )}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b max-[380px]:px-4 max-md:flex-row-reverse max-md:shadow-headerShadow max-md:border-hidden max-md:px-5 dark:bg-darkbg dark:border-darkborder">
          <div className="hidden max-md:block"></div>
          <div className="max-md:-ml-2">
            <h2 className="text-lg font-semibold dark:text-white max-md:text-base max-md:font-medium max-md:text-neutrals800">
              {title}
            </h2>
          </div>
          <button onClick={onClose} className="rtl:rotate-180">
            <X className="w-5 h-5 text-neutrals500 dark:text-neutrals300 dark:hover:text-white max-md:hidden" />
            <div className="hidden max-md:block">
              <svg
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  d="M18.7895 11.0066H7.61953L12.4995 6.12656C12.8895 5.73656 12.8895 5.09656 12.4995 4.70656C12.1095 4.31656 11.4795 4.31656 11.0895 4.70656L4.49953 11.2966C4.10953 11.6866 4.10953 12.3166 4.49953 12.7066L11.0895 19.2966C11.4795 19.6866 12.1095 19.6866 12.4995 19.2966C12.8895 18.9066 12.8895 18.2766 12.4995 17.8866L7.61953 13.0066H18.7895C19.3395 13.0066 19.7895 12.5566 19.7895 12.0066C19.7895 11.4566 19.3395 11.0066 18.7895 11.0066Z"
                  fill="#1E293B"
                  className="dark:fill-white"
                />
              </svg>
            </div>
          </button>
        </div>

        {/* Body */}
        <div className="px-6 py-7 overflow-y-auto h-full max-h-[calc(100%-136px)] max-[380px]:px-4">
          {isLoading === false ? (
            <div className="space-y-5">
              <div>
                <div className="label-box bg-neutrals100 p-3.5 text-base text-primary500 font-medium dark:bg-darkbg dark:text-primary400">
                  {t("my_listing.details")}
                </div>
                <div className="pl-2.5 space-y-2.5 mt-2.5">
                  <div className="pb-2.5 border-b border-neutrals100 dark:border-darkborder">
                    <label className="block text-sm font-medium mb-1 dark:text-neutrals300 text-neutrals800">
                      {t("my_listing.main_category")}
                    </label>
                    {selectedCategory && (
                      <span className="text-sm text-neutrals500 dark:text-neutrals400">
                        {selectedCategory
                          ?.replace(/-/g, " ")
                          .toLowerCase()
                          .replace(/\b\w/g, (c) => c.toUpperCase())}
                      </span>
                    )}
                  </div>

                  <div className="grid md:grid-cols-2 gap-4">
                    <div className="pb-2.5 border-b border-neutrals100 dark:border-darkborder">
                      <label className="block text-sm font-medium mb-1 dark:text-neutrals300 text-neutrals800">
                        {t("my_listing.title")}
                      </label>
                      <span className="text-sm text-neutrals500 dark:text-neutrals400">
                        {post?.details?.title}
                      </span>
                    </div>
                    {formType === "product" ? (
                      <div className="pb-2.5 border-b border-neutrals100 dark:border-darkborder">
                        <label className="block text-sm font-medium mb-1 dark:text-neutrals300 text-neutrals800">
                          {t("my_listing.price")}
                        </label>
                        <span className="text-sm text-neutrals500 dark:text-neutrals400">
                          {post?.details?.price}
                        </span>
                      </div>
                    ) : formType === "job" ? (
                      <div className="pb-2.5 border-b border-neutrals100 dark:border-darkborder">
                        <label className="block text-sm font-medium mb-1 dark:text-neutrals300 text-neutrals800">
                          {t("my_listing.salary")}
                        </label>
                        <span className="text-sm text-neutrals500 dark:text-neutrals400">
                          {post?.details?.salary}
                        </span>
                      </div>
                    ) : null}
                  </div>
                  <div className="pb-2.5 border-b border-neutrals100 dark:border-darkborder">
                    <label className="block text-sm font-medium mb-1 dark:text-neutrals300 text-neutrals800">
                      {t("my_listing.short_description")}
                    </label>
                    <span className="text-sm text-neutrals500 dark:text-neutrals400">
                      {post?.details?.short_description}
                    </span>
                  </div>
                  {
                    (post?.details?.description && post?.details?.description?.trim(),
                    length > 0 && (
                      <div className="pb-2.5 border-b border-neutrals100 dark:border-darkborder">
                        <label className="block text-sm font-medium mb-1 dark:text-neutrals300 text-neutrals800">
                          {t("my_listing.description")}
                        </label>
                        <div
                          className="text-sm text-neutrals500 dark:text-neutrals400"
                          dangerouslySetInnerHTML={{
                            __html: post?.details?.description || "",
                          }}
                        ></div>
                      </div>
                    ))
                  }

                  {post?.details?.image && (
                    <div className="pb-2.5 border-b border-neutrals100 dark:border-darkborder">
                      <label className="block text-sm font-medium mb-1 dark:text-neutrals300 text-neutrals800">
                        {t("my_listing.images")}
                      </label>
                      <div className="flex flex-wrap gap-2.5">
                        {post?.details?.image?.map((img: any, idx: number) => {
                          return (
                            <div
                              className="w-[72px] h-[72px]"
                              key={`${img}idx${idx}`}
                            >
                              <img
                                src={`${process.env.NEXT_PUBLIC_API}${img.location}`}
                                className="w-full h-full object-cover"
                                alt="product"
                                onError={(e) => {
                                  e.currentTarget.onerror = null;
                                  e.currentTarget.src = "/default.jpg";
                                }}
                              />
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  )}

                  {post?.details?.video && (
                    <div className="pb-2.5 border-b border-neutrals100 dark:border-darkborder">
                      <label className="block text-sm font-medium mb-1 dark:text-neutrals300 text-neutrals800">
                        {t("my_listing.videos")}
                      </label>
                      <div className="flex flex-wrap gap-2.5">
                        {post?.details?.video?.map((vid: any, idx: number) => {
                          return (
                            <div
                              className="w-[150px] h-[150px]"
                              key={`${vid}-${idx}`}
                            >
                              <video
                                src={`${process.env.NEXT_PUBLIC_API}${vid.location}`}
                                controls
                                className="w-full h-full object-cover rounded-md"
                              />
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  )}
                </div>
              </div>
              {/* Start from here */}
              {Object.keys(post?.other || {}).length > 0 && (
                <div>
                  <div className="label-box bg-neutrals100 p-3.5 text-base text-primary500 font-medium dark:bg-darkbg dark:text-primary400">
                    {t("my_listing.other_details")}
                  </div>

                  <div className="flex items-end flex-wrap gap-2.5 pl-2.5 mt-2.5 fdfdfd">
                    {Object.entries(post?.other || {}).map(
                      ([ky, attribute]: [any, any], index) => {
                        let key: string = translation[ky];

                        const label = attribute?.label;

                        let displayValue: any = attribute?.value;

                        const value = attribute?.value;

                        if (typeof value === "object" && value !== null) {
                          if (Array.isArray(value)) {
                            displayValue = displayValue?.join(", ");
                          } else if (value?.value?.en) {
                            displayValue = value.value.en;
                          } else {
                            displayValue = JSON.stringify(value);
                          }
                        }

                        if (key?.includes("date")) {
                          try {
                            displayValue = new Date(
                              JSON.parse(value)
                            ).toLocaleDateString();
                          } catch {
                            displayValue = value;
                          }
                        } else if (key?.includes("time")) {
                          try {
                            displayValue = new Date(
                              JSON.parse(value)
                            ).toLocaleTimeString([], {
                              hour: "2-digit",
                              minute: "2-digit",
                              hour12: true,
                            });
                          } catch {
                            displayValue = value;
                          }
                        } else if (key === "contact-number") {
                          try {
                            const parsed = value;
                            if (parsed?.country_code || parsed?.phone) {
                              displayValue = `${parsed.country_code || ""} ${
                                parsed.phone || ""
                              }`.trim();
                            }
                          } catch {
                            displayValue = value;
                          }
                        }

                        return (
                          <div
                            key={index}
                            className="pb-2.5 border-b border-neutrals100 dark:border-darkborder w-[49%] max-sm:w-full"
                          >
                            <label className="block text-sm font-medium mb-1 dark:text-neutrals300 text-neutrals800">
                              {locale == "en" ? label?.en : label?.ar}
                            </label>
                            <span className="text-sm text-neutrals500 dark:text-neutrals400">
                              {displayValue}
                            </span>
                          </div>
                        );
                      }
                    )}
                  </div>
                </div>
              )}

              {/* Other Images */}
              {post &&
                post.images &&
                Object.values(post.images).some(
                  (imageData: any) =>
                    Array.isArray(imageData?.value) &&
                    imageData.value.length > 0
                ) && (
                  <div>
                    <div className="label-box bg-neutrals100 p-3.5 text-base text-primary500 font-medium dark:bg-darkbg dark:text-primary400">
                      {t("my_listing.other_images")}
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-2.5 pl-2.5 mt-2.5">
                      {Object.entries(post?.images || {}).map(
                        ([key, value]: [any, any], index) => {
                          const label = value?.label;
                          let displayValue: any = value?.value;

                          return (
                            <div
                              key={index}
                              className="pb-2.5 border-b border-neutrals100 dark:border-darkborder"
                            >
                              <label className="block text-sm font-medium mb-1 dark:text-neutrals300 text-neutrals800">
                                {locale == "en" ? label?.en : label?.ar}
                              </label>
                              <span className="text-sm text-neutrals500 dark:text-neutrals400">
                                {displayValue.map((ele: any, idx: number) => (
                                  <img
                                    key={`${ele?.label}-${idx}`}
                                    src={`${ele?.location}`}
                                    alt={ele?.label || "option image"}
                                    className="w-24 h-24 object-cover rounded"
                                    onError={(e) => {
                                      e.currentTarget.src = "/default.jpg";
                                      e.currentTarget.alt =
                                        "Image not available";
                                    }}
                                  />
                                ))}
                              </span>
                            </div>
                          );
                        }
                      )}
                    </div>
                  </div>
                )}

              {renderOtherAttribute()}
            </div>
          ) : (
            <div>{t("loading")}</div>
          )}
        </div>

        {/* <div className="px-6 py-4 border-t bg-white sticky bottom-0 max-[380px]:px-4 dark:bg-darkbg dark:border-darkborder">
          footer
        </div> */}
      </div>
    </div>
  );
};

export default ListDetailSidebar;
