import React, { useEffect } from "react";
import {
	Box,
	Button,
	Typography,
	Modal,
	FormControl,
	InputLabel,
	Select,
	MenuItem,
	Checkbox,
	ListItemText,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import { useForm, Controller } from "react-hook-form";
import {
	CustomIconButton,
	CustomTextField,
} from "../AddEditUserModel/styled.css.tsx";

// Define the types for your form data
interface FormData {
	name: string;
	registeredAddress: string;
	totalSlots: number;
	status: number;
	allowedCarIds: string[]; // Assuming allowedCarIds are the vehicle IDs
}

interface EditStationModalProps {
	open: boolean;
	handleClose: () => void;
	handleUpdate: (
		id: string,
		name: string,
		registeredAddress: string,
		totalSlots: number,
		allowedCarIds: string[]
	) => void;
	editRow?: any;
	vehicles: { id: string; name: string }[];
}

const EditStationModal: React.FC<EditStationModalProps> = ({
	open,
	handleClose,
	handleUpdate,
	editRow,
	vehicles,
}) => {
	const { control, handleSubmit, setValue, reset, watch } = useForm<FormData>(
		{
			defaultValues: {
				name: "",
				registeredAddress: "",
				totalSlots: 0,
				status: 1,
				allowedCarIds: [],
			},
		}
	);

	// Watch allowedCarIds from the form state
	const allowedCarIds = watch("allowedCarIds");

	// Set values when editRow is provided
	useEffect(() => {
		if (editRow) {
			setValue("name", editRow.name);
			setValue("registeredAddress", editRow.registeredAddress);
			setValue("totalSlots", editRow.totalSlots);
			setValue("status", editRow.status);

			// Set the allowedCarIds with the previously selected vehicle IDs
			setValue(
				"allowedCarIds",
				editRow.allowedCarIds?.map((car: any) => car.id) || []
			);
		} else {
			reset();
		}
	}, [editRow, setValue, reset]);

	// Handle form submit
	const onSubmit = (data: FormData) => {
		if (editRow) {
			handleUpdate(
				editRow.id,
				data.name,
				data.registeredAddress,
				data.totalSlots,
				data.allowedCarIds
			);
		}
		handleClose(); // Close the modal after update
		reset(); // Reset the form fields
	};

	return (
		<Modal
			open={open}
			onClose={(e, reason) => {
				if (reason === "backdropClick") {
					return;
				}
				handleClose(); // Close modal when clicking cross or cancel
			}}
			aria-labelledby="edit-station-modal"
		>
			<Box
				component="form"
				onSubmit={handleSubmit(onSubmit)}
				sx={{
					position: "absolute",
					top: "50%",
					left: "50%",
					transform: "translate(-50%, -50%)",
					width: 400,
					bgcolor: "background.paper",
					boxShadow: 24,
					p: 3,
					borderRadius: 2,
				}}
			>
				{/* Header */}
				<Box
					sx={{
						display: "flex",
						justifyContent: "space-between",
						alignItems: "center",
					}}
				>
					<Typography variant="h6" fontWeight={600}>
						Edit Charging Station
					</Typography>
					<CustomIconButton onClick={handleClose}>
						<CloseIcon />
					</CustomIconButton>
				</Box>

				{/* Horizontal Line */}
				<Box sx={{ borderBottom: "1px solid #ddd", my: 2 }} />

				{/* Input Fields */}
				<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
					{/* First Row - Two Inputs */}
					<Box sx={{ display: "flex", gap: 2 }}>
						<Box
							sx={{
								display: "flex",
								flexDirection: "column",
								width: "100%",
							}}
						>
							<Typography
								variant="body2"
								fontWeight={500}
								mb={0.5}
							>
								Station Name
							</Typography>
							<Controller
								name="name"
								control={control}
								render={({ field }) => (
									<CustomTextField
										{...field}
										fullWidth
										placeholder="Enter Station Name"
										size="small"
									/>
								)}
							/>
						</Box>

						<Box
							sx={{
								display: "flex",
								flexDirection: "column",
								width: "100%",
							}}
						>
							<Typography
								variant="body2"
								fontWeight={500}
								mb={0.5}
							>
								Station Location
							</Typography>
							<Controller
								name="registeredAddress"
								control={control}
								render={({ field }) => (
									<CustomTextField
										{...field}
										fullWidth
										placeholder="Enter Registered Address"
										size="small"
									/>
								)}
							/>
						</Box>
					</Box>

					{/* Second Row - Total Slots */}
					<Box sx={{ display: "flex", gap: 2 }}>
						<Box
							sx={{
								display: "flex",
								flexDirection: "column",
								width: "100%",
							}}
						>
							<Typography
								variant="body2"
								fontWeight={500}
								mb={0.5}
							>
								Total Slots
							</Typography>
							<Controller
								name="totalSlots"
								control={control}
								render={({ field }) => (
									<CustomTextField
										{...field}
										fullWidth
										placeholder="Enter Total Slots"
										size="small"
										type="number"
									/>
								)}
							/>
						</Box>
					</Box>

					{/* Vehicle Dropdown with Checkboxes */}
					<Box
						sx={{
							display: "flex",
							flexDirection: "column",
							width: "100%",
						}}
					>
						<Typography variant="body2" fontWeight={500}>
							Vehicle Names
						</Typography>
						<FormControl fullWidth>
							<InputLabel>Choose Vehicles</InputLabel>
							<Select
								multiple
								value={allowedCarIds || []} // Watch the allowedCarIds to reflect selected values
								onChange={(e) => {
									// Update the allowedCarIds when the selection changes
									setValue(
										"allowedCarIds",
										e.target.value as string[]
									); // Update allowedCarIds on change
								}}
								renderValue={(selected) => {
									return (selected as string[])
										.map((id) => {
											const vehicle = vehicles?.find(
												(vehicle) => vehicle.id === id
											);
											return vehicle ? vehicle.name : "";
										})
										.join(", ");
								}}
							>
								{vehicles?.map((vehicle) => (
									<MenuItem
										key={vehicle.id}
										value={vehicle.id}
									>
										<Checkbox
											checked={allowedCarIds?.includes(
												vehicle.id
											)} 
										/>
										<ListItemText primary={vehicle.name} />
									</MenuItem>
								))}
							</Select>
						</FormControl>
					</Box>
				</Box>

				{/* Submit Button */}
				<Box
					sx={{ display: "flex", justifyContent: "flex-end", mt: 3 }}
				>
					<Button
						type="submit"
						sx={{
							backgroundColor: "#52ACDF",
							color: "white",
							borderRadius: "8px",
							width: "117px",
							"&:hover": { backgroundColor: "#439BC1" },
						}}
					>
						Update Charging Station
					</Button>
				</Box>
			</Box>
		</Modal>
	);
};

export default EditStationModal;
