import { useFormContext, Controller } from 'react-hook-form';
import React from 'react';
import {
	Select,
	SelectTrigger,
	SelectValue,
	SelectContent,
	SelectItem,
} from '@/components/ui/select';
import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils';

interface Options {
	value: string;
	label: string;
}

interface RHFSelectionProps {
	name: string;
	label: string;
	options: Options[];
	isRequired?: boolean;
	className?: string;
	showLabel?: boolean;
	disabled?: boolean;
}

const RHFSelection: React.FC<RHFSelectionProps> = ({
	name,
	label,
	options,
	isRequired = true,
	className,
	showLabel = true,
	disabled = false,
}) => {
	const { control } = useFormContext();
	return (
		<Controller
			name={name}
			control={control}
			render={({ field, fieldState: { error } }) => {
				return (
					<div className={cn('mb-2 w-full', className)}>
						{showLabel && (
							<Label className="text-[16px] font-medium mb-1 block ">
								{label}
								{isRequired ? (
									<span className="text-red-500 align-middle">
										{' *'}
									</span>
								) : (
									<span className="text-[#929292] font-normal text-[10px]">{`(optional)`}</span>
								)}
							</Label>
						)}

						<Select
							onValueChange={field.onChange}
							value={field.value || undefined}
							disabled={disabled}
						>
							<SelectTrigger
								className={cn(
									'justify-between font-normal  text-[16px] border-[0.44px] border-[#949494] py-2 w-full rounded-lg ps-3 placeholder:font-light placeholder:text-[16px]',
									error ? 'border-red-500 bg-[#FCE9E9]' : '',
									'focus-visible:outline-none focus-visible:ring-0 hover:bg-white hover:text-primary text-black',
									'h-10 py-4 '
								)}
							>
								<SelectValue placeholder={`Select ${label}`} />
							</SelectTrigger>
							<SelectContent>
								{options.map((option) => (
									<SelectItem
										key={option.value}
										value={option.value}
										className="p-4"
									>
										{option.label}
									</SelectItem>
								))}
							</SelectContent>
						</Select>

						{error && (
							<p className="text-[#EE0004] text-[11px] mt-1">
								{error.message}
							</p>
						)}
					</div>
				);
			}}
		/>
	);
};

export default RHFSelection;
