import React, { useEffect, useState } from "react";
import { Box, Button, Typography } from "@mui/material";
import AddEditCategoryModal from "../../components/AddEditCategoryModal";
import { useForm } from "react-hook-form";
import CustomTable, { Column } from "../../components/CustomTable";
import { useDispatch, useSelector } from "react-redux";
import {
	adminList,
	updateAdmin,
	createAdmin,
} from "../../redux/slices/adminSlice";
import { AppDispatch, RootState } from "../../redux/store/store";

export default function AdminList() {
	const [modalOpen, setModalOpen] = useState(false);
	const { reset } = useForm();

	const [deleteModal, setDeleteModal] = React.useState<boolean>(false);
	const [viewModal, setViewModal] = React.useState<boolean>(false);
	const [rowData, setRowData] = React.useState<any | null>(null);

	const dispatch = useDispatch<AppDispatch>();

	const admins = useSelector((state: RootState) => state.adminReducer.admins);

	useEffect(() => {
		dispatch(adminList());
	}, [dispatch]);

	const handleClickOpen = () => {
		setRowData(null); // Reset row data when opening for new admin
		setModalOpen(true);
	};

	const handleCloseModal = () => {
		setModalOpen(false);
		setRowData(null);
		reset();
	};

	const handleCreate = async (data: {
		name: string;
		email: string;
		phone: string;
		registeredAddress: string;
	}) => {
		try {
			await dispatch(createAdmin(data));
			await dispatch(adminList()); // Refresh the list after creation
			handleCloseModal();
		} catch (error) {
			console.error("Creation failed", error);
		}
	};

	const handleUpdate = async (
		id: string,
		name: string,
		email: string,
		phone: string,
		registeredAddress: string
	) => {
		try {
			await dispatch(
				updateAdmin({
					id,
					name,
					email,
					phone,
					registeredAddress,
				})
			);
			await dispatch(adminList());
		} catch (error) {
			console.error("Update failed", error);
		}
	};

	const categoryColumns: Column[] = [
		{ id: "srno", label: "Sr No" },
		{ id: "name", label: "Name" },
		{ id: "email", label: "Email" },
		{ id: "phone", label: "Phone" },
		{ id: "registeredAddress", label: "Address" },
		{ id: "action", label: "Action", align: "center" },
	];

	const categoryRows = admins?.length
		? admins?.map(
				(
					admin: {
						id: string;
						name: string;
						email: string;
						phone: string;
						registeredAddress: string;
					},
					index: number
				) => ({
					id: admin?.id,
					srno: index + 1,
					name: admin?.name,
					email: admin?.email,
					phone: admin?.phone,
					registeredAddress: admin?.registeredAddress,
				})
		  )
		: [];

	return (
		<>
			<Box
				sx={{
					width: "100%",
					maxWidth: {
						sm: "100%",
						display: "flex",
						justifyContent: "space-between",
						alignItems: "center",
					},
				}}
			>
				<Typography
					component="h2"
					variant="h6"
					sx={{ mt: 2, fontWeight: 600 }}
				>
					Admins
				</Typography>
				<Button
					variant="contained"
					size="medium"
					sx={{ textAlign: "right" }}
					onClick={handleClickOpen}
				>
					Add Admin
				</Button>
			</Box>

			<CustomTable
				columns={categoryColumns}
				rows={categoryRows}
				setDeleteModal={setDeleteModal}
				deleteModal={deleteModal}
				setViewModal={setViewModal}
				viewModal={viewModal}
				setRowData={setRowData}
				setModalOpen={setModalOpen}
			/>
			<AddEditCategoryModal
				open={modalOpen}
				handleClose={handleCloseModal}
				handleCreate={handleCreate}
				handleUpdate={handleUpdate}
				editRow={rowData}
			/>
		</>
	);
}
