import { Chip } from "@mui/material";
import AddStationModal from "../../components/AddStationModal";
import CustomTable, { Column } from "../../components/CustomTable";
import EditStationModal from "../../components/EditStationModal";
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 [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 stations = useSelector(
		(state: RootState) => state.stationReducer.stations
	);
		const vehicles = useSelector(
			(state: RootState) => state.vehicleReducer.vehicles
		);


	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: string;
	}) => {
		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: string,
		name: string,
		registeredAddress: string,
		totalSlots: string,
		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: number) => {
		await dispatch(toggleStatus({ id, status: newStatus }));
	};

	const filterStations = stations?.filter((station) =>
		station.name.toLocaleLowerCase().includes(searchTerm.toLowerCase())
	);

	// Mapping and formatting vehicles
	const categoryRows = filterStations?.length
		? filterStations?.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,
					registeredAddress: station.registeredAddress,
					totalSlots: station.totalSlots,
					vehicles: vehicleDisplay, // Add the formatted vehicle display here
					status:
						station.status === 1 ? "Available" : "Not Available", // Format status text
					statusValue: station.status, // Status value for toggling
				};
		  })
		: [];

	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}
			/>
		</>
	);
}
