import { useEffect, useState } from "react";
import CustomTable, { Column } from "../../components/CustomTable/customTable";
import { useDispatch, useSelector } from "react-redux";
import { RootState, AppDispatch } from "../../redux/store/store";
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 stationDetails = useSelector(
		(state: RootState) => state?.managerStationReducer.stationDetails
	);
	console.log("-ghg", stationDetails);
	useEffect(() => {
		dispatch(stationDetailList());
	}, [dispatch]);

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

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

	const handleAddStationDetails = async (data: {
		stationId: string;
		connectorType: string;
		power: number;
		price: number;
		available: boolean;
	}) => {
		try {
			await dispatch(addStationDetails(data));
			await dispatch(stationDetailList()); // Fetch updated station list
			handleCloseModal(); // Close modal
		} catch (error) {
			console.error("Error adding manager", error);
		}
	};

	const handleUpdate = async (
		id: string,
		connectorType: string,
		power: number,
		price: number,
		available: boolean
	) => {
		try {
			// console.log("Updating station with data:", {
			// 	id,
			// 	connectorType,
			// 	power,
			// 	price,
			// 	available,
			// });

			if (!id) {
				console.error("Error: id is missing!");
				return;
			}
			await dispatch(
				updateStationDetails({
					id,
					connectorType,
					power,
					price,
					available,
				})
			).unwrap();
			await dispatch(stationDetailList()); // Fetch updated station list
			handleCloseModal(); // Close modal
		} catch (error) {
			console.error("Update failed", error);
		}
	};

	// Columns for the table
	const categoryColumns: Column[] = [
		{ id: "srno", label: "Sr No" },
		{ id: "stationName", label: "Station Name" },
		{ id: "stationAddress", label: "Station Location" },
		{ id: "connectorType", label: "Connector Type" },
		{ id: "power", label: "Max Power(KW)" },
		{ id: "price", label: "Price" },
		{ id: "available", label: "Is Available", align: "center" },
		{ id: "action", label: "Action", align: "center" }, // Action column for Edit and Delete
	];

	// Rows for the table
	const categoryRows = stationDetails?.length
		? stationDetails.map((station, index) => {
				return {
					srno: index + 1,
					id: station?.id ?? "NA",
					stationName: station?.stationName ?? "NA",
					stationAddress: station?.stationAddress ?? "NA",
					connectorType: station?.connectorType ?? "NA",
					power: station?.power ?? "NA",
					price: station?.price ?? "NA",
					available: station?.available ? "Yes" : "No",
				};
		  })
		: [];

	return (
		<>
			{/* Custom Table to show station details */}
			<CustomTable
				columns={categoryColumns}
				rows={categoryRows}
				setDeleteModal={setDeleteModal}
				deleteModal={deleteModal}
				setViewModal={setViewModal}
				viewModal={viewModal}
				setRowData={setRowData}
				setModalOpen={() => setEditModalOpen(true)} // Open edit modal when row is clicked
				tableType="manager-station"
				handleClickOpen={handleClickOpen} // Open add modal
			/>

			{/* Add Manager Station Modal */}
			<AddManagerStationModal
				open={addModalOpen}
				handleClose={handleCloseModal}
				handleAddStationDetails={handleAddStationDetails}
			/>

			{/* Edit Manager Station Modal */}
			<EditManagerStationModal
				open={editModalOpen}
				handleClose={handleCloseModal}
				handleUpdate={handleUpdate} // Pass the update handler
				editRow={rowData} // Pass the selected row data for editing
			/>
		</>
	);
}
