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,
	fetchManagersSlots,
	toggleStatus,
	updateSlot,
} from "../../redux/slices/slotSlice";
import AddSlotModal from "../../components/AddSlotModal/addSlotModal";
import EditSlotModal from "../../components/EditSlotModal/editSlotModal";
import dayjs from "dayjs";
import isBetween from "dayjs/plugin/isBetween";

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(fetchManagersSlots());
	}, [dispatch]);

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

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

	dayjs.extend(isBetween);
	// In handleAddSlot method
	const handleAddSlot = async (data: {
		date: string;
		startTime: string;
		endTime: string;
		isAvailable: boolean;
	}) => {
		try {
			// Parse start and end time from the backend format using dayjs
			const startTime = dayjs(data.startTime, "MM/DD/YYYY, h:mm:ss A");
			const endTime = dayjs(data.endTime, "MM/DD/YYYY, h:mm:ss A");

			// Check for overlap with existing slots
			const conflict = availableSlots.find((slot) => {
				const slotStartTime = dayjs(
					slot.startTime,
					"MM/DD/YYYY, h:mm:ss A"
				);
				const slotEndTime = dayjs(
					slot.endTime,
					"MM/DD/YYYY, h:mm:ss A"
				);

				return (
					slot.date === data.date &&
					(startTime.isBetween(
						slotStartTime,
						slotEndTime,
						null,
						"[)"
					) ||
						endTime.isBetween(
							slotStartTime,
							slotEndTime,
							null,
							"(]"
						))
				);
			});

			if (conflict) {
				alert(
					"There is an overlapping slot. Please choose another time."
				);
				return;
			}

			// Create the slot with duration
			const duration = endTime.diff(startTime, "minute");

			const payload = {
				date: data.date,
				startHour: startTime.format("hh:mm A"), // Ensure formatting is consistent
				endHour: endTime.format("hh:mm A"), // Ensure formatting is consistent
				isAvailable: data.isAvailable,
				duration: duration,
			};

			await dispatch(createSlot(payload));
			await dispatch(fetchManagersSlots());

			// Close the modal after successful slot creation
			handleCloseModal();
		} catch (error) {
			console.error("Error adding slot", error);
		}
	};

	// In handleUpdate method
	const handleUpdate = async (
		id: string,
		startTime: string,
		endTime: string
	) => {
		try {
			// Convert times using dayjs
			const formattedStartTime = dayjs(
				startTime,
				"MM/DD/YYYY, h:mm:ss A"
			).format("hh:mm A");
			const formattedEndTime = dayjs(
				endTime,
				"MM/DD/YYYY, h:mm:ss A"
			).format("hh:mm A");

			// Dispatch the update action
			await dispatch(
				updateSlot({
					id,
					startTime: formattedStartTime,
					endTime: formattedEndTime,
				})
			).unwrap();

			// Fetch updated slot data
			await dispatch(fetchManagersSlots());

			// Close modal after successful update
			handleCloseModal();
		} catch (error) {
			console.error("Update failed", error);
		}
	};

	const handleStatusToggle = async (id: string, newStatus: boolean) => {
		await dispatch(toggleStatus({ id, isAvailable: newStatus })); // Dispatch the action with the correct status
	};

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

	const slotRows = availableSlots?.length
		? availableSlots.map((slot, index) => {
				const startTime = dayjs(
					slot?.startTime,
					"YYYY-MM-DD hh:mm A"
				).isValid()
					? dayjs(slot?.startTime, "YYYY-MM-DD hh:mm A").format(
							"hh:mm A"
					  )
					: "Invalid";
				const endTime = dayjs(
					slot?.endTime,
					"YYYY-MM-DD hh:mm A"
				).isValid()
					? dayjs(slot?.endTime, "YYYY-MM-DD hh:mm A").format(
							"hh:mm A"
					  )
					: "Invalid";

				return {
					srno: index + 1,
					id: slot?.id ?? "NA",
					stationName: slot?.stationName ?? "NA",
					date: slot?.date ?? "NA",
					startTime: startTime ?? "NA",
					endTime: endTime ?? "NA",
					isAvailable: slot?.isAvailable
						? "Available"
						: "Not Available",
					statusValue: !!slot?.isAvailable, // Normalize to boolean (true/false)
					statusField: "isAvailable", // I
				};
		  })
		: [];

	return (
		<>
			<CustomTable
				columns={slotColumns}
				rows={slotRows}
				setDeleteModal={setDeleteModal}
				deleteModal={deleteModal}
				setViewModal={setViewModal}
				viewModal={viewModal}
				setRowData={setRowData}
				setModalOpen={() => setEditModalOpen(true)}
				tableType="slots"
				handleClickOpen={handleClickOpen}
				handleStatusToggle={handleStatusToggle} // Pass handleStatusToggle as a prop
			/>

			<AddSlotModal
				open={addModalOpen}
				handleClose={handleCloseModal}
				handleAddSlot={handleAddSlot}
			/>
			<EditSlotModal
				open={editModalOpen}
				handleClose={handleCloseModal}
				handleUpdate={handleUpdate}
				editRow={rowData}
			/>
		</>
	);
}
