import { Controller, useFormContext } from 'react-hook-form';
import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils';
import { CheckCircle, Circle } from 'lucide-react';
import Image from 'next/image';

interface Option {
	label: string;
	value: string | number;
	icon: string;
}

interface Props {
	name: string;
	label: string;
	options: Option[];
	isRequired?: boolean;
}

const RHFLageSelectCardGroup = ({
	name,
	label,
	options,
	isRequired = true,
}: Props) => {
	const { control } = useFormContext();

	return (
		<Controller
			name={name}
			control={control}
			render={({ field, fieldState: { error } }) => (
				<div className="space-y-1 w-full">
					{/* Label */}
					{label && (
						<Label className="text-sm font-medium mb-1 block">
							{label}
							{isRequired ? (
								<span className="text-red-500 align-middle ml-1">
									*
								</span>
							) : (
								<span className="text-gray-400 font-normal text-[10px] ml-1">
									(optional)
								</span>
							)}
						</Label>
					)}

					{/* Cards container */}
					<div className="flex flex-row gap-2 max-w-full overflow-x-auto no-scrollbar py-1">
						{options.map((opt) => {
							const selected = field.value === opt.value;

							return (
								<button
									type="button"
									key={opt.value}
									onClick={(e) => {
										e.preventDefault();
										field.onChange(opt.value);
									}}
									className={cn(
										'py-4 pl-4 pr-6 min-w-[170px] max-w-44  h-[200px] rounded-2xl whitespace-nowrap  flex flex-col gap-2 justify-between',
										selected
											? 'border-primary border-[1] bg-[#F5FAEB]'
											: 'border-[#E7E7E7] border-[1] bg-white'
									)}
								>
									<div className="w-full flex justify-end">
										{selected ? (
											<CheckCircle className="bg-primary text-white rounded-full" />
										) : (
											<Circle className="text-gray-500" />
										)}
									</div>
									<div className="flex flex-col gap-3.5 justify-start">
										<Image
											width={45}
											height={37}
											src={opt.icon}
											alt={opt?.icon}
											className=""
										/>
										<p
											className={cn(
												'font-bold text-[15px]',
												selected ? 'text-primary' : 'text-[#888888]'
											)}
										>
											{opt.label}
										</p>
									</div>
								</button>
							);
						})}
					</div>

					{/* Error message */}
					{error && (
						<p className="text-red-500 text-sm mt-1">{error.message}</p>
					)}
				</div>
			)}
		/>
	);
};

export default RHFLageSelectCardGroup;
