"use client";

import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import CloseOutlinedIcon from "@mui/icons-material/CloseOutlined";
import HomeOutlinedIcon from "@mui/icons-material/HomeOutlined";
import SaveOutlinedIcon from "@mui/icons-material/SaveOutlined";
import { ADDRESS_TYPES } from "@/src/constants/data/address";
import { CustomerAddressFormInput, customerAddressSchema } from "@/src/utils/validators/user-schema";
import { customerAddresDefualtValues } from "@/src/utils/form-utils/user-form-utils";
import InputText from "@/src/components/custom-components/text-input";
import useMutateApi from "@/src/server_api/hooks/use-api/use-mutate-api";
import { apiEndpoints } from "@/src/server_api/config/api.endpoints";
import { useEffect } from "react";

interface AddAddressModalProps {
    open: boolean;
    onClose: () => void;
    addressData?: any;
    isEditMode?: boolean;
}

export default function AddAddressModal({
    open,
    onClose,
    addressData,
    isEditMode = false,
}: AddAddressModalProps) {

    const {
        control,
        handleSubmit,
        formState: { errors, isSubmitting },
        reset
    } = useForm<CustomerAddressFormInput>({
        resolver: zodResolver(customerAddressSchema),
        defaultValues: customerAddresDefualtValues()
    });

    useEffect(() => {
        if (open) {
            if (isEditMode && addressData) {
                reset({
                    addressId: addressData?._id,
                    addressType: addressData?.addressType,
                    defaultAddress: addressData?.defaultAddress,
                    name: addressData?.name,
                    phoneNumber: addressData?.phoneNumber,
                    address1: addressData?.address1,
                    address2: addressData?.address2 ?? "",
                    city: addressData?.city,
                    state: addressData?.state,
                    country: addressData?.country,
                    addressMode: addressData?.addressMode,
                    longitude: addressData?.longitude,
                    latitude: addressData?.latitude

                });
            } else {
                reset(customerAddresDefualtValues());
            }
        }
    }, [open, isEditMode, addressData, reset]);

    const { mutate, isLoading } = useMutateApi({
        alertMessage: (response: any) => ({
            messages: response.message,
            type: "success",
            from: "login",
        }),
        isRefresh: true,
        isUpdateQuery: true,
        isCloseModal: true,
        apiKey: [apiEndpoints.address.address],
        onSuccessCallback: async (response: any) => {
            reset(customerAddresDefualtValues());
            onClose()

        },
    });

    const onSubmit = (data: CustomerAddressFormInput) => {
        const payload = {
            ...data,
            addressId: data?.addressId,
            addressMode: data?.addressMode,
            apiEndpoint: apiEndpoints.address.add_address
        };

        mutate(payload as any);
    };

    if (!open) return null;

    return (
        <div className="fixed inset-0 z-[9999] flex items-center justify-center px-4">
            <div
                className="absolute inset-0 bg-black/50"
                onClick={onClose}
            />
            <div
                className="
                    relative
                    z-10
                    w-full
                    max-w-xl
                    rounded-xl
                    bg-white
                    p-6
                    shadow-2xl
                    max-h-[90vh]
                    overflow-y-auto
                "
            >
                <div className="flex items-center justify-between border-b border-gray-100 pb-5">

                    <div className="flex items-center gap-3">
                        <div
                            className="
                                flex
                                h-12
                                w-12
                                items-center
                                justify-center
                                rounded-full
                                bg-secondary/10
                                text-secondary
                            "
                        >
                            <HomeOutlinedIcon />
                        </div>

                        <div>
                            {isEditMode ?
                                <h2 className="text-xl font-semibold text-primary">
                                    Edit Address
                                </h2> :
                                <h2 className="text-xl font-semibold text-primary">
                                    Add New Address
                                </h2>}

                            <p className="text-sm text-gray-500">
                                Save your delivery address
                            </p>
                        </div>
                    </div>
                    <button
                        onClick={onClose}
                        className="text-gray-500 hover:text-black"
                    >
                        <CloseOutlinedIcon />
                    </button>
                </div>
                <form
                    onSubmit={handleSubmit(onSubmit)}
                    className="mt-6 space-y-3"
                >
                    <Controller
                        name="addressType"
                        control={control}
                        render={({ field }) => (
                            <div className="w-full text-sm text-[#000000]">

                                <label className="mb-1 block text-sm font-medium text-gray-700">
                                    Address Type
                                </label>

                                <select
                                    {...field}
                                    className="
                                            h-11
                                            w-full
                                            rounded-lg
                                            border
                                            border-gray-300
                                            px-3
                                            text-sm
                                            outline-none
                                            text-[#000000]
                                            focus:border-[#304298]
                                            focus:ring-1
                                            focus:ring-[#304298]/10
                                        "
                                >
                                    {ADDRESS_TYPES.map((type) => (
                                        <option key={type} value={type}>
                                            {type}
                                        </option>
                                    ))}
                                </select>

                            </div>
                        )}
                    />
                    <div className="">

                        <Controller
                            name="name"
                            control={control}
                            render={({ field }) => (
                                <InputText
                                    {...field}
                                    labelText="Full Name"
                                    placeholder=""
                                    error={errors?.name?.message}
                                />
                            )}
                        />
                    </div>
                    <div className="mb-5">
                        <Controller
                            name="phoneNumber"
                            control={control}
                            render={({ field }) => (
                                <InputText
                                    {...field}
                                    labelText={"Phone Number"}
                                    type="number"
                                    placeholder=""
                                    error={errors?.name?.message}
                                />
                            )}
                        />
                    </div>
                    <div className="mb-5">
                        <Controller
                            name="address1"
                            control={control}
                            render={({ field }) => (
                                <InputText
                                    {...field}
                                    labelText={"Address Line 1"}
                                    placeholder=""
                                    error={errors?.address1?.message}
                                />
                            )}
                        />
                    </div>
                    <div className="mb-5">
                        <Controller
                            name="address2"
                            control={control}
                            render={({ field }) => (
                                <InputText
                                    {...field}
                                    labelText={"Address Line 2"}
                                    placeholder=""
                                    required={false}
                                    error={errors?.address2?.message}
                                />
                            )}
                        />
                    </div>
                    <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
                        <Controller
                            name="city"
                            control={control}
                            render={({ field }) => (
                                <InputText
                                    {...field}
                                    labelText={"City"}
                                    placeholder=""
                                    error={errors?.city?.message}
                                />
                            )}
                        />
                        <Controller
                            name="state"
                            control={control}
                            render={({ field }) => (
                                <InputText
                                    {...field}
                                    labelText={"State"}
                                    placeholder=""
                                    error={errors?.state?.message}
                                />
                            )}
                        />
                    </div>
                    <div>
                        <Controller
                            name="country"
                            control={control}
                            render={({ field }) => (
                                <div>
                                    <label className="block text-sm mb-1">Country</label>

                                    <select
                                        {...field}
                                        className="w-full border rounded-md px-3 py-2 border-gray-300"
                                    >
                                        <option value="">Select Country</option>
                                        <option value="UAE">UAE</option>
                                        <option value="Malaysia">Malaysia</option>
                                    </select>

                                    {errors?.country?.message && (
                                        <p className="text-red-500 text-sm mt-1">
                                            {errors.country.message}
                                        </p>
                                    )}
                                </div>
                            )}
                        />
                    </div>
                    <Controller
                        name="defaultAddress"
                        control={control}
                        render={({ field }) => (
                            <label className="flex items-center gap-2 text-sm text-primary">
                                <input
                                    type="checkbox"
                                    checked={field.value}
                                    onChange={field.onChange}
                                    className="
                                    h-4
                                    w-4
                                    cursor-pointer
                                    rounded
                                    border-gray-300
                                    accent-[var(--color-primary)]
                                "
                                />
                                Set as default address
                            </label>
                        )}
                    />
                    <button
                        type="submit"
                        disabled={isSubmitting}
                        className="
                        flex
                        w-full
                        items-center
                        justify-center
                        gap-2
                        rounded-md
                        bg-secondary
                        py-3
                        text-sm
                        font-semibold
                        text-white
                        transition
                        hover:bg-black
                        disabled:cursor-not-allowed
                        disabled:opacity-70
                        mt-5
                    "
                    >
                        {isSubmitting ? (
                            <span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                        ) : (
                            <SaveOutlinedIcon fontSize="small" />
                        )}

                        {isSubmitting ? "Saving..." : "Save Address"}
                    </button>
                </form>
            </div>
        </div>
    );
}
