import { useEffect, useState } from 'react';
import { OptionsOrGroups } from 'react-select';
import AsyncSelect from 'react-select/async';

interface Billing {
    billing_name: string;
    billing_email: string;
    billing_phone: string;
}
interface Shipping {
    shipping_name: string;
    shipping_phone: string;
    shipping_address: string;
    shipping_province: string;
    shipping_city: string;
    shipping_kecamatan: string;
    shipping_kelurahan: string;
    shipping_postcode: string;
}

interface UserFormeProps {
    userId: string;
    setUserId: React.Dispatch<React.SetStateAction<string>>;
    setBilling: React.Dispatch<React.SetStateAction<Billing>>;
    setShipping: React.Dispatch<React.SetStateAction<Shipping>>;
}

const UserForm: React.FC<UserFormeProps> = ({ userId, setUserId, setBilling, setShipping }) => {
    const fetchData = async (inputValue: string) => {
        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/users/list?q=${inputValue}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include', // Include this option
            });
            const data = await response.json();
            return data.map((user: any) => ({ value: user.user_id, label: user.email }));
        } catch (error) {
            console.error('Error fetching data:', error);
            return [];
        }
    };
    const [selectedUser, setSelectedUser] = useState({ label: '', value: '' });

    // Use a separate useEffect to fetch user data and set selectedUser only once during the initial render
    useEffect(() => {
        // Check if userId is provided and fetch user data
        if (userId) {
            const setInitialSelectedUser = async () => {
                try {
                    const api_url = process.env.API_URL;
                    const response = await fetch(`${api_url}api/users/data/${userId}`, {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        credentials: 'include', // Include this option
                    });
                    const data = await response.json();

                    // Set the selected user when the data is fetched
                    setSelectedUser({ label: data.email, value: data.user_id });
                } catch (error) {
                    console.error('Error fetching data:', error);
                }
            };

            setInitialSelectedUser();
        }
    }, [userId]);
    let debounceTimeout: any;

    const loadOptions = async (inputValue: string): Promise<OptionsOrGroups<any, any>> => {
        return new Promise<OptionsOrGroups<any, any>>((resolve) => {
            clearTimeout(debounceTimeout);

            if (inputValue.length >= 3) {
                debounceTimeout = setTimeout(async () => {
                    try {
                        const options = await fetchData(inputValue);
                        resolve(options);
                    } catch (error) {
                        console.error('Error loading options:', error);
                        resolve([]);
                    }
                }, 1000);
            } else {
                resolve([]);
            }
        });
    };

    const setBillingShippingUser = async () => {
        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/users/data/${userId}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include', // Include this option
            });
            const data = await response.json();

            setBilling((prev) => ({
                ...prev,
                billing_name: data.name,
                billing_email: data.email,
                billing_phone: data.phone || '',
            }));

            setShipping((prev) => ({
                ...prev,
                shipping_name: data.shipping?.name || '',
                shipping_phone: data.shipping?.phone || '',
                shipping_address: data.shipping?.address || '',
                shipping_province: data.shipping?.provinsi || '',
                shipping_city: data.shipping?.kota || '',
                shipping_kecamatan: data.shipping?.kecamatan || '',
                shipping_kelurahan: data.shipping?.kelurahan || '',
                shipping_postcode: data.shipping?.kodepos || '',
            }));
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    };

    return (
        <div className="panel custom-select mb-5">
            <div className="mb-3 italic">Set user to enable point access </div>
            <label htmlFor="user_id">User Email</label>
            <AsyncSelect
                loadOptions={loadOptions}
                placeholder="Search for user"
                isClearable={true}
                value={selectedUser}
                classNamePrefix="user-form-select"
                onChange={(selectedItem: any, actionMeta: any) => {
                    if (selectedItem) {
                        setUserId(selectedItem.value);
                    } else if (actionMeta.action === 'clear') {
                        setUserId(''); // Clear the selected state
                        setSelectedUser({ label: '', value: '' });
                    }
                }}
            />
            {userId && (
                <button type="button" onClick={setBillingShippingUser} className="btn btn-info mt-3 w-full">
                    Set billing and shipping as user selected
                </button>
            )}
        </div>
    );
};
export default UserForm;
