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

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

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

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

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

					{/* Vertical list */}
					<div className="grid grid-cols-1 lg:grid-cols-2 gap-3 max-h-80 overflow-y-auto no-scrollbar py-1">
						{options.map((opt) => {
							const selected = field.value === opt.value;

							return (
								<button
									type="button"
									key={opt.value}
									onClick={() => field.onChange(opt.value)}
									className={cn(
										'w-full text-left p-4 rounded-2xl border flex flex-row items-start gap-3 transition-all',
										selected
											? 'border-primary bg-[#F5FAEB]'
											: 'border-[#E7E7E7] bg-white'
									)}
								>
									{/* Radio Style Icon */}
									{selected ? (
										<CheckCircle className="text-white w-5 h-5 bg-primary rounded-full" />
									) : (
										<Circle className="text-gray-400 w-5 h-5" />
									)}

									<div className="flex flex-col">
										<span className="text-base font-medium">
											{opt.label}
										</span>

										{/* Subtitle (optional) */}
										{opt.subtitle && (
											<span className="text-xs text-gray-500 mt-1 leading-snug">
												{opt.subtitle}
											</span>
										)}
									</div>
								</button>
							);
						})}
					</div>

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

export default RHFSelectCardGroupVertical;
