import DatePicker, { DatePickerProps, registerLocale } from "react-datepicker";
import {
	Control,
	Controller,
	FieldValues,
	Path,
	PathValue,
} from "react-hook-form";
import { de } from "date-fns/locale";
import { useState } from "react";
import { cn } from "../../../helper/cn";
registerLocale("de", de);

interface ListInputProps<T extends FieldValues>
	extends Omit<DatePickerProps, "onChange" | "selected"> {
	control: Control<T>;
	name: Path<T>;
	label?: string;
}

export const ListInput = <T extends FieldValues>({
	control,
	name,
	label,
	...props
}: ListInputProps<T>) => {
	const [value, setValue] = useState<string>("");
	return (
		<Controller
			control={control}
			name={name}
			render={({ field }) => {
				return (
					<fieldset className="fieldset bg-base-200 border border-neutral-400 p-4 rounded-box mt-5">
						<legend className="fieldset-legend">{label}</legend>
						<div className="join w-full flex">
							<input
								type="text"
								className={cn("input join-item grow", props.className)}
								placeholder={props.placeholderText || "Element Hinzufügen"}
								value={value}
								onChange={(e) => setValue(e.target.value)}
							/>
							<button
								className={cn("btn join-item", props.className)}
								onClick={() => {
									if (value.length === 0) return;
									field.onChange([...(field.value || []), value]);
									setValue("");
								}}
								type="button"
								onSubmit={(e) => false}
							>
								Hinzufügen
							</button>
						</div>
						<div>
							{field.value?.map((item: string, index: number) => (
								<div key={index} className="join flex">
									<input
										{...field}
										value={item}
										className={cn("input join-item grow", props.className)}
										onChange={(e) => {
											const value = [...field.value];
											value[index] = e.target.value;
											field.onChange(value);
										}}
									/>
									<button
										className="btn join-item btn-sm"
										onClick={() => {
											const value = [...field.value];
											value.splice(index, 1);
											field.onChange(value);
										}}
									>
										Entfernen
									</button>
								</div>
							))}
						</div>
					</fieldset>
				);
			}}
		/>
	);
};
