"use client";

import { useState, useEffect } from "react";
import { useForm, FormProvider, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { toast } from "react-toastify";
import { profileSchema, ProfileSchemaType } from "@/lib/validations/authSchema";
import axios from "axios";
import Select from "react-select";
import { useTranslations } from "next-intl";
import { getStoredLocale } from "@/lib/getLocale";
import SideDrawer from "@/components/common/SideDrawer";
import Button from "@/components/common/Button";
import Input from "@/components/common/CustomInputField";
import { useRouter } from "next/navigation";
import { useAppSelector, useAppDispatch } from "@/app/store/hooks";
import { checkAuthErrorGet } from "@/lib/checkAuthError";
import { useStateCityForm } from "@/lib/hooks/useStateCityForm";
import { useSelectTheme } from "@/hooks/useSelectTheme";
import SecureAddressAutocomplete from "@/components/SecureAddressAutocomplete";
interface EditProfileDrawerProps {
  isOpen: boolean;
  onClose: () => void;
  fetchUserProfile?: () => Promise<void>;
  populateForm?: () => any;
}

export default function EditProfileDrawer({
  isOpen,
  onClose,
  fetchUserProfile,
  populateForm,
}: EditProfileDrawerProps) {
  const { user } = useAppSelector((state) => state?.auth);
  const locale = getStoredLocale();
  const t = useTranslations();
  const dispatch = useAppDispatch();
  const router = useRouter();

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [countryCode, setCountryCode] = useState("");
  const [addressCountryCode, setAddressCountryCode] = useState("");
  const [profileCanUpdate, setProfileCanUpdate] = useState(true);

  const methods = useForm<ProfileSchemaType>({
    resolver: zodResolver(profileSchema(t)),
    mode: "onChange",
  });

  const {
    handleSubmit,
    control,
    setValue,
    reset,
    formState: { errors },
  } = methods;

  const {
    states,
    cities,
    isLoadingStates,
    isLoadingCities,
    selectedState,
    setSelectedState,
    handleStateChange,
    handleCityChange,
    fetchAndSetCities,
    resetStateCityFields,
  } = useStateCityForm({
    userToken: user?.token ?? "",
    setValue,
    dispatch,
    router,
  });

  function extractMobileNumber(
    fullNumber: string,
    countryCode: string
  ): string {
    const cleanNumber = fullNumber.replace(/^\+/, "");
    const cleanCode = countryCode.replace(/^\+/, "");
    const regex = new RegExp(`^${cleanCode}`);
    return cleanNumber.replace(regex, "");
  }

  useEffect(() => {
    if (!isOpen) {
      reset();
      resetStateCityFields();
      setIsLoading(true);
      setProfileCanUpdate(true);
      return;
    }

    setIsLoading(true);

    if (!populateForm) {
      setIsLoading(false);
      return;
    }

    const formData = populateForm();
    if (!formData) {
      setIsLoading(false);
      return;
    }
    setValue("longitude", formData.longitude);
    setValue("latitude", formData.latitude);
    setValue("first_name", formData.first_name);
    setValue("last_name", formData.last_name);
    setValue("username", formData.username);
    setValue("email", formData.email);
    setValue("phone", formData.phone);
    setValue("short_address", formData.short_address);
    setValue("building_name", formData.building_name);
    setValue("street", formData.street);
    setValue("secondary_number", formData.secondary_number);
    setValue("district", formData.district);
    setValue("address_line_1", formData.address_line_1);
    setValue("address_line_2", formData.address_line_2);
    setValue("postal_code", formData.postal_code);
    setValue("address_phone", formData.address_phone);

    if (formData.profileCanUpdate !== undefined) {
      setProfileCanUpdate(formData.profileCanUpdate);
    } else {
      setProfileCanUpdate(true);
    }

    if (formData.state && formData.state.value) {
      setSelectedState(formData.state);
      setValue("state", formData.state);
      fetchAndSetCities(formData.state.value, formData.city).then(() => {
        setIsLoading(false);
      });
    } else {
      setSelectedState(null);
      setValue("state", { value: "", label: "" });
      setValue("city", { value: "", label: "" });
      setIsLoading(false);
    }
  }, [isOpen]);

  const payload = (data: ProfileSchemaType, isUpdate = false) => {
    const phone_number = extractMobileNumber(data.phone || "", countryCode);

    const requestData: any = {
      ...data,
      phone_number,
      country_code: countryCode,
      alternate_country_code: addressCountryCode,
      alternate_address_contact_number: extractMobileNumber(
        data.address_phone || "",
        addressCountryCode
      ),
      short_address: data.short_address,
      building_name: data.building_name,
      street: data.street,
      secondary_number: data.secondary_number,
      district: data.district,
      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",
      longitude: data.longitude,
      latitude: data.latitude,
    };

    delete requestData.phone;
    delete requestData.address_phone;

    if (isUpdate) requestData._method = "PUT";

    return requestData;
  };

  const onSubmit: any = async (data: ProfileSchemaType) => {
    setIsSubmitting(true);
    try {
      const response = await axios.post(
        `${process.env.NEXT_PUBLIC_API_URL}/profile`,
        payload(data, true),
        {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${user?.token}`,
            "Accept-Language": locale,
          },
        }
      );
      toast.success(t("validation.profile_update_success"));

      if (fetchUserProfile) {
        await fetchUserProfile();
      }
      onClose();
    } catch (error: any) {
      if (checkAuthErrorGet(error, dispatch, router)) return;

      if (error.response?.data?.error) {
        const serverErrors = error.response.data.error;
        Object.entries(serverErrors).forEach(([key, value]: [string, any]) => {
          let formField = key;
          if (key === "phone_number") formField = "phone";
          if (key === "alternate_address_contact_number")
            formField = "address_phone";
          methods.setError(formField as keyof ProfileSchemaType, {
            type: "server",
            message: Array.isArray(value) ? value[0] : value,
          });
        });
      } else {
        toast.error(
          error?.response?.data?.message ||
          t("validation.error_updating_profile")
        );
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  const { themeKey, isDarkMode, customStyles } = useSelectTheme();

  // end

  // Handle authentication check in useEffect instead of during render
  useEffect(() => {
    if (!user?.token) {
      const fakeAuthError = {
        response: {
          data: {
            statusCode: 401,
            statusText: "Unauthorized",
          },
        },
      };
      checkAuthErrorGet(fakeAuthError, dispatch, router);
    }
  }, [user?.token, dispatch, router]);
  //autofill form address fields from google address data
  const handleAddressAutofill = (addressData: any) => {
    if (!addressData) return;
    // Map Google address data to your form fields
    if (addressData.street_number) {
      setValue("secondary_number", addressData.street_number);
    }
    if (addressData.street) {
      setValue("street", addressData.street);
    }
    if (addressData.city) {
      // You might need to match the city with your cities dropdown
      setValue("district", addressData.city);
    }
    if (addressData.postal_code) {
      setValue("postal_code", addressData.postal_code);
    }
    if (addressData.latitude) {
      setValue("latitude", addressData.latitude);
    }
    if (addressData.longitude) {
      setValue("longitude", addressData.longitude);
    }

    // Optionally set address_line_1 with full formatted address
    const fullAddress = [
      addressData.house_number,
      addressData.street,
      addressData.district,
      addressData.state,
      addressData.country,
      addressData.postal_code,
    ].filter(Boolean).join(", ");

    if (fullAddress) {
      setValue("address_line_1", fullAddress);
    }
  };
  if (!user?.token) {
    return null;
  }

  return (
    <>
      <SideDrawer
        isOpen={isOpen}
        title={t("edit_profile_drawer.title")}
        onClose={() => {
          onClose();
          reset();
          setProfileCanUpdate(true);
        }}
        footer={
          <div className="flex justify-end gap-2">
            <Button
              label={t("edit_profile_drawer.button.cancel")}
              onClick={() => {
                onClose();
                reset();
                setProfileCanUpdate(true);
              }}
              variant="outline"
              disabled={isLoading}
            />
            <Button
              type="submit"
              label={isSubmitting ? t("button.updating") : t("update")}
              variant="secondary"
              onClick={handleSubmit(onSubmit)}
              disabled={isSubmitting || isLoading}
            >
              {isSubmitting ? (
                <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>
        }
      >
        <p className="text-neutrals600 text-sm mb-5 dark:text-neutrals400">
          {t("edit_profile_drawer.description")}
        </p>
        <FormProvider {...methods}>
          <form
            onSubmit={handleSubmit(onSubmit)}
            className="space-y-4 relative"
          >
            {isLoading ? (
              <>
                {[
                  { title: "contact_details", fields: 4, layout: "mixed" },
                  { title: "address_details", fields: 8, layout: "single" },
                ].map((section, idx) => (
                  <div key={idx}>
                    <div className="label-box bg-neutrals100 p-3.5 text-base text-primary500 font-medium dark:bg-darkbg dark:text-primary400">
                      {t(`edit_profile_drawer.${section.title}`)}
                    </div>
                    <div className="pl-2.5 pt-3.5 space-y-5">
                      {section.layout === "mixed" ? (
                        <>
                          <div className="flex gap-4 max-sm:flex-col">
                            <div className="flex-1">
                              <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded mb-2 w-20 animate-pulse"></div>
                              <div className="h-12 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
                            </div>
                            <div className="flex-1">
                              <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded mb-2 w-20 animate-pulse"></div>
                              <div className="h-12 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
                            </div>
                          </div>
                          {Array.from({ length: section.fields - 2 }).map(
                            (_, fieldIdx) => (
                              <div key={fieldIdx + 2}>
                                <div
                                  className={`h-4 bg-gray-200 dark:bg-gray-700 rounded mb-2 animate-pulse ${fieldIdx === 0 ? "w-32" : "w-24"
                                    }`}
                                ></div>
                                <div className="h-12 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
                              </div>
                            )
                          )}
                        </>
                      ) : (
                        Array.from({ length: section.fields }).map(
                          (_, fieldIdx) => (
                            <div key={fieldIdx}>
                              <div
                                className={`h-4 bg-gray-200 dark:bg-gray-700 rounded mb-2 animate-pulse ${fieldIdx === 0
                                  ? "w-24"
                                  : fieldIdx === 1
                                    ? "w-28"
                                    : fieldIdx === 2
                                      ? "w-16"
                                      : "w-24"
                                  }`}
                              ></div>
                              <div className="h-12 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
                            </div>
                          )
                        )
                      )}
                    </div>
                  </div>
                ))}
              </>
            ) : (
              // Actual Form Content
              <>
                <div className="label-box bg-neutrals100 p-3.5 text-base text-primary500 font-medium dark:bg-darkbg dark:text-primary400">
                  {t("edit_profile_drawer.contact_details")}
                </div>
                <div className="contact-details pl-2.5 space-y-5">
                  <div className="flex gap-4 max-sm:flex-col">
                    <Input
                      label={t("edit_profile_drawer.first_name")}
                      name="first_name"
                      placeholder={t(
                        "edit_profile_drawer.first_name_placeholder"
                      )}
                      required
                      className="flex-1"
                    />
                    <Input
                      label={t("edit_profile_drawer.last_name")}
                      name="last_name"
                      placeholder={t(
                        "edit_profile_drawer.last_name_placeholder"
                      )}
                      required
                      className="flex-1"
                    />
                  </div>
                  <div>
                    <div className="flex items-center gap-2 mb-1">
                      <label
                        htmlFor="username"
                        className="block text-sm font-medium text-neutrals800 dark:text-neutrals400"
                      >
                        {t("edit_profile_drawer.username")}{" "}
                        <span className="text-sm text-red-500">*</span>
                      </label>
                      <span className="text-xs text-gray-500 dark:text-gray-400">
                        [{t("edit_profile_drawer.username_update_disabled")}]
                      </span>
                    </div>
                    <Input
                      name="username"
                      placeholder={t(
                        "edit_profile_drawer.username_placeholder"
                      )}
                      disabled={!profileCanUpdate}
                      required
                    />
                  </div>
                  <Input
                    label={t("edit_profile_drawer.email")}
                    name="email"
                    placeholder={t("edit_profile_drawer.email_placeholder")}
                    type="email"
                    disabled={true}
                    required
                  />
                  <Controller
                    name="phone"
                    control={control}
                    render={({ field }) => (
                      <Input
                        label={t("edit_profile_drawer.contact")}
                        type="country_code_phone"
                        {...field}
                        placeholder={t(
                          "edit_profile_drawer.contact_placeholder"
                        )}
                        setCountryCode={setCountryCode}
                        required
                      />
                    )}
                  />
                </div>

                <div className="label-box bg-neutrals100 p-3.5 text-base text-primary500 font-medium mb-5 dark:bg-darkbg dark:text-primary400">
                  {t("edit_profile_drawer.address_details")}
                </div>
                <div className="address-details pl-2.5 space-y-5">
                  <div className="bg-blue-50 dark:bg-blue-900/20 p-4 rounded-lg border border-blue-200 dark:border-blue-800">
                    <label className="block text-sm font-semibold mb-2 text-gray-900 dark:text-white">
                      🔍 {t("search_address")}
                    </label>

                    <SecureAddressAutocomplete
                      label={t("search_address")}
                      placeholder={t("start_type_address")}
                      onChange={handleAddressAutofill}
                    />

                  </div>
                  <div className="flex gap-4 max-sm:flex-col">
                    <Input
                      label={t("latitude")}
                      name="latitude"
                      placeholder={t("latitude_auto_placeholder")}
                      className="flex-1"
                      disabled
                      required
                    />
                    <Input
                      label={t("longitude")}
                      name="longitude"
                      placeholder={t("longitude_auto_placeholder")}
                      className="flex-1"
                      disabled
                      required
                    />
                  </div>
                  <Input
                    label={t("edit_profile_drawer.short_address")}
                    name="short_address"
                    placeholder={t(
                      "edit_profile_drawer.short_address_placeholder"
                    )}
                    required
                  />
                  <Input
                    label={t("edit_profile_drawer.building_name")}
                    name="building_name"
                    placeholder={t(
                      "edit_profile_drawer.building_name_placeholder"
                    )}
                    required
                  />
                  <Input
                    label={t("edit_profile_drawer.street")}
                    name="street"
                    placeholder={t("edit_profile_drawer.street_placeholder")}
                    required
                  />
                  <Input
                    label={t("edit_profile_drawer.secondary_number")}
                    name="secondary_number"
                    placeholder={t(
                      "edit_profile_drawer.secondary_number_placeholder"
                    )}
                    required
                  />
                  <Input
                    label={t("edit_profile_drawer.district")}
                    name="district"
                    placeholder={t("edit_profile_drawer.district_placeholder")}
                    required
                  />
                  <div>
                    <label
                      htmlFor="state"
                      className="block text-sm font-medium text-neutrals800 mb-1 dark:text-neutrals400"
                    >
                      {t("edit_profile_drawer.state")}{" "}
                      <span className="text-sm text-red-500">*</span>
                    </label>
                    <Controller
                      name="state"
                      control={control}
                      render={({ field }) => (
                        <Select
                          {...field}
                          inputId="state"
                          options={states}
                          isLoading={isLoadingStates}
                          loadingMessage={() => t("common.loading")}
                          noOptionsMessage={() => t("common.no_options")}
                          placeholder={t("edit_profile_drawer.select_state")}
                          styles={customStyles}
                          key={themeKey}
                          className="react-select-container"
                          classNamePrefix="react-select"
                          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("edit_profile_drawer.city")}{" "}
                      <span className="text-sm text-red-500">*</span>
                    </label>
                    <Controller
                      name="city"
                      control={control}
                      render={({ field }) => (
                        <Select
                          {...field}
                          inputId="city"
                          options={cities}
                          isDisabled={!selectedState?.value || isLoadingCities}
                          isLoading={isLoadingCities}
                          loadingMessage={() => t("common.loading")}
                          noOptionsMessage={() => t("common.no_options")}
                          placeholder={
                            selectedState?.value
                              ? t("edit_profile_drawer.select_city")
                              : t("edit_profile_drawer.select_state_first")
                          }
                          styles={customStyles}
                          key={themeKey}
                          className="react-select-container"
                          classNamePrefix="react-select"
                          value={
                            cities.find(
                              (option) => option.value === field.value?.value
                            ) || null
                          }
                          onChange={handleCityChange}
                          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 text-neutrals800 font-medium mb-1 dark:text-neutrals400">
                      {t("edit_profile_drawer.postal_code")}{" "}
                      <span className="text-sm text-red-500">*</span>
                    </label>
                    <Input
                      name="postal_code"
                      placeholder={t(
                        "edit_profile_drawer.postal_code_placeholder"
                      )}
                      type="number"
                      required
                    />
                  </div>
                  <Input
                    label={t("edit_profile_drawer.address_line_1")}
                    name="address_line_1"
                    placeholder={t(
                      "edit_profile_drawer.address_line_1_placeholder"
                    )}
                    required
                  />
                  <Input
                    label={t("edit_profile_drawer.address_line_2")}
                    name="address_line_2"
                    placeholder={t(
                      "edit_profile_drawer.address_line_2_placeholder"
                    )}
                  />

                  <Controller
                    name="address_phone"
                    control={control}
                    render={({ field }) => (
                      <Input
                        label={t("edit_profile_drawer.contact")}
                        type="country_code_phone"
                        {...field}
                        placeholder={t(
                          "edit_profile_drawer.contact_placeholder"
                        )}
                        setCountryCode={setAddressCountryCode}
                        required
                      />
                    )}
                  />
                </div>
              </>
            )}
          </form>
        </FormProvider>
      </SideDrawer>
    </>
  );
}
