"use client";
import { FieldValues, Path } from "react-hook-form";
import SelectTemplate, { Props as SelectTemplateProps, StylesConfig } from "react-select";
import { cn } from "@repo/shared-components";
import dynamic from "next/dynamic";

const customStyles: StylesConfig<any, false> = {
	control: (provided) => ({
		...provided,
		backgroundColor: "var(--color-base-100)",
		borderColor: "color-mix(in oklab, var(--color-base-content) 20%, #0000);",
		borderRadius: "0.5rem",
		padding: "0.25rem",
		boxShadow: "none",
		"&:hover": {
			borderColor: "color-mix(in oklab, var(--color-base-content) 20%, #0000);",
		},
		color: "var(--color-primary-content)",
	}),
	option: (provided, state) => ({
		...provided,
		backgroundColor: state.isSelected ? "hsl(var(--p))" : "hsl(var(--b1))",
		color: "var(--color-primary-content)",
		"&:hover": { backgroundColor: "var(--color-base-200)" },
	}),
	multiValueLabel: (provided) => ({
		...provided,
		color: "var(--color-primary-content)",
	}),
	singleValue: (provided) => ({
		...provided,
		color: "var(--color-primary-content)",
	}),
	multiValue: (provided) => ({
		...provided,
		backgroundColor: "var(--color-base-300)",
	}),
	input: (provided) => ({
		...provided,
		color: "var(--color-primary-content)",
	}),
	menu: (provided) => ({
		...provided,
		backgroundColor: "var(--color-base-100)",
		borderRadius: "0.5rem",
		zIndex: 9999,
	}),
	menuPortal: (provided) => ({
		...provided,
		maxHeight: "230px",
	}),
	menuList: (provided) => ({
		...provided,
		maxHeight: "230px",
	}),
};

interface SelectProps extends Omit<SelectTemplateProps, "form" | "value" | "onChange"> {
	label?: any;
	value: any;
	onChange: (value: any) => void;
	error?: string;
}

const SelectCom = ({
	label,
	placeholder = label,
	value,
	onChange,
	error,
	className,
	...inputProps
}: SelectProps) => {
	return (
		<div className="relative">
			<span className="label-text text-lg flex items-center gap-2">{label}</span>
			<SelectTemplate
				onChange={(newValue: any) => {
					if ((inputProps as any)?.isMulti) {
						onChange(Array.isArray(newValue) ? newValue.map((v: any) => v.value) : []);
					} else {
						onChange(newValue ? newValue.value : null);
					}
				}}
				value={
					(inputProps as any)?.isMulti
						? (inputProps as any).options?.filter(
								(o: any) => Array.isArray(value) && value.includes(o.value),
							)
						: (inputProps as any).options?.find((o: any) => o.value === value)
				}
				styles={customStyles as any}
				className={cn("w-full placeholder:text-neutral-600", className)}
				placeholder={placeholder}
				{...inputProps}
			/>
			{error && <p className="text-error">{error}</p>}
		</div>
	);
};

const SelectWrapper = <T extends FieldValues>(props: SelectProps) => <SelectCom {...props} />;

export const Select = dynamic(() => Promise.resolve(SelectWrapper), {
	ssr: false,
});
