import React, { useEffect, useState } from "react";
import {
    Dialog,
    DialogTitle,
    DialogContent,
    DialogActions,
    TextField,
    Button,
    MenuItem,
    InputAdornment,
    IconButton,
} from "@mui/material";
import { Person, Email, LocationOn, Phone, AssignmentInd, Visibility, VisibilityOff } from "@mui/icons-material"; // Icons


interface Role {
    id: number;
    name: string;
}

interface AddUserDialogProps {
    open: boolean;
    onClose: () => void;
    onUserAdded: () => void;
}

const AddUserDialog: React.FC<AddUserDialogProps> = ({ open, onClose, onUserAdded }) => {
    const [name, setName] = useState("");
    const [password, setPassword] = useState("newuser");
    const [showPassword, setShowPassword] = useState(false); // Toggle password visibility
    const [address, setAddress] = useState("");
    const [email, setEmail] = useState("");
    const [phone_number, setPhoneNumber] = useState("");
    const [is_under, setIsUnder] = useState<number | "">("");
    const [roles, setRoles] = useState<Role[]>([]);
    // const [status, setStatus] = useState(1); // 1 = Active, 0 = Inactive

    useEffect(() => {
        
        fetch(`${process.env.REACT_APP_API_BASE_URL}/role`)
            .then((res) => res.json())
            .then((data) => setRoles(data))
            .catch((error) => console.error("Error fetching roles:", error));
    }, []);

    const handleSubmit = () => {
        const newUser = {
            name,
            password,
            address,
            email,
            phone_number,
            role: 1, // Always "TBT"
            is_under,
            // status: status === 1, // Convert 1 -> true, 0 -> false
        };
        const token: string | null = localStorage.getItem('token');
    
        if (!token) {
          return;
        }
        fetch(`${process.env.REACT_APP_API_BASE_URL}/user`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",'x-api-key': token
            },
            body: JSON.stringify(newUser),
        })
            .then((response) => response.json())
            .then(() => {
                onUserAdded();
                onClose();
            })
            .catch((error) => console.error("Error adding user:", error));
    };
    
    return (
        <Dialog
            open={open}
            onClose={onClose}
            PaperProps={{
                sx: {
                    backgroundColor: "#121212",
                    border: "2px solid green",
                    borderRadius: "12px",
                    padding: "16px",
                    width: "400px",
                },
            }}
        >
            <DialogTitle sx={{ color: "green", textAlign: "center" }}>Add New User</DialogTitle>
            <DialogContent>
                {/* Name */}
                <TextField
                    autoFocus
                    margin="dense"
                    label="Name"
                    type="text"
                    fullWidth
                    variant="outlined"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    InputProps={{
                        endAdornment: (
                            <InputAdornment position="end">
                                <Person sx={{ color: "white" }} />
                            </InputAdornment>
                        ),
                    }}
                    sx={{
                        input: { color: "white" },
                        label: { color: "white" },
                        "& .MuiOutlinedInput-root": {
                            "& fieldset": { borderColor: "white" },
                            "&:hover fieldset": { borderColor: "limegreen" },
                            "&.Mui-focused fieldset": { borderColor: "limegreen" },
                        },
                    }}
                />
                {/* Email */}
                <TextField
                    margin="dense"
                    label="Email"
                    type="email"
                    fullWidth
                    variant="outlined"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    InputProps={{
                        endAdornment: (
                            <InputAdornment position="end">
                                <Email sx={{ color: "white" }} />
                            </InputAdornment>
                        ),
                    }}
                    sx={{
                        input: { color: "white" },
                        label: { color: "white" },
                        "& .MuiOutlinedInput-root": {
                            "& fieldset": { borderColor: "white" },
                            "&:hover fieldset": { borderColor: "limegreen" },
                            "&.Mui-focused fieldset": { borderColor: "limegreen" },
                        },
                    }}
                />
                {/* Password */}
                <TextField
                    margin="dense"
                    label="Password"
                    type={showPassword ? "text" : "password"}
                    fullWidth
                    variant="outlined"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    InputProps={{
                        endAdornment: (
                            <InputAdornment position="end">
                                <IconButton onClick={() => setShowPassword(!showPassword)}>
                                    {showPassword ? <VisibilityOff sx={{ color: "white" }} /> : <Visibility sx={{ color: "white" }} />}
                                </IconButton>
                            </InputAdornment>
                        ),
                    }}
                    sx={{
                        input: { color: "white" },
                        label: { color: "white" },
                        "& .MuiOutlinedInput-root": {
                            "& fieldset": { borderColor: "white" },
                            "&:hover fieldset": { borderColor: "limegreen" },
                            "&.Mui-focused fieldset": { borderColor: "limegreen" },
                        },
                    }}
                />
                {/* Address */}
                <TextField
                    margin="dense"
                    label="Address"
                    type="text"
                    fullWidth
                    variant="outlined"
                    value={address}
                    onChange={(e) => setAddress(e.target.value)}
                    InputProps={{
                        endAdornment: (
                            <InputAdornment position="end">
                                <LocationOn sx={{ color: "white" }} />
                            </InputAdornment>
                        ),
                    }}
                    sx={{
                        input: { color: "white" },
                        label: { color: "white" },
                        "& .MuiOutlinedInput-root": {
                            "& fieldset": { borderColor: "white" },
                            "&:hover fieldset": { borderColor: "limegreen" },
                            "&.Mui-focused fieldset": { borderColor: "limegreen" },
                        },
                    }}
                />
                {/* Phone Number */}
                <TextField
                    margin="dense"
                    label="Phone Number"
                    type="tel"
                    fullWidth
                    variant="outlined"
                    value={phone_number}
                    onChange={(e) => setPhoneNumber(e.target.value)}
                    InputProps={{
                        endAdornment: (
                            <InputAdornment position="end">
                                <Phone sx={{ color: "white" }} />
                            </InputAdornment>
                        ),
                    }}
                    sx={{
                        input: { color: "white" },
                        label: { color: "white" },
                        "& .MuiOutlinedInput-root": {
                            "& fieldset": { borderColor: "white" },
                            "&:hover fieldset": { borderColor: "limegreen" },
                            "&.Mui-focused fieldset": { borderColor: "limegreen" },
                        },
                    }}
                />
                {/* Is Under (Dropdown) */}
                <TextField
                    select
                    fullWidth
                    variant="outlined"
                    label="Is Under"
                    value={is_under}
                    onChange={(e) => setIsUnder(Number(e.target.value))}
                    sx={{
                        input: { color: "white" },
                        label: { color: "white" },
                        "& .MuiOutlinedInput-root": {
                            "& fieldset": { borderColor: "white" },
                            "&:hover fieldset": { borderColor: "limegreen" },
                            "&.Mui-focused fieldset": { borderColor: "limegreen" },
                        },
                    }}
                >
                    {roles.map((role) => (
                        <MenuItem key={role.id} value={role.id}>
                            {role.name}
                        </MenuItem>
                    ))}
                </TextField>
               
                {/* <Typography sx={{ color: "white", marginTop: 2 }}>Status</Typography>
                
                <FormControlLabel
                    control={
                        <Switch
                            checked={status === 1}
                            onChange={(e) => setStatus(e.target.checked ? 1 : 0)}
                            color="success"
                        />
                    }
                    label={status === 1 ? "Active" : "Inactive"}
                    sx={{ color: "white", marginTop: 2 }}
                /> */}


            </DialogContent>
            <DialogActions sx={{ justifyContent: "center" }}>
                <Button onClick={onClose} sx={{ color: "white", border: "1px solid green" }}>
                    Cancel
                </Button>
                <Button onClick={handleSubmit} sx={{ backgroundColor: "green", color: "black" }}>
                    Add User
                </Button>
            </DialogActions>
        </Dialog>
    );
};

export default AddUserDialog;
