"use client";

import { cn } from "@/lib/utils";
import { useState, useRef, useEffect } from "react";
import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem,
} from "@/components/ui/select";
import * as SelectPrimitive from "@radix-ui/react-select";

export interface SelectOption {
  label: string;
  value: string;
  subcategories?: SelectOption[];
}

interface MultiSelectPopupProps {
  label: string;
  options: SelectOption[];
  selected: string[];
  onChange: (
    selectedValues: string[],
    selectedSubcategories: Record<string, SelectOption[]>
  ) => void;
  placeholder?: string;
}

export default function MultiSelectPopup({
  label,
  options,
  selected,
  onChange,
  placeholder,
}: MultiSelectPopupProps) {
  const [open, setOpen] = useState(false);
  const [tempSelected, setTempSelected] = useState<SelectOption[]>([]);
  const [selectedSubcategories, setSelectedSubcategories] = useState<
    Record<string, SelectOption[]>
  >({});
  const [selectedReligion, setSelectedReligion] = useState<string | null>(null);
  const modalRef = useRef<HTMLDivElement>(null);

  const religionOptions = options?.filter((opt) => opt?.subcategories?.length);
  const hasSubcategories = options?.some((opt) => opt?.subcategories?.length);

  useEffect(() => {
    const normalized: SelectOption[] = [];
    let currentReligion: string | null = null;

    options?.forEach((opt) => {
      const match = selected?.some(
        (s) =>
          typeof s === "string" &&
          (opt?.label?.toLowerCase() === s?.toLowerCase() ||
            opt?.value?.toLowerCase() === s?.toLowerCase())
      );

      if (match) {
        normalized.push(opt);
        if (opt?.subcategories) {
          currentReligion = opt.value;
        }
      }

      if (opt.subcategories?.length) {
        opt.subcategories.forEach((sub) => {
          const subMatch = selected?.some(
            (s) =>
              typeof s === "string" &&
              (sub.label?.toLowerCase() === s?.toLowerCase() ||
                sub.value?.toLowerCase() === s?.toLowerCase())
          );
          if (subMatch) {
            if (!normalized?.some((n) => n?.value === opt?.value)) {
              normalized.push(opt);
              currentReligion = opt?.value;
            }
            setSelectedSubcategories((prev) => {
              const current = prev[opt.value] || [];
              const exists = current?.some((c) => c?.value === sub?.value);
              return {
                ...prev,
                [opt.value]: exists ? current : [...current, sub],
              };
            });
          }
        });
      }
    });

    if (currentReligion) {
      setSelectedReligion(currentReligion);
    }
    setTempSelected(normalized);
  }, [selected, options]);

  const toggleOption = (option: SelectOption) => {
    const exists = tempSelected?.some((item) => item?.value === option?.value);
    if (exists) {
      setTempSelected(
        tempSelected.filter((item) => item?.value !== option?.value)
      );
      if (option.subcategories) {
        setSelectedReligion(null);
        setSelectedSubcategories((prev) => {
          const newState = { ...prev };
          delete newState[option?.value];
          return newState;
        });
      }
    } else {
      setTempSelected([...tempSelected, option]);
      if (option.subcategories) {
        setSelectedReligion(option?.value);
      }
    }
  };

  const handleSave = () => {
    const selectedValues = tempSelected?.map((opt) => opt?.value);
    onChange(selectedValues, selectedSubcategories);
    setOpen(false);
  };

  const handleBackdropClick = (e: React.MouseEvent<HTMLDivElement>) => {
    if (modalRef?.current && !modalRef?.current?.contains(e.target as Node)) {
      e.stopPropagation();
      +setOpen(false);
    }
  };

  const handleSubcategoryChange = (
    subcategory: SelectOption,
    religion: string
  ) => {
    setSelectedSubcategories((prev) => {
      const current = prev[religion] || [];
      const exists = current?.some(
        (item) => item?.value === subcategory?.value
      );
      return {
        ...prev,
        [religion]: exists
          ? current.filter((item) => item?.value !== subcategory?.value)
          : [...current, subcategory],
      };
    });
  };

  const handleReligionChange = (value: string) => {
    const religionOption = options.find((opt) => opt?.value === value);
    if (!religionOption) return;

    setSelectedReligion(value);

    // Update tempSelected to include the new religion
    setTempSelected((prev) => {
      // Remove any existing religion options first
      const filtered = prev.filter((item) => !item?.subcategories);
      return [...filtered, religionOption];
    });

    // Clear any existing subcategories for this religion
    setSelectedSubcategories((prev) => ({
      ...prev,
      [value]: [],
    }));

    // OPEN THE MODAL AUTOMATICALLY AFTER SELECTING A RELIGION
    setOpen(true);
  };

  const displayText = tempSelected.length
    ? tempSelected?.map((o) => o?.label || o?.value)?.join(", ")
    : `Select ${label}`;

  // console.log(selectedReligion, religionOptions, "ggg");

  console.log(selectedReligion, "hee");
  const selectRef = useRef<HTMLSelectElement | null>(null);

  useEffect(() => {
    if (selectRef.current) {
      selectRef.current.style.color = "black";
      selectRef.current.style.accentColor = "#F9F9F9";
    }
  }, []);

  return (
    <div className="relative">
      <div className="w-full">
        <label className="block text-[10px] font-medium text-gray-700 mb-1">
          {label}
        </label>
        <div className="relative">
          {hasSubcategories ? (
            <select
              ref={selectRef}
              value={selectedReligion || ""}
              onChange={(e) => handleReligionChange(e.target.value)}
              className="w-full h-9 flex justify-start text-left items-center rounded-md border bg-[#F9F9F9] px-3 text-[10px] text-black appearance-none"
            >
              <option value="" disabled>
                Select a religion
              </option>
              {religionOptions.map((opt) => (
                <option
                  key={opt.value}
                  value={opt.value}
                  className={`text-xs py-2 px-3 cursor-pointer border-2 border-[#F9F9F9] rounded-md ${
                    selectedReligion?.toLocaleLowerCase() ===
                    opt.value?.toLocaleLowerCase()
                      ? "bg-[#F9F9F9]!"
                      : "bg-[#ffffff]!"
                  }`}
                >
                  {opt.label}
                </option>
              ))}
            </select>
          ) : (
            <div onClick={() => setOpen(true)}>
              <input
                type="text"
                readOnly
                value={displayText}
                placeholder={placeholder}
                className={cn(
                  "flex h-9 w-full rounded-md px-3 py-1 text-[10px] text-black bg-[#F9F9F9] border-none outline-none focus:outline-none",
                  "placeholder:text-muted-foreground",
                  "disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
                )}
              />
            </div>
          )}
        </div>
      </div>

      {open && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
          onClick={(e) => {
            e.stopPropagation();
            handleBackdropClick(e);
          }}
        >
          <div
            ref={modalRef}
            className="bg-gray-200 rounded-lg p-10 w-11/12 max-w-[800px] shadow-lg"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex flex-wrap gap-4 max-h-60 overflow-y-auto">
              {options?.map((opt: any) => (
                <div key={opt.value}>
                  {!opt?.subcategories && (
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        toggleOption(opt);
                      }}
                      className={`py-2 px-3 text-[0.8rem] rounded-full ${
                        tempSelected?.some(
                          (item: any) => item?.value === opt?.value
                        )
                          ? "bg-red-500 text-white"
                          : "bg-white text-gray-700"
                      }`}
                    >
                      {opt?.label}
                    </button>
                  )}

                  {selectedReligion === opt?.value &&
                    opt?.subcategories?.length > 0 && (
                      <div className="w-full">
                        <div className="flex gap-2 flex-wrap">
                          {opt?.subcategories?.map((subOpt: any) => (
                            <button
                              key={subOpt.value}
                              onClick={(e) => {
                                e.stopPropagation();
                                handleSubcategoryChange(subOpt, opt.value);
                              }}
                              className={`py-1 px-2 text-[0.7rem] rounded-full ${
                                selectedSubcategories[opt?.value]?.some(
                                  (sub) => sub?.value === subOpt?.value
                                )
                                  ? "bg-blue-500 text-white"
                                  : "bg-white text-gray-700"
                              }`}
                            >
                              {subOpt?.label}
                            </button>
                          ))}
                        </div>
                      </div>
                    )}
                </div>
              ))}
            </div>

            <div className="mt-6 flex justify-center items-center">
              <button
                onClick={handleSave}
                className="px-4 py-2 bg-red-500 text-white rounded"
              >
                Save
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
