import type { ActivityField } from '@/admin/api/activities';
import { cn } from '@/lib/utils';
import { __ } from '@wordpress/i18n';
import { Plus, Trash2 } from 'lucide-react';
import { uid } from './types';

type Props = {
	field: Extract<ActivityField, { type: 'multiple_choice' | 'checkbox' }>;
	onChange: (f: ActivityField) => void;
};

const OptionsEditor = ({ field, onChange }: Props) => {
	const isCheckbox = field.type === 'checkbox';

	const updateLabel = (id: string, label: string) =>
		onChange({
			...field,
			options: field.options.map((o) => (o.id === id ? { ...o, label } : o)),
		});

	const removeOption = (id: string) =>
		onChange({ ...field, options: field.options.filter((o) => o.id !== id) });

	const addOption = () =>
		onChange({
			...field,
			options: [...field.options, { id: uid(), label: '' }],
		});

	return (
		<div className="mt-2 flex flex-col gap-1.5">
			{field.options.map((opt) => (
				<div key={opt.id} className="group/opt flex items-center gap-2">
					<div
						className={cn(
							'size-4 shrink-0 border-2 border-gray-200',
							isCheckbox ? 'rounded' : 'rounded-full',
						)}
					/>
					<input
						value={opt.label}
						onChange={(e) => updateLabel(opt.id, e.target.value)}
						placeholder={__('Option…', 'allcoach')}
						className="flex-1 border-b border-dashed border-gray-200 bg-transparent pb-0.5 text-[13px] text-gray-700 outline-none placeholder:text-gray-400 focus:border-teal-400"
					/>
					{field.options.length > 1 && (
						<button
							type="button"
							onClick={() => removeOption(opt.id)}
							className="flex size-5 shrink-0 items-center justify-center rounded text-gray-300 opacity-0 transition-opacity group-hover/opt:opacity-100 hover:text-red-500"
						>
							<Trash2 className="size-3" />
						</button>
					)}
				</div>
			))}
			<button
				type="button"
				className="mt-1 flex w-fit items-center gap-1 text-[12px] text-teal-600 hover:text-teal-700"
				onClick={addOption}
			>
				<Plus className="size-3" />
				{__('Add option', 'allcoach')}
			</button>
		</div>
	);
};

export default OptionsEditor;
