"use client";
import React, { useState } from "react";

type Option = {
  id: string;
  label: string;
};

type DynamicSelectProps = {
  options: Option[];
  onSelect: (value: string) => void;
  heading: string;
  defaultValue?: string;
};

export default function DynamicSelect({
  options,
  onSelect,
  heading,
  defaultValue,
}: DynamicSelectProps) {
  const [selected, setSelected] = useState<string>(defaultValue || options[0]?.id || "");

  const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const value = e.target.value;
    setSelected(value);
    onSelect(value);
  };

  return (
    <div className="relative flex w-full flex-col border">
      <label
        htmlFor="dynamic-select"
        className="block pt-1 pl-3 text-xs text-gray-950"
      >
        {heading}
      </label>
      <div className="relative">
        <select
          id="dynamic-select"
          value={selected}
          onChange={handleChange}
          className="relative -top-0.5 z-10 w-full text-sm appearance-none bg-transparent px-3 py-1.5 font-medium"
        >
          {options.map((option) => (
            <option key={option.id} value={option.id}>
              {option.label}
            </option>
          ))}
        </select>
        <div className="pointer-events-none absolute inset-y-0 -top-0.5 right-3 z-1 flex h-full w-4 items-center">
            <i className="icon-[ph--caret-up-down-bold]"></i>
        </div>
      </div>
    </div>
  );
}
