import { useForm, Controller } from "react-hook-form";
import { Box, Button, Typography, Modal } from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import { CustomIconButton, CustomTextField } from "../AddUserModal/styled.css";
import { useDispatch } from "react-redux";
import { addVehicle } from "../../redux/slices/VehicleSlice";
import { autofillFix } from "../../shared-theme/customizations/autoFill";
import { useState } from "react";

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

interface AddVehicleModalProps {
	open: boolean;
	handleClose: () => void;
}

export default function AddVehicleModal({
	open,
	handleClose,
}: AddVehicleModalProps) {
	const {
		control,
		handleSubmit,
		formState: { errors },
		reset,
		setValue,
	} = useForm<FormData>({
		defaultValues: {
			name: "",
			company: "",
			modelName: "",
			chargeType: "",
			imageFile: null,
		},
	});

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

	const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
		const file = e.target.files?.[0];
		if (file) {
			setImagePreview(URL.createObjectURL(file)); // Preview the image
			setValue("imageFile", file); // Set the file in the form
		}
	};

	const onSubmit = (data: FormData) => {
		if (!data.imageFile) {
			console.error("No file selected");
			return;
		}

		dispatch(
			addVehicle({
				name: data.name,
				company: data.company,
				modelName: data.modelName,
				chargeType: data.chargeType,
				imageFile: data.imageFile,
			})
		);

		handleClose();
		reset();
		setImagePreview(null); // Clear image preview
	};

	return (
		<Modal
			open={open}
			onClose={(e, reason) => {
				if (reason === "backdropClick") {
					return;
				}
				handleClose();
			}}
			aria-labelledby="add-vehicle-modal"
		>
			<Box
				component="form"
				onSubmit={handleSubmit(onSubmit)}
				sx={{
					position: "absolute",
					top: "50%",
					left: "50%",
					transform: "translate(-50%, -50%)",
					width: 450,
					boxShadow: 24,
					p: 0,
					borderRadius: 2,
				}}
			>
				{/* Header */}
				<Box
					sx={{
						display: "flex",
						justifyContent: "space-between",
						alignItems: "center",
						backgroundColor: "#000000",
						color: "#D0E1E9",

						padding: "16px 24px",
						borderRadius: "10px 10px 0 0",
					}}
				>
					<Typography
						variant="h6"
						fontWeight={600}
						fontSize={"16px"}
						color="#D0E1E9"
					>
						Add Vehicle
					</Typography>
					<CustomIconButton onClick={handleClose}>
						<CloseIcon />
					</CustomIconButton>
				</Box>

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

				{/* Input Fields */}
				<Box
					sx={{
						backgroundColor: "#b5c4cb",
						padding: "24px",
						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%",
									...autofillFix,
								}}
							>
								<Typography
									variant="body2"
									fontWeight={500}
									mb={0.5}
									color="#000000"
								>
									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%",
									...autofillFix,
								}}
							>
								<Typography
									variant="body2"
									fontWeight={500}
									mb={0.5}
									color="#000000"
								>
									Company
								</Typography>
								<Controller
									name="company"
									control={control}
									rules={{
										required: "Company is required",
										minLength: {
											value: 3,
											message:
												"Minimum 3 characters 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%",
									...autofillFix,
								}}
							>
								<Typography
									variant="body2"
									fontWeight={500}
									mb={0.5}
									color="#000000"
								>
									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%",
									...autofillFix,
								}}
							>
								<Typography
									variant="body2"
									fontWeight={500}
									mb={0.5}
									color="#000000"
								>
									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%",
								...autofillFix,
							}}
						>
							<Typography
								variant="body2"
								fontWeight={500}
								mb={0.5}
								color="#000000"
							>
								Upload Image
							</Typography>
							<Button
								component="label"
								sx={{
									backgroundColor: "#000000",
									color: "#D0E1E9",
									borderRadius: "8px",
									width: "100%",
									"&:hover": { backgroundColor: "#454545" },
								}}
							>
								Choose Image
								<input
									type="file"
									hidden
									accept="image/*"
									onChange={handleImageChange}
								/>
							</Button>
							{errors.imageFile && (
								<Typography
									variant="caption"
									color="error"
									sx={{ mt: 1 }}
								>
									{errors.imageFile.message}
								</Typography>
							)}
							{imagePreview && (
								<Box sx={{ marginTop: 2 }}>
									<Typography
										variant="body2"
										mb={1}
										color="#000000"
									>
										Preview:
									</Typography>
									<img
										src={imagePreview}
										alt="image preview"
										style={{
											maxWidth: "100%",
											height: "auto",
											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: "117px",
								"&:hover": { backgroundColor: "#454545" },
							}}
						>
							Add Vehicle
						</Button>
					</Box>
				</Box>
			</Box>
		</Modal>
	);
}
