import { Modal, Button, TextInput } from "@mantine/core";
import { useEffect, useState } from "react";

const ModalLabel = ({ opened, open, close, data, onSave, setData }) => {
	const [openConfirm, setOpenConfirm] = useState(false);
	const [isError, setIsError] = useState(false);

	useEffect(() => {
		if (!opened) {
			setIsError(false);
			setOpenConfirm(false);
		}
	}, [opened]);

	return (
		<>
			<Modal opened={opened} onClose={close} title={data?.id ? "Edit Label" : "Add Label"} centered>
				<div style={{ padding: 20 }} className="flex justify-center">
					<TextInput
						label="Input label"
						withAsterisk
						placeholder="Input placeholder"
						value={data?.name || ""}
						onChange={(event) => {
							if (event.currentTarget.value) setIsError(false);
							setData((pre) => ({ ...pre, name: event.currentTarget.value }));
						}}
						style={{ width: 300 }}
						error={isError ? "Invalid label" : ""}
					/>
				</div>
				<div style={{ padding: 20 }} className="flex justify-center gap-4">
					<Button onClick={close}>Close</Button>
					<Button
						onClick={() => {
							if (!data?.name) {
								setIsError(true);
								return;
							}
							if (data?.id) {
								onSave(data);
								close();
							} else setOpenConfirm(true);
						}}
						color="#1a9b20">
						Save
					</Button>
				</div>
			</Modal>

			<Modal opened={openConfirm} onClose={() => setOpenConfirm(false)} title={"Confirm"}>
				<div style={{ padding: 20 }} className="flex flex-col gap-4 justify-center items-center">
					<div>Do you want to add new label?</div>
					<div style={{ color: "#f54e4e" }}>Label cannot delete after add!</div>
				</div>
				<div style={{ padding: 20 }} className="flex justify-center gap-4">
					<Button
						onClick={() => {
							setOpenConfirm(false);
						}}>
						Cancel
					</Button>
					<Button onClick={onSave} color="#1a9b20">
						Confirm
					</Button>
				</div>
			</Modal>
		</>
	);
};

export default ModalLabel;
