import React, { useEffect, useState } from 'react';
import { useForm } from '@inertiajs/react';
import Modal from '@/Components/Admin/ui/Modal';
import InputField from "@/Components/Admin/ui/InputField";
import FileUploadInput from '@/Components/Admin/ui/FileUploadInput';
import SelectField from '@/Components/Admin/ui/SelectField';
import { useFormResponse } from '@/hooks/useFormResponse';
import { toast, Toaster } from 'react-hot-toast';

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

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

    useEffect(() => {
        setData({
          name: initialData?.name || '',
          email: initialData?.email || '',
          photo: initialData?.photo || '',
          status: initialData?.status || '',
          role: initialData?.role || '',
          
        });
      }, [initialData, setData]);
    
    const handleSave = (event) => {
    event.preventDefault();
    const formResponse = useFormResponse(reset);
    put(`/admin/api/update_user/${initialData.id}`, {
        ...formResponse,
        preserveScroll: true,
    });

    onClose?.();
    };

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

    const handleError = (error) => {
            console.error("Upload error:", error);
        };
    
    return(
        <>
        <Toaster />
        <Modal
        isOpen={isOpen}
        onClose={onClose}
        title="Edit User Profile"
        size="large"
        primaryButtonText="Save Changes"
        onPrimaryAction={handleSave}>
            <form onSubmit={handleSave}>
                    <div className='row'>
                        {/* Column one */}
                        <div className="col-lg-6">
                            <InputField label="Name" type="text" id="title" 
                            value={data.name}
                            onChange={(e) => setData('name', e.target.value)}/>    

                            <InputField label="Password" type="password" id="subtitle"
                            value={data.password}
                            onChange={(e) => setData('password', e.target.value)}
                            /> 

                            <SelectField label="Role" id="roles" 
                            options={roles.map((role) => ({
                                label: role.name,
                                value: role.id,
                            }))}
                            onChange={(value) => setData('role', value)}
                            value={data.role}
                            />

                            <FileUploadInput
                                label="Upload image"
                                inputId="customFileUpload"
                                buttonText={"Choose file"}
                                uploadUrl="/admin/api/user/upload_image"
                                onSuccess={handleSuccess}
                                onError={handleError}
                                previewUrl={`/storage/${data.photo}`}


                            />  
                            
                        </div> 
                        {/* Column Two   */}
                        <div className="col-lg-6">
                            <InputField label="Email" type="text" id="subtitle"
                            value={data.email}
                            onChange={(e) => setData('email', e.target.value)}
                            disabled
                            />

                            <InputField label="Confirm password" type="password" id="subtitle"
                            value={data.password_confirmation}
                            onChange={(e) => setData('password_confirmation', e.target.value)}
                            /> 

                            <SelectField label="Status" id="status" 
                            options={[
                                { label: "Active", value: "active" },
                                { label: "Inactive", value: "inactive" },
                            ]}
                            onChange={(value) => setData("status", value)} 
                            value={data.status}
                            />
                        </div>
                    </div>
                </form>

        </Modal>
        </>
    );
}