import { useEffect, useState } from "react";
import CustomTable, { Column } from "../../components/CustomTable/customTable";
import AddManagerModal from "../../components/AddManagerModal/addManagerModal";
import EditManagerModal from "../../components/EditManagerModal/editManagerModal";
import { useDispatch, useSelector } from "react-redux";
import { RootState, AppDispatch } from "../../redux/store/store";
import {
	managerList,
	addManager,
	updateManager,
} from "../../redux/slices/managerSlice";
import { useForm } from "react-hook-form";

export default function ManagerList() {
	const [addModalOpen, setAddModalOpen] = useState<boolean>(false);
	const [editModalOpen, setEditModalOpen] = useState<boolean>(false);
	const { reset } = useForm();

	const [deleteModal, setDeleteModal] = useState<boolean>(false);
	const [viewModal, setViewModal] = useState<boolean>(false);
	const [rowData, setRowData] = useState<any | null>(null);
	const dispatch = useDispatch<AppDispatch>();
	const managers = useSelector(
		(state: RootState) => state.managerReducer.managers
	);

	// Fetch manager list on component mount
	useEffect(() => {
		dispatch(managerList());
	}, [dispatch]);

	// Open Add Manager Modal
	const handleClickOpen = () => {
		setRowData(null); // Reset row data when opening for new manager
		setAddModalOpen(true);
	};

	// Close all modals
	const handleCloseModal = () => {
		setAddModalOpen(false);
		setEditModalOpen(false);
		setRowData(null);
		reset();
	};

	// Handle adding a new manager
	const handleAddManager = async (data: {
		name: string;
		email: string;
		phone: string;
		stationId: string;
	}) => {
		try {
			// Add manager with stationId
			await dispatch(addManager(data)); // Dispatch action to add manager
			await dispatch(managerList()); // Fetch the updated list
			handleCloseModal(); // Close the modal
		} catch (error) {
			console.error("Error adding manager", error);
		}
	};

	// Handle updating an existing manager
	const handleUpdate = async (
		id: number,
		name: string,
		email: string,
		phone: string,
		stationId: string
	) => {
		try {
			// Update manager with stationId
			await dispatch(
				updateManager({
					id,
					name,
					email,
					phone,
					stationId,
				})
			);
			await dispatch(managerList()); // Refresh the list after update
			handleCloseModal(); // Close modal after update
		} catch (error) {
			console.error("Update failed", error);
		}
	};

	// Columns for the manager table
	const categoryColumns: Column[] = [
		{ id: "srno", label: "Sr No" },
		{ id: "name", label: "Name" },
		{ id: "email", label: "Email" },
		{ id: "phone", label: "Phone" },
		{ id: "stationName", label: "Station Name" },
		{ id: "registeredAddress", label: "Station Location" },
		{ id: "action", label: "Action", align: "center" },
	];

	const categoryRows = managers?.length
		? managers.map((manager, index) => {
				const station = manager?.chargingStation; // Correct access to the ChargingStation data
				return {
					id: manager.id,
					srno: index + 1,
					name: manager.name,
					email: manager.email,
					phone: manager.phone ?? "NA",
					stationName: station?.name ?? "NA", // Corrected station name
					registeredAddress: station?.registeredAddress ?? "NA", // Corrected station address
				};
		  })
		: [];

	return (
		<>
			{/* Custom Table to show manager list */}
			<CustomTable
				columns={categoryColumns}
				rows={categoryRows}
				setDeleteModal={setDeleteModal}
				deleteModal={deleteModal}
				setViewModal={setViewModal}
				viewModal={viewModal}
				setRowData={setRowData}
				setModalOpen={() => setEditModalOpen(true)}
				tableType="manager"
				handleClickOpen={handleClickOpen}
			/>
			{/* Add Manager Modal */}
			<AddManagerModal
				open={addModalOpen}
				handleClose={handleCloseModal}
				handleAddManager={handleAddManager}
			/>
			{/* Edit Manager Modal */}
			<EditManagerModal
				open={editModalOpen}
				handleClose={handleCloseModal}
				handleUpdate={handleUpdate}
				editRow={rowData}
			/>
		</>
	);
}
