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 {
	createSlot,
	fetchAvailableSlots,
	updateSlot,
} from "../../redux/slices/slotSlice";
import AddSlotModal from "../../components/AddSlotModal/addSlotModal";
import dayjs from "dayjs";
import EditSlotModal from "../../components/EditSlotModal/editSlotModal";
export default function EVSlotList() {
	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 availableSlots = useSelector(
		(state: RootState) => state?.slotReducer.availableSlots
	);
   const { user } = useSelector((state: RootState) => state?.profileReducer);
	useEffect(() => {
		dispatch(fetchAvailableSlots());
	}, [dispatch]);

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

	const handleAddSlot = async (data: {
		date: string;
		startTime: string;
		endTime: string;
		isAvailable: boolean;
	}) => {
		try {
			await dispatch(createSlot(data));
			await dispatch(fetchAvailableSlots());
			handleCloseModal();
		} catch (error) {
			console.error("Error adding slot", error);
		}
	};

	const handleUpdate = async (
		id: string,
		startTime: string,
		endTime: string,
		isAvailable: boolean
	) => {
		try {
			const formattedStartTime = dayjs(startTime, "HH:mm").format(
				"HH:mm"
			);
			const formattedEndTime = dayjs(endTime, "HH:mm").format("HH:mm");

			await dispatch(
				updateSlot({
					id,
					startTime: formattedStartTime,
					endTime: formattedEndTime,
					isAvailable,
				})
			).unwrap();

			await dispatch(fetchAvailableSlots());
			handleCloseModal();
		} catch (error) {
			console.error("Update failed", error);
		}
	};

	const slotColumns: Column[] = [
		{ id: "srno", label: "Sr No" },
		{ id: "name", label: "Station Name" },
		{ id: "stationId", label: "Station Id" },
		{ id: "date", label: "Date" },
		{ id: "startTime", label: "Start Time" },
		{ id: "endTime", label: "End Time" },
		{ id: "isAvailable", label: "Is Available", align: "center" },
		...(user?.userType === "manager"
			? [{ id: "action", label: "Action", align: "center" as const }]
			: []),
	];

	const slotRows = availableSlots?.length
		? availableSlots.map((slot, index) => {
				const formattedDate = dayjs(slot?.date).format("YYYY-MM-DD");
				const startTime = dayjs(slot?.startTime).format("HH:mm");
				const endTime = dayjs(slot?.endTime).format("HH:mm");

				return {
					srno: index + 1,
					id: slot?.id ?? "NA",
					stationId: slot?.stationId ?? "NA",
					name: slot?.ChargingStation?.name ?? "NA",
					date: formattedDate ?? "NA",
					startTime: startTime ?? "NA",
					endTime: endTime ?? "NA",
					isAvailable: slot?.isAvailable ? "Yes" : "No",
				};
		  })
		: [];

	return (
		<>
			<CustomTable
				columns={slotColumns}
				rows={slotRows}
				setDeleteModal={setDeleteModal}
				deleteModal={deleteModal}
				setViewModal={setViewModal}
				viewModal={viewModal}
				setRowData={setRowData}
				setModalOpen={() => setEditModalOpen(true)}
				tableType="slots"
				handleClickOpen={handleClickOpen}
			/>
			<AddSlotModal
				open={addModalOpen}
				handleClose={handleCloseModal}
				handleAddSlot={handleAddSlot}
			/>
			<EditSlotModal
				open={editModalOpen}
				handleClose={handleCloseModal}
				handleUpdate={handleUpdate}
				editRow={rowData}
			/>
		</>
	);
}
