import { useFormik } from "formik";
import { FC } from "react";
import * as yup from "yup";
import { TextField } from "./TextField";
import axios, { AxiosError } from "axios";
import { AssetMap } from "./models/AssetMap";
import { toast } from "react-toastify";
import { uuidValidator } from "./validators/uuid.validator";

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

interface Model {
	abonent: string;
	assetId: string | null;
}

export const CreateMapCard: FC<Props> = ({ onClose, requireUpdate, }) => {
	function handleSubmit({
		abonent,
		assetId,
	}: Model) {
		return axios
			.post<AssetMap>("/api/asset-maps", {
				abonent,
				assetId,
			})
			.then(() => {
				toast.success("Маппинг успешно создан");
				requireUpdate();
				onClose();
			})
			.catch((error: AxiosError) => {
				console.error(error.response?.data);
				toast.error(error.response?.data as string ?? error.message);
			});
	}

	const formik = useFormik<Model>({
		initialValues: {
			abonent: "",
			assetId: null,
		},
		onSubmit: handleSubmit,
		validationSchema: yup
			.object().shape({
				abonent: yup
					.string()
					.required("IMEI обязателен")
					.matches(/^\d{8}$/, "IMEI должен состоять из 8 цифр"),
				assetId: uuidValidator,

			}),
		validateOnMount: true,
		validateOnBlur: true,
		validateOnChange: true,
	});

	function handleCancel(): void {
		formik.resetForm();
		onClose();
	}

	return (
		<div className="w-100 d-flex flex-column justify-content-center align-items-center gap-1 border rounded p-3">
			<h3>Создание маппинга</h3>
			<form
				className="w-100 d-flex flex-column gap-3 align-items-center"
				onSubmit={formik.handleSubmit}
			>
				<TextField
					formik={formik}
					name="abonent"
					title="IMEI:" />

				<TextField
					formik={formik}
					name="assetId"
					title="ID объекта:" />

				<div className="d-flex gap-3">
					<button
						type="submit"
						className="btn btn-primary d-flex gap-1 align-items-center"
						disabled={formik.isSubmitting || !formik.isValid}
					>
						Добавить
						{formik.isSubmitting && (
							<span className="spinner-border spinner-border-sm"></span>
						)}
					</button>
					<button
						type="button"
						className="btn btn-secondary"
						disabled={formik.isSubmitting}
						onClick={handleCancel}
					>
						Отмена
					</button>
				</div>
			</form>
		</div>
	)
};
