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";
import {
	addStationDetails,
	stationDetailList,
	updateStationDetails,
} from "../../redux/slices/managerStationSlice";
import AddManagerStationModal from "../../components/AddManagerStationModal/addmanagerStationModal";
import EditManagerStationModal from "../../components/EditManagerStationModal/editManagerStationModal";

export default function ManagerStationDetails() {
	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 managerStationDetails = useSelector(
		(state: RootState) => state.managerStationReducer.stationDetails
	);

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

	const handleClickOpen = () => {
		setRowData(null);
		setAddModalOpen(true);
	};

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

	const handleAddManager = async (data: {
		stationId: string;
		connectorType: string;
		power: string;
		price: string;
	}) => {
		try {
			// Add manager with stationId
			await dispatch(addStationDetails(data)); // Dispatch action to add manager
			await dispatch(stationDetailList()); // 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,
		connectorType: string,
		power: string,
		price: string
	) => {
		try {
			await dispatch(
				updateStationDetails({
					id,
					connectorType,
					power,
					price,
					isAvailable: false,
				})
			);
			await dispatch(stationDetailList());
			handleCloseModal();
		} catch (error) {
			console.error("Update failed", error);
		}
	};

	const categoryColumns: Column[] = [
		{ id: "srno", label: "Sr No" },
		{ id: "stationName", label: "Station Name" },
		{ id: "registeredAddress", label: "Station Location" },
		{ id: "connectorType", label: "Connector Type" },
		{ id: "power", label: "Max Power(KW)" },
		{ id: "price", label: "Price" },
		{ id: "isAvailable", label: "Is Available", align: "center" },
		{ id: "action", label: "Action", align: "center" },
	];

	const categoryRows = managerStationDetails?.length
		? managerStationDetails.map((managerStation, index) => {
				return {
					id: managerStation.id,
					srno: index + 1,
					stationName: managerStation?.stationName ?? "NA",
					registeredAddress: managerStation.registeredAddress,
					connectorType: managerStation.connectorType,
					power: managerStation.power,
					price: managerStation.price ?? "NA",
					isAvailable: managerStation?.isAvailable ? "Yes" : "No",
				};
		  })
		: [];

	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-station"
				handleClickOpen={handleClickOpen}
			/>
			{/* Add Manager Modal */}
			<AddManagerStationModal
				open={addModalOpen}
				handleClose={handleCloseModal}
				handleAddManager={handleAddManager}
			/>
			{/* Edit Manager Modal */}
			<EditManagerStationModal
				open={editModalOpen}
				handleClose={handleCloseModal}
				handleUpdate={handleUpdate}
				editRow={rowData}
			/>
		</>
	);
}
