"use client";

import { useRef, useState } from "react";
import { useClickOutside } from "@/hooks/useClickOutside";
import { ChevronDownIcon } from "../dashboard/icons";

export type DropdownOption = { value: string; label: string };

export default function Dropdown({
  value,
  placeholder,
  options,
  onChange,
}: {
  value: string;
  placeholder: string;
  options: DropdownOption[];
  onChange: (value: string) => void;
}) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement | null>(null);
  useClickOutside(ref, () => setOpen(false), open);

  const selectedLabel = options.find((option) => option.value === value)?.label;

  return (
    <div ref={ref} className="relative">
      <button
        type="button"
        onClick={() => setOpen((prev) => !prev)}
        className="flex h-10 w-full items-center justify-between rounded-lg border border-[#D0D5DD] bg-white px-3 text-[13px] outline-none transition-colors focus:border-[#1657D9]"
      >
        <span className={selectedLabel ? "text-[#101828]" : "text-[#98A2B3]"}>{selectedLabel ?? placeholder}</span>
        <ChevronDownIcon className={`text-[#667085] transition-transform ${open ? "rotate-180" : ""}`} />
      </button>

      {open && (
        <div className="absolute left-0 right-0 top-[calc(100%+6px)] z-30 overflow-hidden rounded-xl border border-[#E4E7EC] bg-white py-1.5 shadow-[0_18px_40px_rgba(15,23,42,0.16)]">
          {options.map((option) => (
            <button
              key={option.value}
              type="button"
              onClick={() => {
                onChange(option.value);
                setOpen(false);
              }}
              className={`block w-full px-4 py-2.5 text-left text-[13px] transition-colors hover:bg-[#F5F7F9] ${
                option.value === value ? "font-medium text-[#1657D9]" : "text-[#344054]"
              }`}
            >
              {option.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
