import type { Meta, StoryObj } from "@storybook/react";
import { Dropdown } from "./Dropdown";
import { useRef, useState } from "react";
import { Typography } from "../Typography/Typography";
import { SocialIcon } from "../SocialIcon/SocialIcon";
import { SocialIconVariant } from "../SocialIcon/types";
import { Icon } from "../Icon/Icon";

const socialNetworkDropdownOptions = {
  ["All Networks"]: { socialIcon: null, name: "All Networks" },
  Discord: { socialIcon: SocialIconVariant.DISCORD, name: "Discord" },
  X: { socialIcon: SocialIconVariant.X, name: "X" },
  Telegram: { socialIcon: SocialIconVariant.TELEGRAM, name: "Telegram" },
};
type SocialNetworkDropdownOptions = keyof typeof socialNetworkDropdownOptions;
const meta: Meta<typeof Dropdown> = {
  component: Dropdown,
};

export default meta;

type Story = StoryObj<typeof Dropdown>;

const SocialMediaDropdown = () => {
  const [selectedOption, setSelectedOption] =
    useState<SocialNetworkDropdownOptions>("All Networks");
  const [isOpen, setIsOpen] = useState(false);
  const ulRef = useRef<HTMLUListElement>(null);

  const getOption = (
    name: keyof typeof socialNetworkDropdownOptions,
    isSelected: boolean
  ) => {
    return (
      <div className="flex items-center w-full">
        <SocialIcon
          variant={
            socialNetworkDropdownOptions[name].socialIcon as SocialIconVariant
          }
          className="mr-4 w-8 h-8"
        />
        <Typography variant="p" className="font-medium">
          {name}
        </Typography>
        {isSelected && (
          <Icon
            name="check"
            color="primary-600"
            className="sm:hidden ml-auto"
          />
        )}
      </div>
    );
  };

  return (
    <Dropdown
      isOpen={isOpen}
      setIsOpen={setIsOpen}
      mobilHeaderTitle="Filter"
      selectedOption={getOption(selectedOption, false)}
      className="h-[62px] w-[198px]"
    >
      <ul ref={ulRef}>
        {Object.keys(socialNetworkDropdownOptions).map((value) => {
          const option = value as SocialNetworkDropdownOptions;
          return (
            <li
              className="h-10 mb-4 last:mb-0 px-[6px] flex items-center cursor-pointer hover:bg-neutral-50 text-neutral-950"
              key={value}
              onClick={() => {
                setSelectedOption(option);
                setIsOpen(false);
              }}
            >
              {getOption(option, selectedOption === value)}
            </li>
          );
        })}
      </ul>
    </Dropdown>
  );
};

export const SocialMediaExample: Story = {
  render: () => <SocialMediaDropdown />,
};
