import { useState } from "react";
import { Server } from "../types/IServer";
import Button from "./Button";
import { useClickAway } from "@uidotdev/usehooks";
import ArrowDownIcon from "./icons/ArrowDownIcon";

interface Props {
  servers: Server[] | undefined;
  value: Server | undefined;
  onChange: (server: Server) => void;
}

export default function DesktopSelect({ servers, value, onChange }: Props) {
  const [isOpen, setIsOpen] = useState(false);
  const ref = useClickAway<HTMLDivElement>(() => setIsOpen(false));

  return (
    <div
      ref={ref}
      className="relative outline-black/10 outline w-[13.889vw] rounded-[0.556vw]"
    >
      <Button
        onlyIcon
        variant="tertiary"
        className="px-[0.833vw] py-[0.417vw] !justify-between w-full"
        onClick={() => setIsOpen((prev) => !prev)}
      >
        <div className="flex gap-[0.278vw] items-center">
          {value?.name && (
            <div
              className="rounded-full w-[0.417vw] aspect-square"
              style={{
                backgroundColor:
                  value?.sessions &&
                  value.sessions?.length > 0 &&
                  value.sessions[value.sessions.length - 1].status === "started"
                    ? "#EF3C26"
                    : "#108C33",
              }}
            />
          )}
          <p className="text-[0.972vw] leading-[115%]">
            {value?.name || "Выберите из списка"}
          </p>
        </div>
        <div
          className={`w-[1.389vw] transition-transform h-[1.389vw]${
            isOpen ? " rotate-180" : ""
          }`}
        >
          <ArrowDownIcon />
        </div>
      </Button>
      {isOpen && (
        <div className="absolute z-1 top-full w-full bg-white rounded-[0.556vw] outline outline-black/10">
          {servers?.map((server) => (
            <Button
              key={server.id}
              onlyIcon
              variant="tertiary"
              className="px-[0.833vw] py-[0.417vw] !justify-start w-full !first:rounded-t-[0.556vw] !last:rounded-b-[0.556vw]"
              onClick={() => {
                onChange(server);
                setIsOpen(false);
              }}
            >
              <div className="flex gap-[0.278vw] items-center">
                <div
                  className="rounded-full w-[0.417vw] aspect-square"
                  style={{
                    backgroundColor:
                      server.sessions &&
                      server.sessions?.length > 0 &&
                      server.sessions[server.sessions.length - 1].status ===
                        "started"
                        ? "#EF3C26"
                        : "#108C33",
                  }}
                />
                <p className="text-[0.972vw] leading-[115%]">{server.name}</p>
              </div>
            </Button>
          ))}
        </div>
      )}
    </div>
  );
}
