import React, { useEffect } 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();

    useEffect(() => {
        setData({
            name: initialData?.name || '',
            email: initialData?.email || '',
            phone: initialData?.phone || '',
            role_type: initialData?.role_type || '',
            status: initialData?.status || '',
            profile_photo: initialData?.profile_photo || '',
        });
    }, [initialData, setData]);

    const handleSave = (event) => {
        event.preventDefault();
        const formResponse = useFormResponse(reset);
        put(`/admin/users/${initialData.id}`, {
            ...formResponse,
            preserveScroll: true,
        });

        onClose?.();
    };

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

    const handleError = (error) => {
        console.error("Upload error:", error);
        toast.error("Failed to upload profile photo");
    };

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

                            <InputField
                                label="Email Address"
                                type="email"
                                id="email"
                                value={data.email}
                                onChange={(e) => setData('email', e.target.value)}
                                error={errors.email}
                            />

                            <InputField
                                label="Phone Number"
                                type="text"
                                id="phone"
                                value={data.phone}
                                onChange={(e) => setData('phone', e.target.value)}
                                error={errors.phone}
                            />
                        </div>

                        {/* Column two */}
                        <div className="col-lg-6">
                            <SelectField
                                label="Role"
                                id="role_type"
                                options={[
                                    { label: "Admin", value: "3" },
                                    { label: "Landlord", value: "1" },
                                    { label: "Tenant", value: "2" },
                                ]}
                                onChange={(value) => setData("role_type", value)}
                                value={data.role_type}
                                error={errors.role_type}
                            />

                            <SelectField
                                label="Status"
                                id="status"
                                options={[
                                    { label: "Active", value: "1" },
                                    { label: "Inactive", value: "2" },
                                    { label: "Suspended", value: "3" },
                                ]}
                                onChange={(value) => setData("status", value)}
                                value={data.status}
                                error={errors.status}
                            />

                            <FileUploadInput
                                label="Upload Profile Photo"
                                inputId="editProfilePhotoUpload"
                                buttonText={"Choose file"}
                                uploadUrl="/admin/api/users/upload_photo"
                                onSuccess={handleSuccess}
                                onError={handleError}
                                previewUrl={data.profile_photo ? `/storage/${data.profile_photo}` : null}
                            />
                        </div>
                    </div>
                </form>
            </Modal>
        </>
    );
}
