import { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import { coloredToast } from '@/lib/toast';
import Flatpickr from 'react-flatpickr';
import 'flatpickr/dist/flatpickr.css';
import Select from 'react-select';
import { getProvince, getCity, getDistrict } from '@/lib/address-lib';
import { SaveUser } from '@/utils/saveUser';
import { logActivity } from '@/utils/activityLogger';
interface User {
    id: string;
    name: string;
    email: string;
    password: string;
    role: string;
    phone: string;
    birthday: string;
    birthday_notification: boolean;
    gender: string;
    is_google: string;
    is_woo: string;
    is_fb: string;
    shipping: {
        name: string;
        phone: string;
        address: string;
        kecamatan: string;
        kelurahan: string;
        kota: string;
        provinsi: string;
        kodepos: string;
    };
}
interface Options {
    value: string;
    label: string;
}
interface UserFormProps {
    userForm: User;
    setUserForm: React.Dispatch<React.SetStateAction<User>>;
    isCreate: boolean;
    isUpdate: boolean;
}

const UserForm: React.FC<UserFormProps> = ({ userForm, setUserForm, isCreate, isUpdate }) => {
    const provinceList = getProvince();
    const [dataKecamatan, setDataKecamatan] = useState<Options[]>([]);
    const [dataKota, setDataKota] = useState<Options[]>([]);
    
    const handleChange = (e: any) => {
        setUserForm((prev) => ({
            ...prev,
            [e.target.name]: e.target.value,
        }));
    };
    const handleChangeShipping = (e: any) => {
        const { name, value } = e.target;

        setUserForm((prev) => ({
            ...prev,
            shipping: {
                ...prev.shipping,
                [name]: value,
            },
        }));
    };

    const setBirthday = (selectedDates: Date[]) => {
        if (selectedDates.length > 0) {
            const selectedDate = selectedDates[0];
            const year = selectedDate.getFullYear();
            const month = String(selectedDate.getMonth() + 1).padStart(2, '0');
            const day = String(selectedDate.getDate()).padStart(2, '0');
            const formattedBirthday = `${year}-${month}-${day}`;
            setUserForm((prev) => ({
                ...prev,
                birthday: formattedBirthday,
            }));
        }
    };

    useEffect(() => {
        const cityList = getCity(userForm.shipping.provinsi);
        setDataKota(cityList);
    }, [userForm.shipping.provinsi]);

    useEffect(() => {
        const districtList = getDistrict(userForm.shipping.kota);
        setDataKecamatan(districtList);
    }, [userForm.shipping.kota]);

    const router = useRouter();
    const [isLoading, setIsLoading] = useState(false);

    const saveUser = async () => {
        setIsLoading(true);
        const validationSave = SaveUser(userForm);
        if (validationSave.status === false) {
            setIsLoading(false);
            return;
        }

        try {
            const api_url = process.env.API_URL;
            const payload = {
                data: validationSave.data,
            };

            const fetchUrl = isCreate ? `${api_url}api/users/store` : `${api_url}api/users/${userForm.id}`;
            const method = isCreate ? 'POST' : 'PUT';
            // login credential
            const response = await fetch(fetchUrl, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(payload),
                credentials: 'include', // Include this option
            });

            // condition add order failed
            if (!response.ok) {
                const res = await response.json();
                coloredToast('warning', res.message);
                setIsLoading(false);
                return;
            }

            coloredToast('success', `user ${isCreate ? 'created' : 'updated'} successfully`);
            await logActivity({
                location: 'Setting User',
                description: `User - ${userForm.name} - Berhasil ${isCreate ? 'Dibuat' : 'Diubah'}`,
            });
            router.push('/setting/users');
        } catch (error) {
            console.error(error);
            await logActivity({
                location: 'Setting User',
                description: `User - ${userForm.name} - Gagal ${isCreate ? 'Dibuat' : 'Diubah'}`,
            });
            coloredToast('danger', 'somthing went wrong');
        }

        setIsLoading(false);
    };

    return (
        <>
            <div className="panel flex-1 px-0 py-6 ltr:xl:mr-6 rtl:xl:ml-6">
                <div className="flex flex-wrap justify-between px-4">
                    <div className="mb-4 w-full lg:w-1/2 lg:max-w-fit">
                        <div className="text-lg">User Detail : </div>

                        <div className="mt-4 flex items-center">
                            <label htmlFor="email" className="mb-0 flex-1  ltr:mr-2 rtl:ml-2">
                                Email
                            </label>
                            <input
                                id="email"
                                type="email"
                                readOnly={isCreate ? false : true}
                                name="email"
                                className="form-input w-2/3  lg:w-[250px]"
                                placeholder="Enter Email"
                                value={userForm.email}
                                onChange={handleChange}
                            />
                        </div>
                        <div className="mt-4 flex items-center">
                            <label htmlFor="name" className="mb-0 flex-1  ltr:mr-2 rtl:ml-2">
                                Name
                            </label>
                            <input id="name" type="text" name="name" className="form-input w-2/3  lg:w-[250px]" placeholder="Enter Name" value={userForm.name} onChange={handleChange} />
                        </div>
                        <div className="mt-4 flex items-center">
                            <label htmlFor="phone" className="mb-0 flex-1  ltr:mr-2 rtl:ml-2">
                                Phone
                            </label>
                            <input id="phone" type="text" name="phone" className="form-input w-2/3  lg:w-[250px]" placeholder="Enter Phone" value={userForm.phone} onChange={handleChange} />
                        </div>
                        <div className="mt-4 flex items-center">
                            <label htmlFor="gender" className="mb-0 flex-1  ltr:mr-2 rtl:ml-2">
                                Gender
                            </label>
                            <select className="form-select" name="gender" value={userForm.gender} onChange={handleChange}>
                                <option value="">Select Gender</option>
                                <option value="female">Female</option>
                                <option value="male">Male</option>
                            </select>
                        </div>
                        <div className="mt-4 flex items-center">
                            <label htmlFor="birthday" className="mb-0 flex-1  ltr:mr-2 rtl:ml-2">
                                Birthday
                            </label>
                            <Flatpickr
                                options={{
                                    dateFormat: 'Y-m-d',
                                    position: 'auto left',
                                }}
                                value={userForm.birthday}
                                className="form-input w-2/3 lg:w-[250px]"
                                placeholder="yyyy-mm-dd"
                                onChange={(birthday) => setBirthday(birthday)}
                            />
                        </div>
                    </div>
                    <div className="mb-4 w-full lg:w-1/2 lg:max-w-fit">
                        <div className="text-lg">Shipping Detail : </div>
                        <div className="mt-4 flex items-center">
                            <label htmlFor="name" className="mb-0 flex-1  ltr:mr-2 rtl:ml-2">
                                Name
                            </label>
                            <input
                                id="shipping_name"
                                type="text"
                                name="name"
                                className="form-input w-2/3  lg:w-[250px]"
                                placeholder="Enter Name"
                                value={userForm.shipping.name}
                                onChange={handleChangeShipping}
                            />
                        </div>
                        <div className="mt-4 flex items-center">
                            <label htmlFor="phone" className="mb-0 flex-1  ltr:mr-2 rtl:ml-2">
                                Phone
                            </label>
                            <input
                                id="shipping_phone"
                                type="text"
                                name="phone"
                                className="form-input w-2/3  lg:w-[250px]"
                                placeholder="Enter Phone"
                                value={userForm.shipping.phone}
                                onChange={handleChangeShipping}
                            />
                        </div>
                        <div className="mt-4 flex items-center">
                            <label htmlFor="shipping_address" className="mb-0  flex-1  ltr:mr-2 rtl:ml-2 ">
                                Address
                            </label>
                            <textarea
                                id="shipping_address"
                                name="address"
                                className="form-input w-2/3 lg:w-[250px]"
                                placeholder="Enter Address"
                                value={userForm.shipping.address}
                                onChange={handleChangeShipping}
                            ></textarea>
                        </div>
                        <div className="custom-select mt-4 flex items-center">
                            <label htmlFor="shipping_province" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                Province
                            </label>
                            <Select
                                options={provinceList}
                                id="shipping_province"
                                value={provinceList.find((options) => options.value === userForm.shipping.provinsi)}
                                className="  w-2/3 lg:w-[250px]"
                                placeholder="Enter Province"
                                name="shipping_province"
                                onChange={(selectedOption: { value: string } | null) => {
                                    if (selectedOption) {
                                        setUserForm({
                                            ...userForm,
                                            shipping: {
                                                ...userForm.shipping,
                                                provinsi: selectedOption.value,
                                                kota: '',
                                                kecamatan: '',
                                            },
                                        });
                                    }
                                }}
                            />
                        </div>
                        <div className="custom-select mt-4 flex items-center">
                            <label htmlFor="shipping_city" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                City
                            </label>
                            <Select
                                options={dataKota}
                                id="shipping_city"
                                value={dataKota.find((options) => options.value === userForm.shipping.kota) || null}
                                className="  w-2/3 lg:w-[250px]"
                                placeholder="Enter City"
                                name="shipping_city"
                                onChange={(selectedOption: { value: string } | null) => {
                                    if (selectedOption) {
                                        setUserForm({
                                            ...userForm,
                                            shipping: {
                                                ...userForm.shipping,
                                                kota: selectedOption.value,
                                                kecamatan: '',
                                            },
                                        });
                                    }
                                }}
                            />
                        </div>
                        <div className="custom-select mt-4 flex items-center">
                            <label htmlFor="shipping_city" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                Kecamatan
                            </label>
                            <Select
                                options={dataKecamatan}
                                id="shipping_kecamatan"
                                value={dataKecamatan.find((options) => options.value === userForm.shipping.kecamatan) || null}
                                className="  w-2/3 lg:w-[250px]"
                                placeholder="Enter Kecamatan"
                                name="shipping_kecamatan"
                                onChange={(selectedOption: { value: string } | null) => {
                                    if (selectedOption) {
                                        setUserForm({
                                            ...userForm,
                                            shipping: {
                                                ...userForm.shipping,
                                                kecamatan: selectedOption.value,
                                            },
                                        });
                                    }
                                }}
                            />
                        </div>
                        <div className="mt-4 flex items-center">
                            <label htmlFor="kelurahan" className="mb-0 flex-1  ltr:mr-2 rtl:ml-2">
                                Kelurahan
                            </label>
                            <input
                                id="kelurahan"
                                type="text"
                                name="kelurahan"
                                className="form-input w-2/3  lg:w-[250px]"
                                placeholder="Enter Kelurahan"
                                value={userForm.shipping.kelurahan}
                                onChange={handleChangeShipping}
                            />
                        </div>
                        <div className="mt-4 flex items-center">
                            <label htmlFor="kodepos" className="mb-0 flex-1  ltr:mr-2 rtl:ml-2">
                                Postcode
                            </label>
                            <input
                                id="kodepos"
                                type="number"
                                name="kodepos"
                                className="form-input w-2/3  lg:w-[250px]"
                                placeholder="Enter postcode"
                                value={userForm.shipping.kodepos}
                                onChange={handleChangeShipping}
                            />
                        </div>
                    </div>
                </div>
            </div>
            <div>
                {userForm.role !== 'super admin' && (
                    <>
                        <div className="mt-6 w-full xl:mt-0 xl:w-96">
                            <div className="panel  mb-5">
                                <label htmlFor="role">User Role</label>
                                <select id="role" name="role" className="form-select" value={userForm.role} onChange={handleChange}>
                                    <option value="">Select Role</option>
                                    <option value="customer">Customer</option>
                                    <option value="administrator">Administrator</option>
                                </select>
                            </div>
                        </div>
                        <div className="mt-6 w-full xl:mt-0 xl:w-96">
                            <div className="panel  mb-5">
                                <label htmlFor="role">{isCreate ? 'Add ' : 'Update '} Password</label>
                                <input id="password" type="password" name="password" className="form-input " placeholder="Enter postcode" value={userForm.password} onChange={handleChange} />
                            </div>
                        </div>
                    </>
                )}
                <div className="mt-6 w-full xl:mt-0 xl:w-96">
                    <div className="panel">
                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-1">
                            <button type="button" disabled={isLoading} onClick={saveUser} className="btn btn-success w-full gap-2">
                                {isLoading ? (
                                    <span className="inline-block h-5 w-5 animate-spin rounded-full border-2 border-white border-l-transparent align-middle ltr:mr-4 rtl:ml-4"></span>
                                ) : (
                                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 shrink-0 ltr:mr-2 rtl:ml-2">
                                        <path
                                            d="M3.46447 20.5355C4.92893 22 7.28595 22 12 22C16.714 22 19.0711 22 20.5355 20.5355C22 19.0711 22 16.714 22 12C22 11.6585 22 11.4878 21.9848 11.3142C21.9142 10.5049 21.586 9.71257 21.0637 9.09034C20.9516 8.95687 20.828 8.83317 20.5806 8.58578L15.4142 3.41944C15.1668 3.17206 15.0431 3.04835 14.9097 2.93631C14.2874 2.414 13.4951 2.08581 12.6858 2.01515C12.5122 2 12.3415 2 12 2C7.28595 2 4.92893 2 3.46447 3.46447C2 4.92893 2 7.28595 2 12C2 16.714 2 19.0711 3.46447 20.5355Z"
                                            stroke="currentColor"
                                            strokeWidth="1.5"
                                        />
                                        <path
                                            d="M17 22V21C17 19.1144 17 18.1716 16.4142 17.5858C15.8284 17 14.8856 17 13 17H11C9.11438 17 8.17157 17 7.58579 17.5858C7 18.1716 7 19.1144 7 21V22"
                                            stroke="currentColor"
                                            strokeWidth="1.5"
                                        />
                                        <path opacity="0.5" d="M7 8H13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                    </svg>
                                )}
                                Save
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
};
export default UserForm;
