import { IoCloseOutline } from "react-icons/io5";
import { useState } from "react";
import styles from "./EditPopUp.module.css";
import { User, useOrgUsers } from "../../../hooks/useUsers";

type EditPopUpProps = {
  closePopup: () => void;
  refetchUsers: () => Promise<void>;
  user: User;
};

const EditPopUp = ({ closePopup, refetchUsers, user }: EditPopUpProps) => {
    const { updateUser } = useOrgUsers();
    const [formData, setFormData] = useState({
        fullName: user.fullName || "",
        email: user.email || "",
        privilege: user.privilege || "",
        username: user.username || ""
    });
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
        const { name, value } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: value
        }));
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setIsSubmitting(true);
        setError(null);
        
        try {
            await updateUser(user.id, {
                fullName: formData.fullName,
                email: formData.email,
                privilege: formData.privilege,
                username: formData.username
            });
            
            // Refresh the users list and close the popup
            await refetchUsers();
            closePopup();
        } catch (error: any) {
            setError(error.message || "Failed to update user");
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <div style={popupStyles.overlay}>
            <div style={popupStyles.popup}>
                <div className={styles.popupHeader}>
                    <p>Edit User</p>
                    <button 
                        className={styles.closeButton}
                        onClick={closePopup}><IoCloseOutline className={styles.closeIcon}/>
                    </button>
                </div>
                <div className={styles.horizontalLineLight}></div>
                {error && <div className={styles.errorMessage}>{error}</div>}
                <form onSubmit={handleSubmit} className={styles.form}>
                    <div className={styles.formGroup}>
                        <label htmlFor="fullName">Name:</label>
                        <input
                            type="text"
                            id="fullName"
                            name="fullName"
                            value={formData.fullName}
                            onChange={handleChange}
                            required
                        />
                    </div>
                    <div className={styles.formGroup}>
                        <label htmlFor="email">Email:</label>
                        <input
                            type="email"
                            id="email"
                            name="email"
                            value={formData.email}
                            onChange={handleChange}
                            required
                        />
                    </div>
                    <div className={styles.formGroup}>
                        <label htmlFor="username">Username:</label>
                        <input
                            type="text"
                            id="username"
                            name="username"
                            value={formData.username}
                            onChange={handleChange}
                            required
                        />
                    </div>
                    <div className={styles.formGroup}>
                        <label htmlFor="privilege">Privilege:</label>
                        <select
                            id="privilege"
                            name="privilege"
                            value={formData.privilege}
                            onChange={handleChange}
                            required
                        >
                            <option value="admin">admin</option>
                            <option value="user">user</option>
                            <option value="sysadmin">sysadmin</option>
                        </select>
                    </div>
                    <div className={styles.horizontalLineLight}></div>
                    <div className={styles.submitButtonDiv}>
                        <button 
                            type="submit"
                            className={styles.submitButton}
                            disabled={isSubmitting}>
                                {isSubmitting ? "Updating..." : "Update"}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
};

const popupStyles: { overlay: React.CSSProperties; popup: React.CSSProperties } = {
  overlay: {
    position: "fixed",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: "rgba(0,0,0,0.5)",
    display: "flex",
    justifyContent: "center",
    alignItems: "center",

  },
  popup: {
    backgroundColor: "#fff",
    borderRadius: "8px",
    boxShadow: "0 5px 15px rgba(0,0,0,0.3)",
    position: "relative",
    width: "400px",
    maxWidth: "90%"
  }
};

export default EditPopUp; 