import React, { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import CustomTable, { Column } from "../../components/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";
import EditVehicleModal from "../../components/EditVehicleModal";

export default function VehicleList() {
	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 vehicles = useSelector(
		(state: RootState) => state.vehicleReducer.vehicles
	);

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

	const handleClickOpen = () => {
		setRowData(null); // Reset row data when opening for new admin
		setAddModalOpen(true);
	};

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

	const handleAddVehicle = async (data: {
		vehicleName: string;
		company: string;
		modelName: string;
		chargeType: string;
		imageUrl: string;
	}) => {
		try {
			await dispatch(addVehicle(data)); // Dispatch action to add vehicle
			await dispatch(vehicleList()); // Fetch the updated list
			handleCloseModal(); // Close the modal
		} catch (error) {
			console.error("Error adding vehicle", error);
		}
	};

	const handleUpdate = async (
		id: number,
		name: string,
		company: string,
		modelName: string,
		chargeType: string,
		imageUrl: string
	) => {
		try {
			await dispatch(
				updateVehicle({
					id,
					name,
					company,
					modelName,
					chargeType,
					imageUrl,
				})
			);
			await dispatch(vehicleList());
			handleCloseModal();
		} catch (error) {
			console.error("Update failed", error);
		}
	};

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

	const filteredVehicles = vehicles?.filter(
		(vehicle) =>
			vehicle.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
			vehicle.company?.toLowerCase().includes(searchTerm.toLowerCase()) ||
			vehicle.modelName
				?.toLowerCase()
				.includes(searchTerm.toLowerCase()) ||
			vehicle.chargeType
				?.toLowerCase()
				.includes(searchTerm.toLowerCase()) ||
			vehicle.imageUrl?.toLowerCase().includes(searchTerm.toLowerCase())
	);

	const categoryRows = filteredVehicles?.length
		? filteredVehicles?.map(
				(
					vehicle: {
						id: number;
						name: string;
						company: string;
						modelName: string;
						chargeType: string;
						imageUrl: string;
					},
					index: number
				) => ({
					id: vehicle?.id,
					srno: index + 1,
					name: vehicle?.name,
					company: vehicle?.company,
					modelName: vehicle?.modelName,
					chargeType: vehicle?.chargeType,
					imageUrl: vehicle?.imageUrl,
				})
		  )
		: [];

	

	return (
		<>
			<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}
			/>
		
		</>
	);
}
