"use client";
import React, { useState } from "react";
import { RxCrossCircled } from "react-icons/rx";
import { IoMdArrowDropdown, IoMdArrowDropup } from "react-icons/io";
import { FaCheck } from "react-icons/fa";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "../../../lib/utils";
import { ScrollArea } from "../scroll-area";

const multiSelectVariants = cva("relative", {
  variants: {
    outlineVariant: {
      default: "focus:border-accent hover:border-accent-foreground",
      primary: "focus:border-primary hover:border-primary",
    },
    size: {
      default: "w-72",
      sm: "w-52",
      lg: "w-96",
    },
  },
  defaultVariants: {
    size: "default",
    outlineVariant: "default",
  },
});

export interface Option {
  id: any;
  value: any;
}

interface MultiSelectDropdownProps
  extends VariantProps<typeof multiSelectVariants> {
  onSelect: (selectedItems: Option[]) => void;
  data: Option[];
  selectedItemsStyle?: string;
  dropdownContainerStyle?: string;
  outlineBorderColor?: string;
  displayChipsInline?: boolean;
  checkIconColor?: string;
}

const defData = [
  { id: 1, value: "Option 1" },
  { id: 2, value: "Option 2" },
  { id: 3, value: "Option 3" },
];

const MultiSelectDropdown: React.ForwardRefRenderFunction<
  HTMLDivElement,
  MultiSelectDropdownProps
> = ({
  onSelect,
  data,
  selectedItemsStyle,
  dropdownContainerStyle,
  outlineVariant,
  displayChipsInline = true,
  checkIconColor,
  size,
}) => {
  const [selectedItems, setSelectedItems] = useState<Option[]>([]);
  const [isOpen, setIsOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState<string>("");
  const filteredData = data
    ? data.filter((item) =>
        item.value.toLowerCase().includes(searchQuery.toLowerCase())
      )
    : [
        { id: 1, value: "Option 1" },
        { id: 2, value: "Option 2" },
        { id: 3, value: "Option 3" },
      ];

  const handleSelect = (item: Option) => {
    const isSelected = selectedItems.some(
      (selected) => selected.id === item.id
    );
    setSelectedItems((prevSelected) =>
      isSelected
        ? prevSelected.filter((selected) => selected.id !== item.id)
        : [...prevSelected, item]
    );
  };

  const handleUnselect = (
    item: Option,
    event: React.MouseEvent<HTMLButtonElement>
  ) => {
    event.stopPropagation();

    setSelectedItems((prevSelected) =>
      prevSelected.filter((selected) => selected.id !== item.id)
    );
  };

  const handleDone = () => {
    onSelect(selectedItems);
    setIsOpen(false);
  };

  return (
    <div className={`relative ${cn(multiSelectVariants({ size }))}`}>
      <div
        className={`cursor-pointer px-4 py-2 text-sm text-black border border-accent-secondary rounded-md focus:outline-none ${cn(
          multiSelectVariants({ size, outlineVariant })
        )} flex flex-row justify-between items-center overflow-x-scroll no-scrollbar h-12`}
        onClick={() => setIsOpen(!isOpen)}
      >
        <div
          className={`flex items-center justify-between ${
            selectedItems.length > 0 ? "pr-2" : ""
          }`}
        >
          {displayChipsInline
            ? selectedItems.map((selectedItem) => (
                <div
                  key={selectedItem.id}
                  style={{
                    width: `${Math.max(selectedItem.value.length * 10, 130)}px`,
                    minWidth: `${130}px`,
                  }}
                  className={`flex border border-slate-500 bg-slate-100 ml-2 rounded-xl px-1 py-[2px] justify-between `}
                >
                  <div>{selectedItem.value}</div>
                  <button
                    className="text-black focus:outline-none"
                    onClick={(event) => handleUnselect(selectedItem, event)}
                  >
                    <RxCrossCircled />
                  </button>
                </div>
              ))
            : null}
        </div>
        {isOpen ? <IoMdArrowDropup /> : <IoMdArrowDropdown />}
      </div>

      {isOpen && (
        <ScrollArea className="h-44 w-full border border-slate-200 z-10">
          <div
            className={`absolute rounded-md shadow-lg z-50 max-h-48 bg-white ${cn(
              multiSelectVariants({ size })
            )}`}
          >
            <div className="relative py-1">
              <div className="sticky top-0 bg-white z-20 flex flex-row justify-between">
                <input
                  type="text"
                  placeholder="Search..."
                  className="block w-full px-4 py-2 text-sm focus:outline-none "
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                />
                <button
                  className={`sticky mr-2 none ${
                    checkIconColor || "focus:text-primary hover:text-primary"
                  }`}
                  onClick={handleDone}
                >
                  <FaCheck />
                </button>
              </div>
              {filteredData.map((item) => (
                <div
                  key={item.id}
                  className={`cursor-pointer block px-4 py-2 text-sm ${
                    selectedItems.some((selected) => selected.id === item.id)
                      ? ` ${selectedItemsStyle || "bg-orange-100"}`
                      : " text-gray-700 bg-white hover:bg-accent focus:outline-none focus:bg-gray-100"
                  }`}
                  onClick={() => handleSelect(item)}
                >
                  {item.value}
                </div>
              ))}
            </div>
          </div>
        </ScrollArea>
      )}

      {displayChipsInline
        ? null
        : selectedItems.map((selectedItem) => (
            <div
              key={selectedItem.id}
              style={{
                width: `${Math.max(selectedItem.value.length * 10, 130)}px`,
                minWidth: `${130}px`,
              }}
              className={`flex border border-black ml-2 rounded-xl p-1 justify-between`}
            >
              <div>{selectedItem.value}</div>
              <button
                className="text-black focus:outline-none"
                onClick={(event) => handleUnselect(selectedItem, event)}
              >
                <RxCrossCircled />
              </button>
            </div>
          ))}
    </div>
  );
};

export default MultiSelectDropdown;
