"use client";

import { cn } from "@/lib/utils";
import { useId } from "react";
import Typography from "../Typography/Typography";
import { Label } from "../label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "../select";

type Option = {
  value: string | number;
  label: string;
};

export interface SelectInputProps extends React.ComponentProps<typeof Select> {
  error?: boolean;
  options: Option[];
  placeholder?: string;
  label?: string;
  labelProps?: React.ComponentProps<typeof Label>;
  triggerProps?: React.ComponentProps<typeof SelectTrigger>;
  contentProps?: React.ComponentProps<typeof SelectContent>;
  itemProps?: React.ComponentProps<typeof SelectItem>;
  errorProps?: React.ComponentProps<typeof Typography>;
}

export default function SelectInput({
  error,
  options,
  placeholder,
  label,
  labelProps,
  triggerProps,
  contentProps,
  itemProps,
  errorProps,
  ...props
}: SelectInputProps) {
  const id = useId();

  return (
    <div className={cn("w-full flex flex-col gap-2")}>
      {label && (
        <Label
          htmlFor={id}
          className={cn(
            "text-muted-foreground font-inter font-medium text-base",
            labelProps?.className
          )}
          {...labelProps}
        >
          {label}
        </Label>
      )}
      <Select {...props}>
        <SelectTrigger
          className={cn(
            "cursor-pointer",
            "w-full min-w-[106px] h-fit! min-h-14",
            "px-4 py-3.5",
            "font-inter text-[18px]/[28px] font-medium text-foreground",
            "data-[placeholder]:text-placeholder-foreground",
            "rounded-2xl outline-2 outline-primary/30",
            "duration-200",
            "disabled:opacity-50 disabled:cursor-not-allowed",
            // placeholder && !props.value && "text-placeholder-foreground",
            error &&
              "outline-destructive focus-visible:shadow-destructive focus-visible:ring-destructive/30",
            triggerProps?.className
          )}
          {...triggerProps}
        >
          <SelectValue placeholder={placeholder} />
        </SelectTrigger>
        <SelectContent {...contentProps}>
          {options.map((option) => (
            <SelectItem
              key={option.value}
              value={option.value.toString()}
              {...itemProps}
            >
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
      {error && (
        <Typography size="xs" color="destructive" {...errorProps}>
          {errorProps?.children}
        </Typography>
      )}
    </div>
  );
}
