"use client";

import FormField from "@/components/common/FormField";
import { useTranslations } from "next-intl";
import { RxCross2 } from "react-icons/rx";

interface SaveSearchContentProps {
  saveSearchFilters: any;
  setSaveSearchFilters: (updater: any) => void;
  filterOptions: any;
  filterData: any;
  searchTitle: string;
  setSearchTitle: (title: string) => void;
}

export default function SaveSearchContent({
  saveSearchFilters,
  setSaveSearchFilters,
  filterOptions,
  filterData,
  searchTitle,
  setSearchTitle,
}: SaveSearchContentProps) {
  const t = useTranslations();
  // const renderFilterChips = (
  //   lookupKey: string,
  //   selectedIds: string[],
  //   onRemove: (id: string) => void,
  //   dynamicKey?: string
  // ) => {
  //   if (selectedIds.length === 0) {
  //     return (
  //       <span className="text-xs text-neutrals400 dark:text-neutrals500">
  //         No {lookupKey} selected
  //       </span>
  //     );
  //   }

  //   if (lookupKey === "dynamicAttributes" && dynamicKey) {
  //     const dynamicAttr = filterOptions?.dynamicAttributes?.[dynamicKey];
  //     if (dynamicAttr?.options) {
  //       return (
  //         <div className="flex flex-wrap gap-2.5">
  //           {selectedIds.map((id) => {
  //             const option = dynamicAttr.options.find(
  //               (opt: any) => opt.id === id
  //             );
  //             return (
  //               <div
  //                 key={id}
  //                 className="bg-kzblue50 text-primary500 text-xs rounded-full flex items-center gap-1 py-1 px-2 dark:bg-background dark:text-neutrals400"
  //               >
  //                 <span className="text-xs text-primary500 dark:text-primary400">
  //                   {option ? option.label?.en : id}
  //                 </span>
  //                 <RxCross2
  //                   className="cursor-pointer text-sm ml-1"
  //                   onClick={() => onRemove(id)}
  //                 />
  //               </div>
  //             );
  //           })}
  //         </div>
  //       );
  //     }
  //   }

  //   const getProps = (key: string) => {
  //     switch (key) {
  //       case "colors":
  //         return { idProp: "id", valueProp: "label" };
  //       case "brands":
  //       case "conditions":
  //       case "fuels":
  //         return { idProp: "id", valueProp: "value" };
  //       case "states":
  //       case "tags":
  //         return { idProp: "key", valueProp: "value" };
  //       default:
  //         return { idProp: "id", valueProp: "value" };
  //     }
  //   };

  //   const { idProp, valueProp } = getProps(lookupKey);
  //   return (
  //     <div className="flex flex-wrap gap-2.5">
  //       {selectedIds.map((id) => {
  //         const item = filterOptions?.[lookupKey]?.find(
  //           (i: any) => i[idProp] === id
  //         );
  //         return (
  //           <div
  //             key={id}
  //             className="bg-kzblue50 text-primary500 text-xs rounded-full flex items-center gap-1 py-1 px-2 dark:bg-background dark:text-neutrals400"
  //           >
  //             <span className="text-xs text-primary500 dark:text-primary400">
  //               {item ? item[valueProp] : id}
  //             </span>
  //             <RxCross2
  //               className="cursor-pointer text-sm ml-1"
  //               onClick={() => onRemove(id)}
  //             />
  //           </div>
  //         );
  //       })}
  //     </div>
  //   );
  // };

  return (
    // <div>
    //   <form action="">
    //     <FormField
    //       label="Title"
    //       name="title"
    //       placeholder="Enter a title here"
    //       value={searchTitle}
    //       onChange={(e) => setSearchTitle(e.target.value)}
    //     />
    //     <div className="mt-5">
    //       <label
    //         htmlFor="area-of-search"
    //         className="text-sm text-neutrals600 dark:text-neutrals400"
    //       >
    //         Area of search
    //       </label>
    //       <div className="mt-2.5 bg-neutrals50 p-5 dark:bg-card">
    //         <div className="space-y-5">
    //           {(() => {
    //             const activeSections = [];

    //             // Price filter
    //             const hasPriceFilter =
    //               saveSearchFilters.priceRange[0] > 0 ||
    //               saveSearchFilters.priceRange[1] < 100000;
    //             if (hasPriceFilter) {
    //               activeSections.push(
    //                 <div key="price">
    //                   <span className="block text-sm text-neutrals500 mb-2 dark:text-neutrals400">
    //                     Price
    //                   </span>
    //                   <div className="flex flex-wrap gap-2.5">
    //                     <div className="bg-kzblue50 text-primary500 text-xs rounded-full flex items-center gap-1 py-1 px-2 dark:bg-background dark:text-neutrals400">
    //                       <span className="text-xs text-primary500 dark:text-neutrals400">
    //                         SAR {saveSearchFilters.priceRange[0]} - SAR{" "}
    //                         {saveSearchFilters.priceRange[1]}
    //                       </span>
    //                       <RxCross2
    //                         className="cursor-pointer text-sm ml-1"
    //                         onClick={() => {
    //                           setSaveSearchFilters((prev: any) => ({
    //                             ...prev,
    //                             priceRange: [
    //                               filterOptions?.priceRange.actualMin || 0,
    //                               filterOptions?.priceRange.actualMax || 100000,
    //                             ],
    //                           }));
    //                         }}
    //                       />
    //                     </div>
    //                   </div>
    //                 </div>
    //               );
    //             }

    //             // Static filters (brand, color, condition, fuel, state, tag)
    //             const staticFilters = [
    //               { key: "selectedColors", label: "Color", lookup: "colors" },
    //               { key: "selectedBrands", label: "Brand", lookup: "brands" },
    //               { key: "selectedTags", label: "Tags", lookup: "tags" },
    //               {
    //                 key: "selectedConditions",
    //                 label: "Condition",
    //                 lookup: "conditions",
    //               },
    //               { key: "selectedFuels", label: "Fuel", lookup: "fuels" },
    //               { key: "selectedStates", label: "State", lookup: "states" },
    //             ];

    //             staticFilters.forEach(({ key, label, lookup }) => {
    //               const hasValues =
    //                 saveSearchFilters[key] && saveSearchFilters[key].length > 0;
    //               if (hasValues) {
    //                 activeSections.push(
    //                   <div key={key}>
    //                     <span className="block text-sm text-neutrals500 mb-2 dark:text-neutrals400">
    //                       {label}
    //                     </span>
    //                     <div className="flex flex-wrap gap-2.5">
    //                       {renderFilterChips(
    //                         lookup,
    //                         saveSearchFilters[key],
    //                         (id: string) => {
    //                           setSaveSearchFilters((prev: any) => ({
    //                             ...prev,
    //                             [key]: prev[key].filter(
    //                               (item: any) => item !== id
    //                             ),
    //                           }));
    //                         }
    //                       )}
    //                     </div>
    //                   </div>
    //                 );
    //               }
    //             });

    //             // Dynamic attributes
    //             if (
    //               filterData?.attributes &&
    //               filterOptions?.dynamicAttributes
    //             ) {
    //               const staticSlugs = new Set([
    //                 "brand",
    //                 "color",
    //                 "condition",
    //                 "fuel",
    //                 "state",
    //                 "tag",
    //               ]);

    //               filterData.attributes.forEach((attr: any) => {
    //                 if (!attr?.key?.filterable) return;
    //                 const slug = attr.key.attributeId.slug.replace(/\s+/g, "_"); // Replace spaces with underscores for internal use
    //                 if (staticSlugs.has(slug)) return;

    //                 const title = attr.key.attributeId.title;
    //                 const filterKey = `selected${
    //                   slug.charAt(0).toUpperCase() + slug.slice(1)
    //                 }s`;
    //                 const uniqueKey = `${slug}_0`;
    //                 const dynamicAttr =
    //                   filterOptions.dynamicAttributes[uniqueKey];

    //                 if (
    //                   !dynamicAttr ||
    //                   !Array.isArray(dynamicAttr.options) ||
    //                   dynamicAttr.options.length === 0
    //                 )
    //                   return;

    //                 const hasValues =
    //                   saveSearchFilters[filterKey] &&
    //                   saveSearchFilters[filterKey].length > 0;
    //                 if (hasValues) {
    //                   activeSections.push(
    //                     <div key={slug}>
    //                       <span className="block text-sm text-neutrals500 mb-2 dark:text-neutrals400">
    //                         {title}
    //                       </span>
    //                       <div className="flex flex-wrap gap-2.5">
    //                         {renderFilterChips(
    //                           "dynamicAttributes",
    //                           saveSearchFilters[filterKey],
    //                           (selectedId: string) => {
    //                             setSaveSearchFilters((prev: any) => ({
    //                               ...prev,
    //                               [filterKey]: prev[filterKey].filter(
    //                                 (id: any) => id !== selectedId
    //                               ),
    //                             }));
    //                           },
    //                           uniqueKey
    //                         )}
    //                       </div>
    //                     </div>
    //                   );
    //                 }
    //               });
    //             }

    //             // Show message if no filters are applied
    //             if (activeSections.length === 0) {
    //               return (
    //                 <div className="text-center text-neutrals400 dark:text-neutrals500 py-8">
    //                   No filters applied
    //                 </div>
    //               );
    //             }

    //             return activeSections;
    //           })()}
    //         </div>
    //       </div>
    //     </div>
    //   </form>
    // </div>

    <div>
      <form action="">
        <FormField
          label="Title"
          name="title"
          placeholder="Enter a title here"
          value={searchTitle}
          onChange={(e) => setSearchTitle(e.target.value)}
        />
        <div className="mt-5">
          <label
            htmlFor="area-of-search"
            className="text-sm text-neutrals600 dark:text-neutrals400"
          >
            {t("area_of_search")}
          </label>
          <div className="mt-2.5 bg-neutrals50 p-5 dark:bg-card">
            <div className="space-y-5">
              {(() => {
                const activeSections = [];

                // Price filter
                const hasPriceFilter =
                  saveSearchFilters.priceRange?.[0] >= 0 &&
                  saveSearchFilters.priceRange?.[1] != 0;

                if (hasPriceFilter) {
                  activeSections.push(
                    <div key="price">
                      <span className="block text-sm text-neutrals500 mb-2 dark:text-neutrals400">
                        {t("price")}
                      </span>
                      <div className="flex flex-wrap gap-2.5">
                        <div className="bg-kzblue50 text-primary500 text-xs rounded-full flex items-center gap-1 py-1 px-2 dark:bg-background dark:text-neutrals400">
                          <span className="text-xs text-primary500 dark:text-neutrals400">
                            SAR {saveSearchFilters.priceRange[0]} - SAR{" "}
                            {saveSearchFilters.priceRange[1]}
                          </span>
                          <RxCross2
                            className="cursor-pointer text-sm ml-1"
                            onClick={() => {
                              setSaveSearchFilters((prev: any) => ({
                                ...prev,
                                priceRange: [
                                  filterOptions?.priceRange.actualMin || 0,
                                  filterOptions?.priceRange.actualMax || 100000,
                                ],
                              }));
                            }}
                          />
                        </div>
                      </div>
                    </div>
                  );
                }

                // Static filters (brands, tags, condition, fuel, colors)
                const staticFilters = [
                  { key: "selectedBrands", label: "Brand" },
                  { key: "selectedTags", label: "Tags" },
                  { key: "selectedConditions", label: "Condition" },
                  { key: "selectedFuels", label: "Fuel" },
                  { key: "selectedColors", label: "Color" },
                ];

                staticFilters.forEach(({ key, label }) => {
                  const values = saveSearchFilters[key] || [];
                  if (values.length > 0) {
                    activeSections.push(
                      <div key={key}>
                        <span className="block text-sm text-neutrals500 mb-2 dark:text-neutrals400">
                          {label}
                        </span>
                        <div className="flex flex-wrap gap-2.5">
                          {values.map((item: any) => {
                            const imageUrl = item?.imageUrl;
                            return (
                              <div
                                key={item.value}
                                className="bg-kzblue50 text-primary500 text-xs rounded-full flex items-center gap-1 py-1 px-2 dark:bg-background dark:text-neutrals400"
                              >
                                {item?.label?.en && (
                                  <span className="text-xs text-primary500 dark:text-neutrals400">
                                    {item.label?.en}
                                  </span>
                                )}

                                {imageUrl && (
                                  <div
                                    className={`w-8 h-8 border-2 overflow-hidden transition-all duration-200 ${item?.type?.includes("image")
                                        ? "rounded-full"
                                        : "rounded"
                                      }`}
                                  >
                                    <img
                                      src={`${process.env.NEXT_PUBLIC_API}/${item.imageUrl}`}
                                      alt={item.label?.en || "option"}
                                      className="w-full h-full object-cover rounded-full"
                                    />
                                  </div>
                                )}
                                <RxCross2
                                  className="cursor-pointer text-sm ml-1"
                                  onClick={() => {
                                    setSaveSearchFilters((prev: any) => ({
                                      ...prev,
                                      [key]: prev[key].filter(
                                        (x: any) => x.value !== item.value
                                      ),
                                    }));
                                  }}
                                />
                              </div>
                            );
                          })}
                        </div>
                      </div>
                    );
                  }
                });

                // Dynamic filters (everything else in saveSearchFilters)
                Object.entries(saveSearchFilters).forEach(
                  ([key, values]: any) => {
                    if (
                      key === "priceRange" ||
                      staticFilters.some((sf) => sf.key === key)
                    ) {
                      return; // skip price + statics
                    }

                    if (Array.isArray(values) && values.length > 0) {
                      activeSections.push(
                        <div key={key}>
                          <span className="block text-sm text-neutrals500 mb-2 dark:text-neutrals400">
                            {key.replace(/_/g, " ")}
                          </span>
                          <div className="flex flex-wrap gap-2.5">
                            {values.map((item: any) => (
                              <div
                                key={item.value}
                                className="bg-kzblue50 text-primary500 text-xs rounded-full flex items-center gap-1 py-1 px-2 dark:bg-background dark:text-neutrals400"
                              >
                                <span className="text-xs text-primary500 dark:text-neutrals400">
                                  {item.label?.en}
                                  {item?.imageUrl && (
                                    <div
                                      className={`w-8 h-8 border-2 overflow-hidden transition-all duration-200 ${item?.type?.includes("image")
                                          ? "rounded-full"
                                          : "rounded"
                                        } `}
                                    >
                                      <img
                                        src={`${process.env.NEXT_PUBLIC_API}/${item.imageUrl}`}
                                        alt={item.label?.en || ""}
                                        className="w-full h-full object-cover rounded-full"
                                      />
                                    </div>
                                  )}
                                </span>
                                <RxCross2
                                  className="cursor-pointer text-sm ml-1"
                                  onClick={() => {
                                    setSaveSearchFilters((prev: any) => ({
                                      ...prev,
                                      [key]: prev[key].filter(
                                        (x: any) => x.value !== item.value
                                      ),
                                    }));
                                  }}
                                />
                              </div>
                            ))}
                          </div>
                        </div>
                      );
                    }
                  }
                );

                // Show message if no filters are applied
                if (activeSections.length === 0) {
                  return (
                    <div className="text-center text-neutrals400 dark:text-neutrals500 py-8">
                      {t("no_filter_applied")}
                    </div>
                  );
                }

                return activeSections;
              })()}
            </div>
          </div>
        </div>
      </form>
    </div>
  );
}
