import { useFormik } from "formik";
import * as yup from "yup";
import { FC, useEffect, useRef } from "react";
import { AssetMap } from "./models/AssetMap";
import { useAssetMap } from "./hooks/useAssetMap";
import { uuidValidator } from "./validators/uuid.validator";

interface Props {
	assetMap: AssetMap,
	onClose: () => void,
}


export const AssetIdSetter: FC<Props> = ({
	assetMap,
	onClose,
}) => {
	const assetIdInputRef = useRef<HTMLInputElement>(null);
	const { remove, update, } = useAssetMap();

	const {
		handleSubmit,
		values,
		errors,
		touched,
		handleChange,
		handleBlur,
		setFieldValue,
	} = useFormik({
		initialValues: {
			assetId: assetMap.assetId ?? undefined,
		},
		validationSchema: yup.object({
			assetId: uuidValidator,
		}),
		validateOnMount: true,
		onSubmit: (values) => {
			const request = {
				assetId: values.assetId || null,
			};

			return update(assetMap.id, request)
				.then(() => {
					onClose();
				});
		},
	});

	const handleReset = () => {
		setFieldValue("assetId", "");
	};

	useEffect(() => {
		assetIdInputRef.current?.focus();
	}, [assetMap]);

	useEffect(() => {
		setFieldValue("assetId", assetMap.assetId ?? "");
	}, [assetMap, setFieldValue]);

	function handleDelete(): void {
		remove(assetMap.id)
			.then(() => {
				onClose();
			});
	}

	return (
		<div>
			<h3>Задание ИД объекта для: {assetMap.abonent}</h3>
			<form onSubmit={handleSubmit} className="d-flex flex-column gap-3">
				<div className="form-group">
					<label htmlFor="assetId" className="form-label">
						ИД объекта
					</label>
					<div className="d-flex flex-column gap-1">
						<input
							id="assetId"
							type="text"
							name="assetId"
							className={`form-control ${touched.assetId && errors.assetId
								? "invalid-field"
								: ""
								}`}
							value={values.assetId}
							onChange={handleChange}
							onBlur={handleBlur}
							autoFocus
							ref={assetIdInputRef}
						/>
						{touched.assetId && errors.assetId && (
							<div className="invalid-message">
								{errors.assetId}
							</div>
						)}
					</div>
				</div>
				<div className="d-flex gap-3">
					<button
						type="submit"
						className="btn btn-primary">
						Задать
					</button>
					<button
						type="button"
						className="btn btn-secondary"
						onClick={handleReset}>
						Сбросить
					</button>
					<button
						type="button"
						className="btn btn-danger"
						onClick={handleDelete}>
						Удалить
					</button>
				</div>
			</form>
		</div>
	);
};
