import React, { useEffect, useState } from "react";
import { Box, Button, TextField, Typography } from "@mui/material";
import CustomTable, { Column } from "../../components/CustomTable";
import AddManagerModal from "../../components/AddManagerModal";
import EditManagerModal from "../../components/EditManagerModal";
import { useDispatch, useSelector } from "react-redux";
import { RootState, AppDispatch } from "../../redux/store/store";
import {
	managerList,
	addManager,
	updateManager,
	deleteManager,
} 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 [editRow, setEditRow] = useState<any>(null);
	const { reset } = useForm();

	const [deleteModal, setDeleteModal] = useState<boolean>(false);
	const [viewModal, setViewModal] = useState<boolean>(false);
	const [rowData, setRowData] = useState<any | null>(null);
	const [searchTerm, setSearchTerm] = useState("");
	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 categoryColumns: Column[] = [
	// 	{ id: "srno", label: "Sr No" },
	// 	{ id: "name", label: "Name" },
	// 	{ id: "email", label: "Email" },
	// 	{ id: "phone", label: "Phone" },
	// 	{ id: "stationName", label: "Station Name" }, // Added station name column
	// 	{ id: "stationAddress", label: "Station Location" }, // Added station address column
	// 	{ id: "action", label: "Action", align: "center" },
	// ];


	// Filter managers based on search term
	const filteredManagers = managers?.filter(
		(manager) =>
			manager.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
			manager.email?.toLowerCase().includes(searchTerm.toLowerCase()) ||
			manager.phone?.toLowerCase().includes(searchTerm.toLowerCase()) 
	
	);

	// Format rows to display manager details
	// const categoryRows = filteredManagers?.length
	// 	? filteredManagers?.map(
	// 			(
	// 				manager: {
	// 					id: number;
	// 					name: string;
	// 					email: string;
	// 					phone: string;
						
					
	// 				},
	// 				index: number
	// 			) => ({
	// 				id: manager?.id,
	// 				srno: index + 1,
	// 				name: manager?.name,
	// 				email: manager?.email,
	// 				phone: manager.phone ?? "NA",
	// 			})
	// 	  )
	// 	: [];

const categoryRows = filteredManagers?.length
	? filteredManagers.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}
			/>
		</>
	);
}
