import React, { useEffect, useState } from "react";
import {
	Box,
	Button,
	Typography,
	Modal,
	CircularProgress,
	FormControlLabel,
	Switch,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import { useForm, Controller } from "react-hook-form";
import { useDispatch } from "react-redux";
import {
	updateStationDetails,
	stationDetailList,
} from "../../redux/slices/managerStationSlice"; // <-- Update path if needed
import { CustomIconButton, CustomTextField } from "../AddUserModal/styled.css";
import { AppDispatch } from "../../redux/store/store";
import { toast } from "sonner";

interface EditManagerStationModalProps {
	open: boolean;
	handleClose: () => void;
	handleUpdate: (
		id: string,
		connectorType: string,
		power: number,
		price: number,
		available: boolean
	) => Promise<void>;
	editRow: any; // Slot data including id
}
interface FormData {
	connectorType: string;
	power: number; // Changed to number
	price: number; // Changed to number
	available: boolean;
}

const EditManagerStationModal: React.FC<EditManagerStationModalProps> = ({
	open,
	handleClose,
	editRow,
}) => {
	const dispatch = useDispatch<AppDispatch>();
	const {
		control,
		handleSubmit,
		formState: { errors },
		setValue,
		reset,
	} = useForm<FormData>({
		defaultValues: {
			connectorType: "",
			power: 0, // Default to 0
			price: 0, // Default to 0
			available: false,
		},
	});

	const [loading, setLoading] = useState(false);
	const [available, setAvailable] = useState<boolean>(
		editRow?.available || false
	);

	useEffect(() => {
		
		if (editRow) {
			setValue("connectorType", editRow.connectorType);
			setValue("power", Number(editRow.power));
			setValue("price", Number(editRow.price));
			setValue("available", editRow.available); 
			setAvailable(editRow.available);
		} else {
			reset();
		}
	}, [editRow, setValue, reset]);

	const onSubmit = async (data: FormData) => {
		if (editRow) {
			setLoading(true);
			try {
				console.log("Updating station with data:", data);
				const availabilityStatus = available ? true : false;
				const response = await dispatch(
					updateStationDetails({
						id: editRow.id,
						connectorType: data.connectorType,
						power: Number(data.power),
						price: Number(data.price),
						available: availabilityStatus,
					})
				).unwrap();

				console.log("Update response:", response);

				dispatch(stationDetailList());
				handleClose();
				reset();
				toast.success("Station details updated successfully");
			} catch (error) {
				console.error("Update failed", error);
				toast.error("Failed to update station details");
			} finally {
				setLoading(false);
			}
		}
	};

	return (
		<Modal
			open={open}
			onClose={(e, reason) => {
				if (reason === "backdropClick") return;
				handleClose();
			}}
			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 Station Details
					</Typography>
					<CustomIconButton onClick={handleClose}>
						<CloseIcon />
					</CustomIconButton>
				</Box>

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

				{/* Input Fields */}
				<Box sx={{ display: "flex", flexWrap: "wrap", gap: 2 }}>
					{/* Connector Type */}
					<Box sx={{ flex: "1 1 100%" }}>
						<Typography variant="body2" fontWeight={500} mb={0.5}>
							Connector Type
						</Typography>
						<Controller
							name="connectorType"
							control={control}
							rules={{ required: "Connector type is required" }}
							render={({ field }) => (
								<CustomTextField
									{...field}
									fullWidth
									size="small"
									error={!!errors.connectorType}
									helperText={errors.connectorType?.message}
								/>
							)}
						/>
					</Box>

					{/* Power */}
					<Box sx={{ flex: "1 1 48%" }}>
						<Typography variant="body2" fontWeight={500} mb={0.5}>
							Power
						</Typography>
						<Controller
							name="power"
							control={control}
							rules={{ required: "Power is required" }}
							render={({ field }) => (
								<CustomTextField
									{...field}
									type="number"
									fullWidth
									size="small"
									error={!!errors.power}
									helperText={errors.power?.message}
								/>
							)}
						/>
					</Box>

					{/* Price */}
					<Box sx={{ flex: "1 1 48%" }}>
						<Typography variant="body2" fontWeight={500} mb={0.5}>
							Price
						</Typography>
						<Controller
							name="price"
							control={control}
							rules={{ required: "Price is required" }}
							render={({ field }) => (
								<CustomTextField
									{...field}
									type="number"
									fullWidth
									size="small"
									error={!!errors.price}
									helperText={errors.price?.message}
								/>
							)}
						/>
					</Box>

					{/* Available Toggle */}
					<Box
						display="flex"
						alignItems="center"
						justifyContent="space-between"
						sx={{ flex: "1 1 100%" }}
					>
						<FormControlLabel
							control={
								<Switch
									checked={available}
									onChange={() => {
										const toggle = !available;
										setAvailable(toggle);
										setValue("available", toggle);
									}}
								/>
							}
							label={available ? "Available" : "Not Available"}
							sx={{ mt: 1 }}
						/>
					</Box>
				</Box>

				{/* Submit Button */}
				<Box
					sx={{ display: "flex", justifyContent: "flex-end", mt: 3 }}
				>
					<Button
						type="submit"
						sx={{
							backgroundColor: "#52ACDF",
							color: "white",
							borderRadius: "8px",
							fontSize: "16px",
							width: "117px",
							"&:hover": { backgroundColor: "#439BC1" },
						}}
						disabled={loading}
					>
						{loading ? (
							<CircularProgress size={24} color="inherit" />
						) : (
							"Update"
						)}
					</Button>
				</Box>
			</Box>
		</Modal>
	);
};

export default EditManagerStationModal;
