import React, { useEffect, useState } from "react";
import { Box, Button, TextField, Typography } from "@mui/material";
import CustomTable, { Column } from "../../components/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";
import dayjs from "dayjs";
import EditManagerModal from "../../components/EditManagerModal";
import EditSlotModal from "../../components/EditSlotModal";
export default function EVSlotList() {
	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 availableSlots = useSelector(
		(state: RootState) => state?.slotReducer.availableSlots
	);

	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);
		}
	};
	console.log("isAvailable type:", typeof isAvailable);
	const handleUpdate = async (
		id: string,
		date: string,
		startTime: string,
		endTime: string,
		isAvailable: boolean
	) => {
		try {
			// Update manager with stationId
			await dispatch(
				updateSlot({
					id,
					date,
					startTime,
					endTime,
					isAvailable,
				})
			);
			await dispatch(fetchAvailableSlots()); // Refresh the list after update
			handleCloseModal(); // Close modal after update
		} 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" },
		{ id: "action", label: "Action", align: "center" },
	];

	// Make sure dayjs is imported

	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");
				console.log("availability", availableSlots.isAvailable);
				console.log("first", startTime);
				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}
			/>
		</>
	);
}
