import React, { useEffect, useState } from "react";
import { Box, Button, Typography, Modal } from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import { useForm, Controller } from "react-hook-form";
import { CustomIconButton, CustomTextField } from "../AddUserModal/styled.css";

interface EditVehicleModalProps {
	open: boolean;
	handleClose: () => void;
	handleUpdate: (
		id: string,
		name: string,
		company: string,
		modelName: string,
		chargeType: string,
		imageUrl: File | null
	) => void;
	editRow: any;
}

interface FormData {
	name: string;
	company: string;
	modelName: string;
	chargeType: string;
	imageUrl: File | null;
}

const EditVehicleModal: React.FC<EditVehicleModalProps> = ({
	open,
	handleClose,
	handleUpdate,
	editRow,
}) => {
	const {
		control,
		handleSubmit,
		formState: { errors },
		setValue,
		reset,
	} = useForm<FormData>({
		defaultValues: {
			name: "",
			company: "",
			modelName: "",
			chargeType: "",
			imageUrl: null,
		},
	});

	const [imagePreview, setImagePreview] = useState<string | null>(null);

	// Set form values and image preview when editRow changes
	useEffect(() => {
		if (editRow) {
			// Set form fields
			setValue("name", editRow.name || "");
			setValue("company", editRow.company || "");
			setValue("modelName", editRow.modelName || "");
			setValue("chargeType", editRow.chargeType || "");

			// Set image preview for existing image
			if (editRow?.imageUrl) {
				const imageUrl =
					editRow.imageUrl.startsWith("http") ||
					editRow.imageUrl.startsWith("blob")
						? editRow.imageUrl
						: `${process.env.REACT_APP_BACKEND_URL}/image/${editRow.imageUrl}`;

				setImagePreview(imageUrl);
			} else {
				setImagePreview(null);
			}
		} else {
			// Reset form and preview when no editRow
			reset();
			setImagePreview(null);
		}
	}, [editRow, setValue, reset]);

	// Handle image upload
	const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
		const file = e.target.files?.[0];
		if (file) {
			setImagePreview(URL.createObjectURL(file)); // Show preview of new image
			setValue("imageUrl", file); // Update form with new file
		}
	};

	// Handle form submission
	const onSubmit = (data: FormData) => {
		handleUpdate(
			editRow.id,
			data.name,
			data.company,
			data.modelName,
			data.chargeType,
			data.imageUrl // Pass File | null to handleUpdate
		);

		handleClose();
		reset();
		setImagePreview(null); // Clear preview after submission
	};

	return (
		<Modal
			open={open}
			onClose={(e, reason) => {
				if (reason === "backdropClick") {
					return;
				}
				handleClose();
			}}
			aria-labelledby="edit-vehicle-modal"
		>
			<Box
				component="form"
				onSubmit={handleSubmit(onSubmit)}
				sx={{
					position: "absolute",
					top: "50%",
					left: "50%",
					transform: "translate(-50%, -50%)",
					width: 500,
					boxShadow: 24,
					p: 0,
					borderRadius: 2,
				}}
			>
				{/* Header */}
				<Box
					sx={{
						display: "flex",
						justifyContent: "space-between",
						alignItems: "center",
						backgroundColor: "#000000",
						color: "#D0E1E9",
						padding: "20px 24px",
						borderRadius: "10px 10px 0 0",
					}}
				>
					<Typography
						variant="h6"
						fontWeight={600}
						fontSize={"16px"}
						color="#D0E1E9"
					>
						Edit Vehicle
					</Typography>
					<CustomIconButton onClick={handleClose}>
						<CloseIcon />
					</CustomIconButton>
				</Box>

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

				{/* Input Fields */}
				<Box
					sx={{
						backgroundColor: "#b5c4cb", // light background for body
						padding: "20px",
						borderRadius: "0 0 10px 10px",
					}}
				>
					<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}
									color="#000000"
									fontSize={"16px"}
								>
									Vehicle Name
								</Typography>
								<Controller
									name="name"
									control={control}
									rules={{
										required: "Vehicle Name is required",
										minLength: {
											value: 3,
											message:
												"Minimum 3 characters required",
										},
										maxLength: {
											value: 30,
											message:
												"Maximum 30 characters allowed",
										},
										pattern: {
											value: /^[A-Za-z\s]+$/,
											message:
												"Vehicle Name must only contain letters and spaces",
										},
									}}
									render={({ field }) => (
										<CustomTextField
											{...field}
											fullWidth
											placeholder="Enter Vehicle Name"
											size="small"
											sx={{ marginTop: 1 }}
											error={!!errors.name}
											helperText={errors.name?.message}
										/>
									)}
								/>
							</Box>

							<Box
								sx={{
									display: "flex",
									flexDirection: "column",
									width: "100%",
								}}
							>
								<Typography
									variant="body2"
									fontWeight={500}
									mb={0.5}
									color="#000000"
									fontSize={"16px"}
								>
									Company
								</Typography>
								<Controller
									name="company"
									control={control}
									rules={{ required: "Company is required" }}
									render={({ field }) => (
										<CustomTextField
											{...field}
											fullWidth
											placeholder="Enter Company Name"
											size="small"
											sx={{ marginTop: 1 }}
											error={!!errors.company}
											helperText={errors.company?.message}
										/>
									)}
								/>
							</Box>
						</Box>

						{/* Second 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}
									color="#000000"
									fontSize={"16px"}
								>
									Model Name
								</Typography>
								<Controller
									name="modelName"
									control={control}
									rules={{
										required: "Model Name is required",
									}}
									render={({ field }) => (
										<CustomTextField
											{...field}
											fullWidth
											placeholder="Enter Model Name"
											size="small"
											sx={{ marginTop: 1 }}
											error={!!errors.modelName}
											helperText={
												errors.modelName?.message
											}
										/>
									)}
								/>
							</Box>

							<Box
								sx={{
									display: "flex",
									flexDirection: "column",
									width: "100%",
								}}
							>
								<Typography
									variant="body2"
									fontWeight={500}
									mb={0.5}
									color="#000000"
									fontSize={"16px"}
								>
									Charge Type
								</Typography>
								<Controller
									name="chargeType"
									control={control}
									rules={{
										required: "Charge Type is required",
									}}
									render={({ field }) => (
										<CustomTextField
											{...field}
											fullWidth
											placeholder="Enter Charge Type"
											size="small"
											sx={{ marginTop: 1 }}
											error={!!errors.chargeType}
											helperText={
												errors.chargeType?.message
											}
										/>
									)}
								/>
							</Box>
						</Box>

						{/* Image Upload */}
						<Box
							sx={{
								display: "flex",
								flexDirection: "column",
								width: "100%",
							}}
						>
							<Typography
								variant="body2"
								fontWeight={500}
								mb={0.5}
								color="#000000"
								fontSize={"16px"}
							>
								Upload Image
							</Typography>
							<Button
								component="label"
								sx={{
									backgroundColor: "#000000",
									color: "#D0E1E9",
									borderRadius: "8px",
									width: "100%",
									fontSize: "16px",
									"&:hover": { backgroundColor: "#454545" },
								}}
							>
								Choose Image
								<input
									type="file"
									hidden
									accept="image/*"
									onChange={handleImageChange}
								/>
							</Button>
							{imagePreview && (
								<Box sx={{ marginTop: 2 }}>
									<Typography
										variant="body2"
										mb={1}
										color="#000000"
										fontSize={"16px"}
									>
										Preview (
										{imagePreview.startsWith("blob")
											? "New"
											: "Existing"}
										):
									</Typography>
									<img
										src={imagePreview}
										alt="Vehicle"
										style={{
											maxWidth: "100%",
											borderRadius: "8px",
										}}
									/>
								</Box>
							)}
						</Box>
					</Box>

					{/* Submit Button */}
					<Box
						sx={{
							display: "flex",
							justifyContent: "flex-end",
							mt: 3,
						}}
					>
						<Button
							type="submit"
							sx={{
								backgroundColor: "#000000",
								color: "#D0E1E9",
								borderRadius: "8px",
								fontSize: "16px",
								width: "140px",
								"&:hover": { backgroundColor: "#454545" },
							}}
						>
							Update Vehicle
						</Button>
					</Box>
				</Box>
			</Box>
		</Modal>
	);
};

export default EditVehicleModal;
