import React, { useEffect } from "react";
import {
    Box,
    Button,
    Typography,
    TextField,
    Modal,
    IconButton,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import { useForm, Controller } from "react-hook-form";

interface EditModalProps {
    open: boolean;
    handleClose: () => void;
    handleCreate: (data: FormData) => void;
    handleUpdate: (id: string, data: FormData) => void;
    editRow: any;
}

interface FormData {
    managerName: string;
    stationName: string;
    stationLocation: string;
    phoneNumber: string;
}

const EditModal: React.FC<EditModalProps> = ({
    open,
    handleClose,
    handleCreate,
    handleUpdate,
    editRow,
}) => {
    const {
        control,
        handleSubmit,
        formState: { errors },
        setValue,
        reset,
    } = useForm<FormData>({
        defaultValues: {
            managerName: "",
            stationName: "",
            stationLocation: "",
            phoneNumber: "",
        },
    });

    useEffect(() => {
        if (editRow) {
            setValue("managerName", editRow.managerName);
            setValue("stationName", editRow.stationName);
            setValue("stationLocation", editRow.stationLocation);
            setValue("phoneNumber", editRow.phoneNumber);
        } else {
            reset();
        }
    }, [editRow, setValue, reset]);

    const onSubmit = (data: FormData) => {
        if (editRow) {
            handleUpdate(editRow.id, data);
        } else {
            handleCreate(data);
        }
        handleClose();
        reset();
    };

    return (
        <Modal open={open} onClose={handleClose} aria-labelledby="edit-manager-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}>
                        {editRow ? "Edit Manager" : "Add Manager"}
                    </Typography>
                    <IconButton onClick={handleClose}>
                        <CloseIcon />
                    </IconButton>
                </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}>Manager Name</Typography>
                            <Controller
                                name="managerName"
                                control={control}
                                rules={{ required: "Manager Name is required" }}
                                render={({ field }) => (
                                    <TextField {...field} fullWidth placeholder="Enter Manager Name" size="small" error={!!errors.managerName} helperText={errors.managerName?.message} />
                                )}
                            />
                        </Box>

                        <Box sx={{ display: "flex", flexDirection: "column", width: "100%" }}>
                            <Typography variant="body2" fontWeight={500} mb={0.5}>Station Name</Typography>
                            <Controller
                                name="stationName"
                                control={control}
                                rules={{ required: "Station Name is required" }}
                                render={({ field }) => (
                                    <TextField {...field} fullWidth placeholder="Enter Station Name" size="small" error={!!errors.stationName} helperText={errors.stationName?.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}>Station Location</Typography>
                            <Controller
                                name="stationLocation"
                                control={control}
                                rules={{ required: "Station Location is required" }}
                                render={({ field }) => (
                                    <TextField {...field} fullWidth placeholder="Enter Station Location" size="small" error={!!errors.stationLocation} helperText={errors.stationLocation?.message} />
                                )}
                            />
                        </Box>

                        <Box sx={{ display: "flex", flexDirection: "column", width: "100%" }}>
                            <Typography variant="body2" fontWeight={500} mb={0.5}>Phone Number</Typography>
                            <Controller
                                name="phoneNumber"
                                control={control}
                                rules={{
                                    required: "Phone number is required",
                                    pattern: {
                                        value: /^[0-9]+$/,
                                        message: "Only numbers are allowed",
                                    },
                                }}
                                render={({ field }) => (
                                    <TextField {...field} fullWidth placeholder="Enter Phone Number" size="small" error={!!errors.phoneNumber} helperText={errors.phoneNumber?.message} />
                                )}
                            />
                        </Box>
                    </Box>
                </Box>

                {/* Submit Button */}
                <Box sx={{ display: "flex", justifyContent: "flex-end", mt: 3 }}>
                    <Button variant="contained" type="submit">
                        {editRow ? "Update" : "Create"}
                    </Button>
                </Box>
            </Box>
        </Modal>
    );
};

export default EditModal;