import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import CustomTable, { Column } from "../../components/CustomTable/customTable";
import { RootState } from "../../redux/reducers";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch } from "../../redux/store/store";
import {
	addVehicle,
	updateVehicle,
	vehicleList,
} from "../../redux/slices/VehicleSlice";
import AddVehicleModal from "../../components/AddVehicleModal/addVehicleModal";
import EditVehicleModal from "../../components/EditVehicleModal/editVehicleModal";

export default function VehicleList() {
	const [addModalOpen, setAddModalOpen] = useState<boolean>(false);
	const [editModalOpen, setEditModalOpen] = useState<boolean>(false);
	const [isAdding, setIsAdding] = 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 vehicles = useSelector(
		(state: RootState) => state.vehicleReducer.vehicles
	);

	useEffect(() => {
		dispatch(vehicleList());
	}, [dispatch]);

	console.log("Backend URL:", process.env.REACT_APP_BACKEND_URL);

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

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

	const handleAddVehicle = async (data: {
		name: string;
		company: string;
		modelName: string;
		chargeType: string;
		imageFile: File;
	}) => {
		try {
			setIsAdding(true);
			const response = await dispatch(addVehicle(data));
			console.log("Added vehicle response: ", response);
			handleCloseModal();
		} catch (error) {
			console.error("Error adding vehicle", error);
		} finally {
			setIsAdding(false);
		}
	};



const handleUpdate = (
	id: string,
	name: string,
	company: string,
	modelName: string,
	chargeType: string,
	imageUrl: File | null
) => {
	dispatch(
		updateVehicle({
			id,
			name,
			company,
			modelName,
			chargeType,
			imageUrl, // File or null
		})
	);
};


	const categoryColumns: Column[] = [
		{ id: "srno", label: "Sr No" },
		{ id: "imageUrl", label: "Image" },
		{ id: "name", label: "Vehicle Name" },
		{ id: "company", label: "Company" },
		{ id: "modelName", label: "Model Name" },
		{ id: "chargeType", label: "Charge Type" },

		{ id: "action", label: "Action", align: "center" },
	];

	const categoryRows = vehicles?.length
		? vehicles?.map(
				(
					vehicle: {
						id: number;
						name: string;
						company: string;
						modelName: string;
						chargeType: string;
						imageUrl: string;
					},
					index: number
				) => {
					const imageUrl = vehicle?.imageUrl
						? `${process.env.REACT_APP_BACKEND_URL}/image/${vehicle?.imageUrl}`
						: "/images/fallback.jpg";
					console.log(
						"Vehicle:",
						vehicle.name,
						"Image URL:",
						imageUrl
					);
					return {
						id: vehicle?.id,
						srno: index + 1,
						name: vehicle?.name,
						company: vehicle?.company,
						modelName: vehicle?.modelName,
						chargeType: vehicle?.chargeType,
						imageUrl,
					};
				}
		  )
		: [];

	return (
		<>
			{isAdding ? <p>Adding vehicle...</p> : null}
			<CustomTable
				columns={categoryColumns}
				rows={categoryRows}
				setDeleteModal={setDeleteModal}
				deleteModal={deleteModal}
				setViewModal={setViewModal}
				viewModal={viewModal}
				setRowData={setRowData}
				setModalOpen={() => setEditModalOpen(true)}
				tableType="vehicle"
				handleClickOpen={handleClickOpen}
			/>
			<AddVehicleModal
				open={addModalOpen}
				handleClose={handleCloseModal}
				handleAddVehicle={handleAddVehicle}
			/>
			<EditVehicleModal
				open={editModalOpen}
				handleClose={handleCloseModal}
				handleUpdate={handleUpdate}
				editRow={rowData}
			/>
		</>
	);
}
