import CustomTable, { Column } from "../../components/CustomTable/customTable";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../redux/reducers";
import { AppDispatch } from "../../redux/store/store";
import { addStationLocation, externalStationList, } from "../../redux/slices/stationSlice"; // Import setCity
import AddStationLocationModal from "../../components/AddStationLocation/addStationLocation";
import { useForm } from "react-hook-form";

export default function ExternalStationList() {
	const dispatch = useDispatch<AppDispatch>();

	const { stations, loading, error } = useSelector(
		(state: RootState) => state.stationReducer
	);

	const [city, setCityState] = useState("");
	const [addModalOpen, setAddModalOpen] = useState<boolean>(false);
	const [rowData, setRowData] = useState<any | null>(null);
	const { reset } = useForm();

	// Fetch stations when the component mounts
	useEffect(() => {
		dispatch(externalStationList());
	}, [dispatch]);
	const handleClickOpen = () => {
		setRowData(null);
		setAddModalOpen(true);
	};
	const handleCloseModal = () => {
		setAddModalOpen(false);
		setRowData(null);
		reset();
	};
	const handleAddStation = async (data: { city: string }) => {
		try {
			await dispatch(addStationLocation(data));
			dispatch(externalStationList());

			handleCloseModal();
		} catch (error) {
			console.error("Error adding slot", error);
		}
	};

	// Handle City Submission

	// Error Handling UI
	if (error) {
		console.error("Error fetching stations:", error);
	}

	// Mapping and formatting stations
	const categoryRows = stations?.length
		? stations.map((station: any, index: number) => ({
				id: station.id,
				srno: index + 1,
				name: station.name,
				registeredAddress: station.registeredAddress,
				totalSlots: station.totalSlots,
				status: station.status === 1 ? "Available" : "Not Available",
		  }))
		: [];

	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: "status", label: "Status" },
	];

	return (
		<>
			{/* Custom Table */}
			<CustomTable
				columns={categoryColumns}
				rows={categoryRows}
				tableType="external-station"
				loading={loading}
				currentPanel="external-station-list"
				handleClickOpen={handleClickOpen}
			/>
			<AddStationLocationModal
				open={addModalOpen}
				handleClose={handleCloseModal}
				handleAddStation={handleAddStation}
			/>
		</>
	);
}
