import React, { useEffect, useState } from "react";
import { Box, Button, TextField, Typography } from "@mui/material";
import AddEditCategoryModal from "../../components/AddEditCategoryModal";
import { useForm } from "react-hook-form";
import CustomTable, { Column } from "../../components/CustomTable";
import { useDispatch, useSelector } from "react-redux";
import {
	adminList,
	updateAdmin,
	createAdmin,
} from "../../redux/slices/adminSlice";
import { AppDispatch, RootState } from "../../redux/store/store";
import SearchIcon from "@mui/icons-material/Search";

export default function AdminList() {
	const [modalOpen, setModalOpen] = useState(false);
	const { reset } = useForm();

	const [deleteModal, setDeleteModal] = React.useState<boolean>(false);
	const [viewModal, setViewModal] = React.useState<boolean>(false);
	const [rowData, setRowData] = React.useState<any | null>(null);

	const dispatch = useDispatch<AppDispatch>();

	const admins = useSelector((state: RootState) => state.adminReducer.admins);
	const [searchTerm, setSearchTerm] = useState("");
	useEffect(() => {
		dispatch(adminList());
	}, [dispatch]);

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

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

	const handleCreate = async (data: {
		name: string;
		email: string;
		phone: string;
		registeredAddress: string;
	}) => {
		try {
			await dispatch(createAdmin(data));
			await dispatch(adminList()); // Refresh the list after creation
			handleCloseModal();
		} catch (error) {
			console.error("Creation failed", error);
		}
	};

	const handleUpdate = async (
		id: string,
		name: string,
		email: string,
		phone: string,
		registeredAddress: string
	) => {
		try {
			await dispatch(
				updateAdmin({
					id,
					name,
					email,
					phone,
					registeredAddress,
				})
			);
			await dispatch(adminList());
		} catch (error) {
			console.error("Update failed", error);
		}
	};

	const categoryColumns: Column[] = [
		{ id: "srno", label: "Sr No" },
		{ id: "name", label: "Name" },
		{ id: "email", label: "Email" },
		{ id: "phone", label: "Phone" },
		{ id: "registeredAddress", label: "Address" },
		{ id: "action", label: "Action", align: "center" },
	];
	const filteredAdmins = admins?.filter(
		(admin) =>
			admin.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
			admin.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
			admin.phone.toLowerCase().includes(searchTerm.toLowerCase()) ||
			admin.registeredAddress
				.toLowerCase()
				.includes(searchTerm.toLowerCase())
	);

	const categoryRows = filteredAdmins?.length
		? filteredAdmins?.map(
				(
					admin: {
						id: string;
						name: string;
						email: string;
						phone: string;
						registeredAddress: string;
					},
					index: number
				) => ({
					id: admin?.id,
					srno: index + 1,
					name: admin?.name,
					email: admin?.email,
					phone: admin?.phone,
					registeredAddress: admin?.registeredAddress,
				})
		  )
		: [];

	return (
		<>
			<Typography
				component="h2"
				variant="h6"
				sx={{
					fontWeight: 600,
					mb: { xs: 2, sm: 0 },
					width: "100%",
					display: "flex",
				}}
			>
				Admins
			</Typography>

			<Box
				sx={{
					width: "100%",
					display: "flex",
					flexDirection: { xs: "column", sm: "row" },
					justifyContent: "space-between",
					alignItems: "center",
					mb: 2, // Add margin bottom for spacing
				}}
			>
				<TextField
					variant="outlined"
					size="small"
					placeholder="Search..."
					value={searchTerm}
					onChange={(e) => setSearchTerm(e.target.value)}
					sx={{
						width: { xs: "100%", sm: "30%" }, 
						marginBottom: { xs: 2, sm: 0 }, 
					}}
					InputProps={{
						startAdornment: (
							<SearchIcon
								sx={{ color: "#202020", marginRight: 1 }}
							/>
						),
					}}
				/>

				<Button
					variant="contained"
					size="medium"
					sx={{
						textAlign: "center",
						width: { xs: "100%", sm: "auto" },
					}}
					onClick={handleClickOpen}
				>
					Add Admin
				</Button>
			</Box>

			<CustomTable
				columns={categoryColumns}
				rows={categoryRows}
				setDeleteModal={setDeleteModal}
				deleteModal={deleteModal}
				setViewModal={setViewModal}
				viewModal={viewModal}
				setRowData={setRowData}
				setModalOpen={setModalOpen}
			/>
			<AddEditCategoryModal
				open={modalOpen}
				handleClose={handleCloseModal}
				handleCreate={handleCreate}
				handleUpdate={handleUpdate}
				editRow={rowData}
			/>
		</>
	);
}
