"use client";

import { useState } from "react";

// export type SortValue = "desc" | "asc" | "newest" | "oldest";
export type SortValue =
  | "price_desc"
  | "price_asc"
  | "date_newest"
  | "date_oldest"
  | "name_az"
  | "name_za";

type Option = {
  label: string;
  value: SortValue;
};

// const OPTIONS: Option[] = [
//   { label: "HIGHEST TO LOWEST", value: "desc" },
//   { label: "LOWEST TO HIGHEST", value: "asc" },
//   { label: "NEWEST FIRST", value: "newest" },
//   { label: "OLDEST FIRST", value: "oldest" },
// ];

const OPTIONS: Option[] = [
  { label: "PRICE: HIGH → LOW", value: "price_desc" },
  { label: "PRICE: LOW → HIGH", value: "price_asc" },

  // { label: "DATE: NEWEST", value: "date_newest" },
  // { label: "DATE: OLDEST", value: "date_oldest" },

  { label: "NAME: A → Z", value: "name_az" },
  { label: "NAME: Z → A", value: "name_za" },
];

type Props = {
  value: SortValue;
  onChange: (v: SortValue) => void;
};

export default function SortDropdown({ value, onChange }: Props) {
  const [isOpen, setIsOpen] = useState(false);

  const selected = OPTIONS.find((o) => o.value === value) ?? OPTIONS[0];

  const handleSelect = (option: Option) => {
    onChange(option.value);
    setIsOpen(false);
  };

  return (
    <div className="relative font-sofia inline-block text-left">
      <button
        type="button"
        onClick={() => setIsOpen((prev) => !prev)}
        className="flex w-[260px] items-center justify-between bg-[#121823] px-6 py-2 md:py-2.5 text-base md:text-xl font-semibold text-[#DBFAFF] uppercase border border-[#121823] hover:bg-[#161d29] focus:outline-none"
      >
        <span>{selected.label}</span>

        <svg
          className={`h-4 w-4 transition-transform ${
            isOpen ? "rotate-180" : ""
          }`}
          viewBox="0 0 20 20"
          fill="none"
        >
          <path
            d="M5 7.5L10 12.5L15 7.5"
            stroke="white"
            strokeWidth="1.6"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        </svg>
      </button>

      {isOpen && (
        <ul className="absolute left-0 right-0 mt-1 max-h-60 overflow-auto border border-[#29313D] bg-[#121823] text-[#DBFAFF] shadow-lg z-30">
          {OPTIONS.map((option) => (
            <li key={option.value}>
              <button
                type="button"
                onClick={() => handleSelect(option)}
                className={`flex w-full items-center justify-between px-6 py-2 text-xs md:text-sm tracking-[0.15em] uppercase hover:bg-[#1b2432] ${
                  value === option.value ? "bg-[#1b2432]" : ""
                }`}
              >
                {option.label}
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
