"use client";
import {
  formatFinalPhoneValue,
  getPhoneCodeBycountryCode,
} from "@/components/theme/ui/PhoneNumberInput/phoneCodeMetaData";

import {  useEffect, useState } from "react";
// import { useQuery } from "@apollo/client/react";
import { useFormContext, Controller, useWatch } from "react-hook-form";
import { IS_VALID_FULL_PHONE, IS_VALID_PHONECODE } from "@utils/constants";
// import { GET_COUNTRY_STATES } from "@/graphql";
import PhoneNumberInput from "@/components/theme/ui/PhoneNumberInput/PhoneNumberInput";

export default function CustomerAddressPhone() {
  const {
    getValues,
    setValue,
    formState: {  },
    control,
  } = useFormContext();

  // 🔴 修复1：监听父表单的 country 字段（原 shippingCountry 是错误字段）
  const selectedCountryCode = useWatch({
    control,
    name: "country",
  });

  // 是否用户手动选择过区号
  const [hasUserSelectedPhoneCode, setHasUserSelectedPhoneCode] =
    useState(false);

  // 国家切换 → 自动同步电话区号（兼容 reset 回填）
  useEffect(() => {
    const currentPhone = getValues("phone");
    const regPhoneCode = IS_VALID_PHONECODE;

    if (currentPhone && !hasUserSelectedPhoneCode) {
      const newPhoneCode = getPhoneCodeBycountryCode(selectedCountryCode);
      const codeMatch = regPhoneCode.exec(currentPhone);
      let purePhone = currentPhone;

      // 剥离已有区号
      if (codeMatch) {
        purePhone = currentPhone.replace(codeMatch[0], "");
      }

      // 新区号和原有区号不一致才更新
      if (codeMatch && newPhoneCode !== codeMatch[0].trim()) {
        setValue("phone", formatFinalPhoneValue(newPhoneCode, purePhone));
      }
    }
  }, [selectedCountryCode, hasUserSelectedPhoneCode, getValues, setValue]);

  // const { data: statesData, loading: statesLoading } = useQuery(
  //   GET_COUNTRY_STATES,
  //   {
  //     variables: {},
  //     skip: !selectedCountryCode,
  //   },
  // );

  return (
    <div className="w-full mt-4">
      <label className="text-ly-12 block mb-4 font-semibold">
        Phone number *
      </label>
      {/* ✅ Controller 本身写法没问题，保留即可，字段 name="phone" 和父表单一致 */}
      <Controller
        name="phone"
        control={control}
        rules={{
          required: "Phone Number is required",
          pattern: {
            value: IS_VALID_FULL_PHONE,
            message: "Invalid Phone Number",
          },
        }}
        render={({ field, fieldState }) => {
          return (
            <PhoneNumberInput
              placeholder="Please Input Your Phone Number"
              value={field.value}
              onChange={field.onChange}
              onBlur={field.onBlur}
              name={field.name}
              ref={field.ref}
              error={fieldState.error?.message}
              countryCode={selectedCountryCode}
              hasUserSelectedPhoneCode={hasUserSelectedPhoneCode}
              onHasUserSelectedPhoneCode={() =>
                setHasUserSelectedPhoneCode(true)
              }
            />
          );
        }}
      />
    </div>
  );
}