
import AddStationModal from "../../components/AddStationModal/addStationModal";
import CustomTable, { Column } from "../../components/CustomTable/customTable";
import EditStationModal from "../../components/EditStationModal/editSationModal";
import {
	createStation,
	stationList,
	toggleStatus,
	updateStation,
} from "../../redux/slices/stationSlice";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../redux/reducers";
import { AppDispatch } from "../../redux/store/store";
import { useForm } from "react-hook-form";

export default function StationList() {
	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 vehicles = useSelector(
		(state: RootState) => state.vehicleReducer.vehicles
	);
	const stations = useSelector(
		(state: RootState) => state.stationReducer.stations
	);
	useEffect(() => {
		dispatch(stationList());
	}, [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 handleAddStation = async (data: {
		name: string;
		registeredAddress: string;
		totalSlots: number;
		allowedCarIds: number[];
	}) => {
		try {
			await dispatch(createStation(data)); // Dispatch action to add Station
			await dispatch(stationList()); // Fetch the updated list
			handleCloseModal(); // Close the modal
		} catch (error) {
			console.error("Error adding Station", error);
		}
	};

	const handleUpdate = async (
		id: number,
		name: string,
		registeredAddress: string,
		totalSlots: number,
		allowedCarIds: number[]
	) => {
		try {
			await dispatch(
				updateStation({
					id,
					name,
					registeredAddress,
					totalSlots,
					status: 0,
					allowedCarIds, // Pass the updated allowedCarIds
				})
			);
			await dispatch(stationList());
			handleCloseModal();
		} catch (error) {
			console.error("Update failed", error);
		}
	};

	const handleStatusToggle = async (id: string, newStatus: boolean) => {
		await dispatch(toggleStatus({ id, status: newStatus ? 1 : 0 })); // For stations, convert boolean to 1/0
	};

	const categoryRows = stations?.length
		? stations?.map((station: any, index: number) => {
				// Format the selected vehicles from the allowedCars array
				const formattedVehicles = station.allowedCars?.map(
					(car: any) => car.name
				);

				// Format the vehicle list like "Tata Punch Electric, Royal" or similar
				const vehicleDisplay = formattedVehicles
					? formattedVehicles.length > 1
						? `${formattedVehicles.slice(0, 2).join(", ")} + ${
								formattedVehicles.length - 2
						  }`
						: formattedVehicles.join(", ")
					: "No vehicles"; // In case there are no vehicles selected

				return {
					id: station.id,
					srno: index + 1,
					name: station.name || "N/A",
					registeredAddress: station.registeredAddress || "N/A",
					totalSlots: station.totalSlots,
					vehicles: vehicleDisplay, // Add the formatted vehicle display here
					statusValue: station?.status === 1, // Normalize to boolean (true for 1, false for 0)
					statusField: "status", // Status value for toggling
				};
		  })
		: [];
	console.log("Rowssss", categoryRows);

	const categoryColumns: Column[] = [
		{ id: "srno", label: "Sr No" },
		{ id: "id", label: "Station ID" },
		{ id: "name", label: "Station Name" },
		{ id: "registeredAddress", label: "Station Location" },
		{ id: "totalSlots", label: "Total Slots" },
		{ id: "vehicles", label: "Vehicles" }, // Add Vehicles column here
		{ id: "status", label: "Status" }, // Add Status column here
		{ id: "action", label: "Action", align: "center" },
	];

	return (
		<>
			<CustomTable
				columns={categoryColumns}
				rows={categoryRows}
				setDeleteModal={setDeleteModal}
				deleteModal={deleteModal}
				setViewModal={setViewModal}
				viewModal={viewModal}
				setRowData={setRowData}
				setModalOpen={() => setEditModalOpen(true)}
				handleStatusToggle={handleStatusToggle}
				tableType="station"
				handleClickOpen={handleClickOpen}
			/>
			<AddStationModal
				open={addModalOpen}
				handleClose={handleCloseModal}
				handleAddStation={handleAddStation}
			/>
			<EditStationModal
				open={editModalOpen}
				handleClose={handleCloseModal}
				handleUpdate={handleUpdate}
				editRow={rowData}
				vehicles={vehicles}
			/>
		</>
	);
}
