import React, { useEffect, useState } from "react";
import { Box, Button, Typography } from "@mui/material";
import AddEditCategoryModal from "../../components/AddEditCategoryModal/addEdit";
import { useForm } from "react-hook-form";
import CustomTable, { Column } from "../../components/CustomTable/customTable";
import { useDispatch, useSelector } from "react-redux";
import { createUser, updateUser, userList } from "../../redux/slices/userSlice";
import { AppDispatch, RootState } from "../../redux/store/store";
import AddUserModal from "../../components/AddUserModal/addUserModal";
import EditUserModal from "../../components/EditUserModal/editUserModal";

export default function UserList() {
	const [addModalOpen, setAddModalOpen] = useState<boolean>(false);
	const [editModalOpen, setEditModalOpen] = useState<boolean>(false);
	const [rowData, setRowData] = useState<any | null>(null);
	const [deleteModal, setDeleteModal] = useState<boolean>(false);
	const [viewModal, setViewModal] = useState<boolean>(false);
	const { reset } = useForm();

	const dispatch = useDispatch<AppDispatch>();

	const users = useSelector((state: RootState) => state.userReducer.users);
    const { user } = useSelector((state: RootState) => state?.profileReducer);
	useEffect(() => {
		dispatch(userList());
	}, [dispatch]);

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

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

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

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

	const categoryColumns: Column[] = [
		{ id: "srno", label: "Sr No" },
		{ id: "name", label: "User Name" },
		{ id: "email", label: "Email" },
		{ id: "phone", label: "Phone" },

		...(user?.userType === "admin"
			? [{ id: "action", label: "Action", align: "center" as const }]
			: []),
	];
	const categoryRows = users?.length
		? users.map((user, index) => ({
				id: user.id,
				srno: index + 1,
				name: user.name,
				email: user.email,
				phone: user.phone || "NA", // Ensures it's a string
		  }))
		: [];

	return (
		<>
			<CustomTable
				columns={categoryColumns}
				rows={categoryRows}
				setDeleteModal={setDeleteModal}
				deleteModal={deleteModal}
				setViewModal={setViewModal}
				viewModal={viewModal}
				setRowData={setRowData}
				tableType="user"
				handleClickOpen={handleClickOpen}
				setModalOpen={() => setEditModalOpen(true)}
			/>
			<AddUserModal
				open={addModalOpen}
				handleClose={handleCloseModal}
				handleCreate={handleCreate}
			/>

			<EditUserModal
				open={editModalOpen}
				handleClose={handleCloseModal}
				handleUpdate={handleUpdate}
				editRow={rowData}
			/>
		</>
	);
}
