'use client';
import { Controller, useFormContext } from 'react-hook-form';
import { cn } from '@/lib/utils';
import { Circle, CheckCircle } from 'lucide-react';

interface Option {
	title: string;
	subtitle?: string;
	description?: string;
	value: string | number;
}

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

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

	return (
		<Controller
			name={name}
			control={control}
			render={({ field, fieldState: { error } }) => (
				<div className={cn('space-y-2 w-full', className)}>
					{/* Label */}
					{label && (
						<p className="text-sm font-medium">
							{label}
							{isRequired ? (
								<span className="text-red-500 ml-1">*</span>
							) : (
								<span className="text-gray-400 text-xs ml-1">
									(optional)
								</span>
							)}
						</p>
					)}

					<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
						{options.map((opt) => {
							const selected = opt.value === field.value;

							return (
								<button
									key={opt.value}
									type="button"
									onClick={() => field.onChange(opt.value)}
									className={cn(
										'flex flex-col gap-4 p-4 rounded-[20px] border pt-3.5 pr-3.5 pb-4 pl-6 text-left transition-all duration-150 cursor-pointer',
										selected
											? 'border-primary bg-[#F5FAEB]'
											: 'border-[#D9D9D9] bg-white hover:border-primary/50'
									)}
								>
									<div className="flex justify-end">
										{selected ? (
											<CheckCircle className="w-7 h-7 text-primary" />
										) : (
											<Circle className="w-7 h-7 text-gray-400" />
										)}
									</div>

									<div className="flex flex-col gap-2">
										<div className="flex flex-col gap-1">
											<p className="font-black text-xl text-ring">
												{opt.title}
											</p>
											{opt.subtitle && (
												<p className="font-bold text-[16px] text-[#888888]">
													{opt.subtitle}
												</p>
											)}
										</div>
										{opt.description && (
											<p className="font-thin text-[12px] text-black">
												{opt.description}
											</p>
										)}
									</div>
								</button>
							);
						})}
					</div>

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

export default RHFCardSelectorGroup;
