"use client";

import Button from "@/components/common/Button";
import SideDrawer from "@/components/common/SideDrawer";
import { toast } from "react-toastify";
import { IoLocationOutline } from "react-icons/io5";
import { LuCirclePlus } from "react-icons/lu";
import { MdOutlineDeleteOutline, MdOutlineEdit } from "react-icons/md";
import Select from "react-select";
import { useState, useEffect, useCallback } from "react";
import DataNotFound from "@/components/common/DataNotFound";
import {
  useForm,
  FormProvider,
  Controller,
  SubmitHandler,
} from "react-hook-form";
import { useAppSelector, useAppDispatch } from "@/app/store/hooks";
import {
  fetchAddressesAction,
  storeAddressAction,
  updateAddressAction,
  deleteAddressAction,
  setPrimaryAddress,
} from "@/lib/actions/myAddressActions";
import { AddressSchemaType } from "@/lib/validations/authSchema";
import { getStoredLocale } from "@/lib/getLocale";
import { zodResolver } from "@hookform/resolvers/zod";
import { addressSchema } from "@/lib/validations/authSchema";
import { useTranslations } from "next-intl";
import Input from "@/components/common/CustomInputField";
import {
  setSelectedAddress,
  addLocalAddress,
  deleteLocalAddress,
  clearAddresses,
  updateLocalAddress,
} from "@/app/store/slices/addressSlice";
import { useRouter } from "next/navigation";
import { checkAuthErrorGet } from "@/lib/checkAuthError";
import { useStateCityForm } from "@/lib/hooks/useStateCityForm";
import MobilePageHeader from "@/components/common/MobilePageHeader";
import { IoMdAddCircleOutline } from "react-icons/io";
import { useSelectTheme } from "@/hooks/useSelectTheme";
import AccountDropdown from "@/components/common/AccountDropdown";
import RouteLoader from "@/components/common/RouteLoader";
import Loader from "@/components/common/Loader";
export default function MyAddress() {
  const locale = getStoredLocale();
  const dispatch = useAppDispatch();
  const router = useRouter();

  const { user } = useAppSelector((state) => state?.auth);
  const { addresses, isLoading, selectedAddress } = useAppSelector(
    (state) => state?.address
  );
  const [addressCountryCode, setAddressCountryCode] = useState("");
  const [activeDrawer, setActiveDrawer] = useState<
    null | "addaddress" | "editaddress"
  >(null);
  const [editingAddress, setEditingAddress] = useState<any>(null);
  const [addressToMakePrimary, setAddressToMakePrimary] = useState<
    string | null
  >(null);
  const [isSettingPrimary, setIsSettingPrimary] = useState(false);
  const closeDrawer = (shouldReset = true) => {
    setActiveDrawer(null);
    setEditingAddress(null);
    if (shouldReset) {
      reset();
      resetStateCityFields();
    }
  };

  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [addressToDelete, setAddressToDelete] = useState<any>(null);
  const t = useTranslations();

  const DEFAULT_FORM_VALUES = {
    state: { value: "", label: "" },
    city: { value: "", label: "" },
    short_address: "",
    building_name: "",
    street: "",
    secondary_number: "",
    district: "",
    address_line_1: "",
    address_line_2: "",
    postal_code: "",
    phone: "",
    address_type: "shipping" as const,
    isPrimary: false,
  };

  const handleSetPrimaryAddress = useCallback(async () => {
    if (!addressToMakePrimary) return;

    try {
      setIsSettingPrimary(true);
      const result = await setPrimaryAddress(addressToMakePrimary, user?.token);

      if (result.success) {
        toast.success(t("validation.primary_address_updated"));
        const updatedAddresses = addresses.map((addr) => ({
          ...addr,
          isPrimary: addr._id === addressToMakePrimary,
        }));
        dispatch(clearAddresses());
        updatedAddresses.forEach((addr) => dispatch(addLocalAddress(addr)));
        dispatch(setSelectedAddress(addressToMakePrimary));
      } else {
        toast.error(
          result.message || t("validation.error_setting_primary_address")
        );
      }
    } catch (error) {
      if (checkAuthErrorGet(error, dispatch, router)) return;
      toast.error(t("validation.error_setting_primary_address"));
    } finally {
      setAddressToMakePrimary(null);
      setIsSettingPrimary(false);
    }
  }, [addressToMakePrimary, addresses, dispatch, t, user?.token]);

  const handleRadioChange = (
    addressId: string,
    isCurrentlyPrimary: boolean
  ) => {
    if (isCurrentlyPrimary) return;
    setAddressToMakePrimary(addressId);
  };
  const methods = useForm<AddressSchemaType>({
    resolver: zodResolver(addressSchema(t)),
    mode: "onChange",
    defaultValues: DEFAULT_FORM_VALUES,
  });

  const {
    handleSubmit,
    control,
    setValue,
    reset,
    formState: { errors },
  } = methods;

  const [isSubmittingAddress, setIsSubmittingAddress] = useState(false);

  // Use custom hook for state/city logic
  const {
    states,
    cities,
    isLoadingStates,
    isLoadingCities,
    selectedState,
    setSelectedState,
    handleStateChange,
    handleCityChange,
    fetchAndSetCities,
    resetStateCityFields,
    resetCityField,
    resetStateField,
  } = useStateCityForm({
    userToken: user?.token ?? "",
    setValue,
    dispatch,
    router,
  });

  const [pendingCityId, setPendingCityId] = useState<string | null>(null);

  function extractMobileNumber(
    fullNumber: string,
    countryCode: string
  ): string {
    const cleanNumber = fullNumber.replace(/^\+/, "");
    const cleanCode = countryCode.replace(/^\+/, "");
    const regex = new RegExp(`^${cleanCode}`);
    return cleanNumber.replace(regex, "");
  }

  const resetForm = useCallback(() => {
    methods.reset(DEFAULT_FORM_VALUES);
    resetStateCityFields();
  }, [methods, resetStateCityFields]);

  //fetch addresses
  useEffect(() => {
    if (!user?.token) return;

    const fetchAddresses = async () => {
      try {
        const result = await fetchAddressesAction(user.token, locale);
        if (result.success) {
          dispatch(clearAddresses());
          // Add all addresses to the store
          result.data.forEach((addr: any) => dispatch(addLocalAddress(addr)));

          // Find addresses in order of priority
          const primaryAddress = result.data.find(
            (addr: any) => addr.isPrimary
          );
          const profileAddress = result.data.find(
            (addr: any) => addr.address_type === "profile"
          );
          const firstAddress = result.data[0];

          // Set selected address based on priority
          if (primaryAddress) {
            dispatch(setSelectedAddress(primaryAddress._id));
          } else if (profileAddress) {
            // If no primary but profile exists, set it as primary
            dispatch(setSelectedAddress(profileAddress._id));
            // Optionally update the address as primary in the backend
            await setPrimaryAddress(profileAddress._id, user.token);
          } else if (firstAddress) {
            // Fallback to first address if no primary or profile
            dispatch(setSelectedAddress(firstAddress._id));
            // Optionally update the first address as primary in the backend
            await setPrimaryAddress(firstAddress._id, user.token);
          }
        } else {
          toast.error(result.message || t("validation.update_failed"));
        }
      } catch (error: any) {
        if (checkAuthErrorGet(error, dispatch, router)) return;
        toast.error(t("validation.update_failed"));
      }
    };

    fetchAddresses();
  }, [user?.token, dispatch, locale, t, router]);

  // Helper function to construct address string
  const constructAddressString = (data: AddressSchemaType) =>
    `${data.short_address ? data.short_address + ", " : ""}${data.building_name ? data.building_name + ", " : ""
    }${data.street ? data.street + ", " : ""}${data.secondary_number ? data.secondary_number + ", " : ""
    }${data.district ? data.district + ", " : ""}${data.address_line_1}${data.address_line_2 ? ", " + data.address_line_2 : ""
    }, ${data.city?.label || ""}, ${data.state?.label || ""}`;

  // Helper function to set form errors from server response
  const setFormErrors = (errors: Record<string, any>) => {
    Object.entries(errors).forEach(([fieldName, value]: [string, any]) => {
      if (fieldName === "state" || fieldName === "city") {
        methods.setError(`${fieldName}.value` as any, {
          type: "server",
          message: Array.isArray(value) ? value[0] : value,
        });
      } else {
        methods.setError(fieldName as any, {
          type: "server",
          message: Array.isArray(value) ? value[0] : value,
        });
      }
    });
  };

  //common payload for add address and edit address
  const createPayload = (data: AddressSchemaType) => {
    // Ensure address_type is always included and has a default value
    const payload = {
      short_address: data.short_address,
      building_name: data.building_name,
      street: data.street,
      secondary_number: data.secondary_number,
      district: data.district,
      address_line_1: data.address_line_1,
      address_line_2: data.address_line_2,
      city: typeof data.city === "object" ? data.city.value : data.city,
      state: typeof data.state === "object" ? data.state.value : data.state,
      country: process.env.NEXT_PUBLIC_COUNTRY_CODE || "231",
      postal_code: data.postal_code,
      alternate_country_code: addressCountryCode,
      alternate_address_contact_number: extractMobileNumber(
        data.phone || "",
        addressCountryCode
      ),
      // Ensure address_type is preserved, default to 'shipping' if not provided
      address_type: data.address_type || "shipping",
      isPrimary: data.isPrimary ?? false,
    };

    return payload;
  };

  // add address
  const handleAddAddress = async (data: AddressSchemaType) => {
    const payload = createPayload(data);
    setIsSubmittingAddress(true);
    try {
      const result = await storeAddressAction(payload, user.token, locale);
      if (result.success) {
        // Only add to local state if we have a real ID from the API
        if (result.data?.addressData?._id || result.data?.addressData?.id) {
          const newAddress = {
            _id: result.data.addressData._id || result.data.addressData.id,
            name: data.address_line_1 || "My Place",
            address: constructAddressString(data),
            phone: data.phone || `+${addressCountryCode}`,
            short_address: data.short_address,
            building_name: data.building_name,
            street: data.street,
            secondary_number: data.secondary_number,
            district: data.district,
            address_line_1: data.address_line_1,
            address_line_2: data.address_line_2,
            city: data.city,
            state: data.state,
            postal_code: data.postal_code,
            country: process.env.NEXT_PUBLIC_COUNTRY_CODE || "231",
            address_type: data.address_type,
            isPrimary: data.isPrimary ?? false,
            country_code: addressCountryCode,
            contact_number: extractMobileNumber(
              data.phone || "",
              addressCountryCode
            ),
          };

          dispatch(addLocalAddress(newAddress));
          reset();
          closeDrawer();
          toast.success(t("validation.address_added_successfully"));
        } else {
          // If no ID returned, refresh the addresses list to get the updated data
          toast.success(t("validation.address_added_successfully"));
          reset();
          closeDrawer();
          // Refresh addresses to get the newly added one with proper ID
          const refreshResult = await fetchAddressesAction(user.token, locale);
          if (refreshResult.success) {
            dispatch(clearAddresses());
            refreshResult.data.forEach((addr: any) =>
              dispatch(addLocalAddress(addr))
            );
          }
        }
      } else {
        const resultWithError = result as any;
        if (resultWithError.error) {
          setFormErrors(resultWithError.error);
        } else {
        }
      }
    } catch (error: any) {
      if (checkAuthErrorGet(error, dispatch, router)) return;

      // Handle validation errors from error response
      if (error?.response?.data?.error) {
        setFormErrors(error.response.data.error);
      }
    } finally {
      setIsSubmittingAddress(false);
    }
  };

  //  handleUpdateAddress function
  const handleUpdateAddress = async (data: AddressSchemaType) => {
    if (!editingAddress) return;

    const updateData = {
      ...data,
      address_type:
        data.address_type || editingAddress.address_type || "shipping",
    };

    const payload = createPayload(updateData);
    setIsSubmittingAddress(true);

    try {
      if (!editingAddress._id || editingAddress._id.startsWith("temp-")) {
        toast.error(
          t("cannot_edit_listing")
        );
        setIsSubmittingAddress(false);
        return;
      }

      const result = await updateAddressAction(
        editingAddress._id,
        payload,
        user.token,
        locale
      );

      if (result.success) {
        const updatedAddress = {
          ...editingAddress,
          ...payload,
          _id: editingAddress._id,
        };

        dispatch(updateLocalAddress(updatedAddress));
        toast.success(t("validation.address_updated_successfully"));
        closeDrawer();

        // Refresh the addresses to ensure we have the latest data
        const refreshResult = await fetchAddressesAction(user.token, locale);
        if (refreshResult.success) {
          dispatch(clearAddresses());
          refreshResult.data.forEach((addr: any) =>
            dispatch(addLocalAddress(addr))
          );
        }
      } else {
        const resultWithError = result as any;
        if (resultWithError.error) {
          setFormErrors(resultWithError.error);
        } else {
          toast.error(t("failed_to_update_address"));
        }
      }
    } catch (error: any) {
      if (checkAuthErrorGet(error, dispatch, router)) return;

      if (error?.response?.data?.error) {
        setFormErrors(error.response.data.error);
      } else {
        toast.error(t("an_error_occurred_while_updating_address"));
      }
    } finally {
      setIsSubmittingAddress(false);
    }
  };

  const onSubmit: SubmitHandler<AddressSchemaType> = async (data) => {
    // Always validate first before proceeding
    const isValid = await methods.trigger();

    if (!isValid) {
      return; // Don't proceed if validation fails
    }

    if (activeDrawer === "editaddress" && editingAddress) {
      await handleUpdateAddress(data);
    } else {
      await handleAddAddress(data);
    }
  };

  // Helper function to set phone number
  const setPhoneValue = (addr: any) => {
    if (addr.country_code && addr.contact_number) {
      setValue(
        "phone",
        `+${addr.country_code.replace(/^\+/, "")}${addr.contact_number}`
      );
    } else if (addr.phone) {
      setValue(
        "phone",
        addr.phone.startsWith("+") ? addr.phone : `+${addr.phone}`
      );
    } else {
      setValue("phone", "");
    }
  };

  // edit address
  const handleEditAddress = async (addr: any) => {
    if (!addr._id || addr._id.startsWith("temp-")) {
      toast.error(t("cannot_edit_with_temporary_account"));
      return;
    }

    setEditingAddress(addr);
    setActiveDrawer("editaddress");
    setAddressCountryCode(addr.country_code || "");

    // Reset the form with the address data
    methods.reset({
      ...addr,
      state: addr.state || { value: "", label: "" },
      city: addr.city || { value: "", label: "" },
      address_type: addr.address_type || "shipping",
      short_address: addr.short_address || "",
      building_name: addr.building_name || "",
      street: addr.street || "",
      secondary_number: addr.secondary_number || "",
      district: addr.district || "",
      address_line_1: addr.address_line_1 || "",
      address_line_2: addr.address_line_2 || "",
      postal_code: addr.postal_code || "",
      phone: addr.phone || "",
      isPrimary: addr.isPrimary || false,
    });

    setPhoneValue(addr);

    // Handle state - check multiple possible formats
    if (addr.state) {
      let foundState = null;

      // Try to find state by _id (the actual data structure)
      if (typeof addr.state === "object" && addr.state._id) {
        foundState = states.find((s) => s.value === String(addr.state._id));
      }

      // If not found by _id, try by name
      if (!foundState && typeof addr.state === "object" && addr.state.name) {
        foundState = states.find((s) => s.label === addr.state.name);
      }

      // Try to find state by value (ID) - fallback
      if (!foundState && typeof addr.state === "string") {
        foundState = states.find((s) => s.value === addr.state);
      }

      // If still not found, try by label - fallback
      if (!foundState && typeof addr.state === "string") {
        foundState = states.find((s) => s.label === addr.state);
      }

      if (foundState) {
        setSelectedState(foundState);
        setValue("state", foundState);

        // Fetch cities for this state
        await fetchAndSetCities(foundState.value, null);

        // Handle city population
        if (addr.city) {
          // Store the city ID to be populated once cities are loaded
          if (typeof addr.city === "object" && addr.city._id) {
            setPendingCityId(String(addr.city._id));
          } else if (typeof addr.city === "string") {
            setPendingCityId(addr.city);
          } else {
            resetCityField(); // Use helper instead of inline setValue
          }
        } else {
          resetCityField(); // Use helper instead of inline setValue
        }
      } else {
        setSelectedState(null);
        resetStateCityFields(); // Use helper instead of multiple setValue calls
      }
    } else {
      setSelectedState(null);
      resetStateCityFields(); // Use helper instead of multiple setValue calls
    }
  };

  // delete address
  const handleDeleteAddress = async () => {
    if (user?.token && addressToDelete?._id) {
      try {
        const result = await deleteAddressAction(
          addressToDelete._id,
          user.token,
          locale
        );

        if (result.success) {
          dispatch(deleteLocalAddress(addressToDelete._id));
          toast.success(t("validation.address_deleted_successfully"));
        } else {
          toast.error(result.message || t("validation.address_deleted_failed"));
        }
      } catch (error: any) {
        if (checkAuthErrorGet(error, dispatch, router)) return;
        toast.error(t("validation.address_deleted_failed"));
      }
    }
    setShowDeleteModal(false);
    setAddressToDelete(null);
  };

  useEffect(() => {
    if (pendingCityId && cities.length > 0) {
      let foundCity = cities.find((c) => c.value === String(pendingCityId));
      if (!foundCity) {
        foundCity = cities.find((c) => c.label === pendingCityId);
      }

      if (foundCity) {
        setValue("city", foundCity);
      } else {
        resetCityField();
      }
      setPendingCityId(null);
    }
  }, [pendingCityId, cities, setValue]);

  const { themeKey, isDarkMode, customStyles } = useSelectTheme();

  if (!user?.token) {
    const fakeAuthError = {
      response: {
        data: {
          statusCode: 401,
          statusText: "Unauthorized",
        },
      },
    };
    checkAuthErrorGet(fakeAuthError, dispatch, router);
    return null;
  }

  const handleBack = () => {
    window.history.back();
  };
  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Loader />
      </div>
    );
  }

  return (
    <RouteLoader>
      <MobilePageHeader
        title={t("my_address.title")}
        onBack={handleBack}
        rightContent={
          <button
            className="text-neutrals900 dark:text-white"
            onClick={() => {
              setActiveDrawer("addaddress");
              resetForm();
            }}
            disabled={isLoading}
          >
            <IoMdAddCircleOutline size={24} />
          </button>
        }
      />

      <main className="flex-1 max-md:px-0">
        <div className="flex items-center justify-between gap-2 pb-6 max-md:hidden">
          <h1 className="text-lg font-bold text-neutrals900 dark:text-white">
            {t("my_address.title")}
          </h1>
          <div className="flex gap-2">
            <AccountDropdown t={t} />
            <button
              onClick={() => {
                setActiveDrawer("addaddress");
                resetForm();
              }}
              disabled={isLoading}
              title="Add a new address"
              className="flex items-center text-primary500 border border-primary500 p-2 py-1.5 rounded-lg hover:bg-primary500 hover:text-white dark:text-primary400 dark:border-primary400 dark:hover:bg-primary400 dark:hover:text-white"
            >
              <IoMdAddCircleOutline size={20} />
            </button>
          </div>
        </div>

        {(addresses.length === 0 && !isLoading) && (
          <div className="text-center py-8">
            <DataNotFound />
          </div>
        )}

        <div className="grid grid-cols-2 gap-4 max-lg:grid-cols-1 gap-y-0 max-md:gap-y-2.5">
          {/* <Button
            label={t("my_address.button.add_address")}
            variant="secondary"
            icon={<LuCirclePlus size={20} />}
            onClick={() => {
              setActiveDrawer("addaddress");
              resetForm();
            }}
            className="mb-4 w-fit flex flex-row-reverse max-sm:w-full justify-center max-md:hidden"
            disabled={isLoading}
          /> */}

          {/* <p className="text-sm text-neutrals500 pt-1.5 mb-0.5 dark:text-neutrals400">
            {t("my_address.saved_address")}
          </p> */}

          {isLoading && (
            <div className="flex justify-center items-center py-8">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary500"></div>
            </div>
          )}
          {[...addresses]
            .sort((a, b) => {
              // Sort profile address to the top
              if (a.address_type === "profile") return -1;
              if (b.address_type === "profile") return 1;
              return 0;
            })

            .map((addr, index, arr) => {
              const addressNumber = arr
                .slice(0, index + 1)
                .filter((a) => a.address_type !== "profile").length;
              return { addr, addressNumber };
            })

            .map(({ addr, addressNumber }, index) => (
              <div className=" bg-white px-6 py-5 border border-neutrals100 rounded-md max-sm:p-2 dark:bg-darkbg dark:border-darkborder" key={
                addr._id ? `address-${addr._id}` : `address-fallback-${index}`
              }>
                <div

                  className={`border-b border-neutrals100 pb-4 flex items-start justify-between last-of-type:border-hidden dark:border-darkborder gap-1 ${selectedAddress === addr._id ? "" : ""
                    }`}
                >
                  <div>
                    <p className="text-sm font-medium text-neutrals800 mb-2.5 dark:text-neutrals300">
                      {addr.address_type === "profile"
                        ? t("my_address.profile_address")
                        : `${t("my_address.address")} ${addressNumber}`}
                    </p>
                    <div className="flex items-start gap-[15px]">
                      <div className="w-8 h-8 rounded bg-neutrals50 flex items-center justify-center dark:bg-background">
                        <IoLocationOutline
                          size={21}
                          className="text-primary500 dark:text-primary400"
                        />
                      </div>
                      <div className="w-[calc(100%-32px)]">
                        <p className="font-bold text-neutrals800 text-sm mb-0.5 dark:text-neutrals300">
                          {addr.name}
                        </p>
                        <p className="text-sm text-neutrals500 max-lg:text-xs dark:text-neutrals400">
                          {addr.address}
                        </p>
                        <p className="text-sm text-neutrals500 max-lg:text-xs dark:text-neutrals400">
                          {t("my_address.contact_number")}: {addr.phone}
                        </p>
                      </div>
                    </div>
                  </div>
                  <div className="h-full items-end justify-between flex flex-col min-h-24">
                    <div className="relative">
                      <label className="cursor-pointer">
                        <input
                          type="radio"
                          name="address"
                          value={addr._id}
                          checked={addr.isPrimary || selectedAddress === addr._id}
                          onChange={() =>
                            handleRadioChange(addr._id, addr.isPrimary ?? false)
                          }
                          className="peer hidden"
                        />
                        <div className="w-5 h-5 rounded-full border-2 border-neutrals200 peer-checked:border-primary500 peer-checked:bg-primary500 flex items-center justify-center dark:peer-checked:border-primary400 dark:peer-checked:bg-primary400">
                          <div className="w-2.5 h-2.5 rounded-full bg-white max-lg:w-2 max-lg:h-2" />
                        </div>
                      </label>
                    </div>
                    <div className="flex items-center gap-2.5">
                      <MdOutlineEdit
                        size={23}
                        className="text-neutrals500 cursor-pointer hover:text-primary500 dark:text-neutrals400 dark:hover:text-primary400"
                        onClick={() => handleEditAddress(addr)}
                      />
                      {addr.address_type !== "profile" && (
                        <MdOutlineDeleteOutline
                          size={24}
                          className="text-red-600 cursor-pointer hover:text-red-700"
                          onClick={() => {
                            setAddressToDelete(addr);
                            setShowDeleteModal(true);
                          }}
                        />
                      )}
                    </div>
                  </div>
                </div>
              </div>
            ))}
        </div>

      </main>
      <SideDrawer
        isOpen={activeDrawer === "addaddress" || activeDrawer === "editaddress"}
        title={
          activeDrawer === "editaddress"
            ? t("my_address.edit_address")
            : t("my_address.add_address")
        }
        onClose={() => {
          closeDrawer();
          reset();
        }}
        footer={
          <div className="flex justify-end gap-2">
            <Button
              label={t("my_address.button.cancel")}
              onClick={() => {
                closeDrawer();
                reset();
              }}
              variant="fadoutline"
            />
            <Button
              type="submit"
              label={
                isSubmittingAddress
                  ? t("button.saving")
                  : activeDrawer === "editaddress"
                    ? t("my_address.button.update")
                    : t("my_address.button.save")
              }
              variant="secondary"
              onClick={handleSubmit(onSubmit)}
              disabled={isLoading || isSubmittingAddress}
            >
              {isSubmittingAddress ? (
                <div role="status" className="flex items-center justify-center">
                  <svg
                    className="animate-spin -ml-1 mr-2 h-4 w-4 text-white"
                    xmlns="http://www.w3.org/2000/svg"
                    fill="none"
                    viewBox="0 0 24 24"
                  >
                    <circle
                      className="opacity-25"
                      cx="12"
                      cy="12"
                      r="10"
                      stroke="currentColor"
                      strokeWidth="4"
                    ></circle>
                    <path
                      className="opacity-75"
                      fill="currentColor"
                      d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                    ></path>
                  </svg>
                  <span className="sr-only">{t("button.loading")}</span>
                </div>
              ) : null}
            </Button>
          </div>
        }
      >
        <FormProvider {...methods}>
          <form onSubmit={handleSubmit(onSubmit)}>
            {isLoading && (
              <div className="absolute inset-0 bg-white bg-opacity-90 z-10 flex items-center justify-center">
                <div className="text-center">
                  <div role="status" className="mb-4">
                    <svg
                      aria-hidden="true"
                      className="w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary600 mx-auto"
                      viewBox="0 0 100 101"
                      fill="none"
                      xmlns="http://www.w3.org/2000/svg"
                    >
                      <path
                        d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
                        fill="currentColor"
                      />
                      <path
                        d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
                        fill="currentFill"
                      />
                    </svg>
                    <span className="sr-only">
                      {t("edit_profile_drawer.loading")}
                    </span>
                  </div>
                  <p className="text-gray-600 text-sm">
                    {t("edit_profile_drawer.loading_profile_data")}
                  </p>
                </div>
              </div>
            )}
            <div className="address-details space-y-5">
              <Input
                label={t("my_address.short_address")}
                name="short_address"
                placeholder={t("my_address.short_address_placeholder")}
                required
              />
              <Input
                label={t("my_address.building_name")}
                name="building_name"
                placeholder={t("my_address.building_name_placeholder")}
                required
              />
              <Input
                label={t("my_address.street")}
                name="street"
                placeholder={t("my_address.street_placeholder")}
                required
              />
              <Input
                label={`${t("my_address.secondary_number")}`}
                name="secondary_number"
                type="number"
                placeholder={`${t("my_address.secondary_number_placeholder")}`}
                required
              />
              <Input
                label={t("my_address.district")}
                name="district"
                placeholder={t("my_address.district_placeholder")}
                required
              />

              <div>
                <label
                  htmlFor="state"
                  className="block text-sm font-medium text-neutrals800 mb-1 dark:text-neutrals400"
                >
                  {t("my_address.state")}{" "}
                  <span className="text-sm text-red-500">*</span>
                </label>
                <Controller
                  name="state"
                  control={control}
                  render={({ field }) => (
                    <Select
                      {...field}
                      inputId="state"
                      options={states}
                      placeholder={t("my_address.select_state")}
                      className="react-select-container"
                      classNamePrefix="react-select"
                      styles={customStyles}
                      key={themeKey}
                      isLoading={isLoadingStates}
                      loadingMessage={() => t("common.loading")}
                      noOptionsMessage={() => t("common.no_options")}
                      value={
                        states.find(
                          (option) => option.value === field.value?.value
                        ) || null
                      }
                      onChange={handleStateChange}
                      isClearable
                    />
                  )}
                />
                {errors.state?.value && (
                  <span className="text-red-800 dark:text-red-500 text-sm">
                    {errors.state.value.message}
                  </span>
                )}
              </div>
              <div>
                <label
                  htmlFor="city"
                  className="block text-sm font-medium text-neutrals800 mb-1 dark:text-neutrals400"
                >
                  {t("my_address.city")}{" "}
                  <span className="text-sm text-red-500">*</span>
                </label>
                <Controller
                  name="city"
                  control={control}
                  render={({ field }) => (
                    <Select
                      {...field}
                      inputId="city"
                      options={cities}
                      placeholder={t("my_address.select_city")}
                      className="react-select-container"
                      classNamePrefix="react-select"
                      styles={customStyles}
                      key={themeKey}
                      isLoading={isLoadingCities}
                      loadingMessage={() => t("common.loading")}
                      noOptionsMessage={() => t("common.no_options")}
                      value={
                        cities.find(
                          (option) => option.value === field.value?.value
                        ) || null
                      }
                      onChange={handleCityChange}
                      isDisabled={!selectedState?.value || isLoadingCities}
                      isClearable
                    />
                  )}
                />
                {errors.city?.value && (
                  <span className="text-red-800 dark:text-red-500 text-sm">
                    {errors.city.value.message}
                  </span>
                )}
              </div>
              <div>
                <label className="block text-sm font-medium text-neutrals800 font-medium mb-1 dark:text-neutrals400">
                  {t("my_address.postal_code")}{" "}
                  <span className="text-sm text-red-500">*</span>
                </label>
                <Input
                  placeholder={t("my_address.postal_code_placeholder")}
                  type="number"
                  name="postal_code"
                  required
                />
              </div>
              <Input
                label={t("my_address.address_line_1")}
                name="address_line_1"
                placeholder={t("my_address.address_line_1_placeholder")}
                required
              />
              <Input
                label={t("my_address.address_line_2")}
                name="address_line_2"
                placeholder={t("my_address.address_line_2_placeholder")}
              />
              <Input
                label={t("my_address.contact_number")}
                type="country_code_phone"
                name="phone"
                placeholder={t("my_address.contact_number_placeholder")}
                setCountryCode={setAddressCountryCode}
                required
              />
            </div>
          </form>
        </FormProvider>
      </SideDrawer>

      {showDeleteModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-40">
          <div className="bg-white rounded-lg shadow-lg p-6 w-full max-w-xs">
            <h2 className="text-lg font-semibold mb-4">
              {t("my_address.confirm_deletion")}
            </h2>
            <p className="mb-6">{t("my_address.confirm_deletion_message")}</p>
            <div className="flex justify-end gap-2">
              <button
                className="px-4 py-2 rounded bg-gray-200 hover:bg-gray-300 text-gray-800"
                onClick={() => {
                  setShowDeleteModal(false);
                  setAddressToDelete(null);
                }}
              >
                {t("my_address.button.cancel")}
              </button>

              <button
                className="px-4 py-2 rounded bg-red-600 hover:bg-red-700 text-white"
                onClick={handleDeleteAddress}
              >
                {t("my_address.button.delete")}
              </button>
            </div>
          </div>
        </div>
      )}

      {addressToMakePrimary && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-neutrals800 rounded-lg p-6 max-w-md w-full">
            <h3 className="text-lg font-medium text-neutrals900 dark:text-white mb-4">
              {t("my_address.confirm_primary_title")}
            </h3>
            <p className="text-neutrals600 dark:text-neutrals300 mb-6">
              {t("my_address.confirm_primary_message")}
            </p>
            <div className="flex justify-end space-x-3">
              <button
                onClick={() => setAddressToMakePrimary(null)}
                disabled={isSettingPrimary}
                className="px-4 py-2 text-sm font-medium text-neutrals700 dark:text-neutrals300 bg-neutrals100 dark:bg-neutrals700 rounded-md hover:bg-neutrals200 dark:hover:bg-neutrals600 transition-colors"
              >
                {t("my_address.button.cancel")}
              </button>
              <button
                onClick={handleSetPrimaryAddress}
                disabled={isSettingPrimary}
                className="px-4 py-2 text-sm font-medium text-white bg-primary500 dark:bg-primary400 rounded-md hover:bg-primary600 dark:hover:bg-primary300 transition-colors disabled:opacity-50 flex items-center"
              >
                {isSettingPrimary ? (
                  <>
                    <svg
                      className="animate-spin -ml-1 mr-2 h-4 w-4 text-white"
                      xmlns="http://www.w3.org/2000/svg"
                      fill="none"
                      viewBox="0 0 24 24"
                    >
                      <circle
                        className="opacity-25"
                        cx="12"
                        cy="12"
                        r="10"
                        stroke="currentColor"
                        strokeWidth="4"
                      ></circle>
                      <path
                        className="opacity-75"
                        fill="currentColor"
                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                      ></path>
                    </svg>
                    {t("button.processing")}
                  </>
                ) : (
                  t("my_address.button.confirm")
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </RouteLoader>
  );
}
