import FormGroup from "@admin/ui/forms/FormGroup";
import Switch from "@admin/ui/forms/Switch";
import FileUploadInput from "@admin/ui/forms/FileUploadInput";
import Modal from "@admin/ui/Modal";
import { useEffect, useState } from "react";
import { useFormResponse } from '@/hooks/useFormResponse';
import { useForm } from "@inertiajs/react";

export default function EditUser({ isOpen, onClose, initialData }){
    const {data,setData,put,processing,errors,reset} = useForm({
        name: '',
        email: '',
        photo:'',
        password: '',
        password_confirmation: '',
        role: '',
        status: true,

    });

    useEffect(() => {
        if (initialData) {
          setData({
              name: initialData?.name || '',
              email: initialData?.email || '',
              photo: initialData?.photo || '',
              role: initialData?.role || '',
              status: initialData?.status === 1,
          });
        }
    }, [initialData, setData]);

    const handleSave = (event) => {
        event.preventDefault();
        const formResponse = useFormResponse(() => {
            onClose?.(); 
        });
        put(`/admin/api/update_user/${initialData.id}`, {
            preserveScroll: true,
                onSuccess: formResponse.onSuccess, 
                onError: formResponse.onError, 
            });
    };


    const [roles, setRoles] = useState([]);

    useEffect(() => {
        fetch('/admin/api/roles')
            .then((response) => response.json())
            .then((data) => setRoles(data));
    }, []);

    const handleSuccess = (filename) => {
            setData('photo',filename);
        };

    const handleError = (error) => {
            console.error("Upload error:", error);
        };

    return(
        <>
        <Modal isOpen={isOpen} onClose={onClose} title="Edit User" size="large"
        primaryButtonText="Save Changes"
        onPrimaryAction={handleSave}
        processing={processing}
        >
            <form onSubmit={handleSave}>
            <FormGroup label="Name" 
            value={data.name}
            onChange={(e) => setData('name', e.target.value)}
            invalidFeedback={errors.name}
            />
            <FormGroup label="Email" 
            type="email"
            value={data.email}
            onChange={(e) => setData('email', e.target.value)}
            invalidFeedback={errors.email}
            />
            <FormGroup
            id="exampleSelect"
            label="Role"
            as="select"
            value={data.role}
            onChange={(e) => setData("role", e.target.value)}
            required
            >
            <option value="">...</option>
            {roles.map((role) => (
                <option key={role.id} value={role.id}>
                {role.name}
                </option>
            ))}
            </FormGroup>


            <FormGroup label="Password (Optional: only fill if you want to update user's password)" 
            type="password"
            value={data.password}
            onChange={(e) => setData('password', e.target.value)}
            invalidFeedback={errors.password}
            />

            <FormGroup label="Confirm Password" 
            type="password"
            value={data.password_confirmation}
            onChange={(e) => setData('password_confirmation', e.target.value)}
            invalidFeedback={errors.password_confirmation}
            />

            <br />
            <FileUploadInput label="Upload image (200x200)px" 
            buttonText={"Choose file (200x200)"}
            uploadUrl="/admin/api/user/upload_image"
            onSuccess={handleSuccess}
            onError={handleError}
            previewUrl={`/storage/${data.photo}`}

            />
            <Switch
            id="customSwitch"
            label="Active"
            checked={data.status}
            onChange={({ target: { checked } }) =>
                setData(prevData => ({ ...prevData, status: checked }))
                }                  
                />
                <br/>
            </form>

        </Modal>
        </>
    );
}