"use client";
import { useForm, FormProvider } from "react-hook-form";
import { useMemo } from "react";
import CustomerAddressPhone from "./CustomerAddressPhone";
import Select from "@/components/theme/ui/Select";
import { clientFetch } from "@/lib/restApiClient";
import { useRouter } from "next/navigation";
// 定义表单类型（严格对齐你要的字段）
interface AddressFormData {
  first_name: string;
  last_name: string;
  email: string;
  phone: string;
  address: string[];
  country: string;
  state: string;
  city: string;
  postcode: string;
  default_address: number;
}

export default function NewAddressDefault({ countries }: { countries: any[] }) {
  // 国家选项
  const countriesOptions = useMemo(() => {
    return countries.map((country) => ({
      value: country.code,
      label: country.name,
      id: String(country.id),
    }));
  }, [countries]);
   const router = useRouter();
  // 提交地址到接口
  const AddAdress = async (formData: AddressFormData) => {
    const res = await clientFetch("/api/customer/token/address", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(formData),
    });
    const json = await res;
    console.log("提交成功，返回结果：", json);
    if(json?.status== 201){
        router.push("/customer/address/");
    }else{
      alert("error");
    }
    return json;
  };

  // 表单提交
  const addressFormOnSubmit = async (formData: AddressFormData) => {
    console.log("最终提交给后端的数据：", formData);
    await AddAdress(formData);
  };

  // 表单实例（严格对齐你需要的字段）
  const addressForm = useForm<AddressFormData>({
    mode: "onBlur",
    reValidateMode: "onChange",
    defaultValues: {
      first_name: "",
      last_name: "",
      email: "",
      phone: "",
      address: ["", ""], // 数组格式
      country: "",
      state: "",
      city: "",
      postcode: "",
      default_address: 0,
    },
  });

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = addressForm;
  return (
    <div className="w-full h-full">
      <FormProvider {...addressForm}>
        <form
          className="overflow-hidden"
          onSubmit={handleSubmit(addressFormOnSubmit)}
        >
          {/* 头部 */}
          <div className="bg-[#fff] px-2.5 w-full text-center text-base h-11 leading-11 font-semibold relative text-[#0b0b0b]">
            <div
              onClick={() => window.history.back()}
              className="absolute left-2.5 text-2xl inline-block top-1/2 -translate-y-1/2"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
              >
                <path
                  stroke="rgba(0, 0, 0, 1)"
                  strokeWidth="1.2"
                  strokeLinejoin="round"
                  strokeLinecap="round"
                  d="M15 18L9 12L15 6"
                ></path>
              </svg>
            </div>
            <span>Add New Address</span>
          </div>

          <div className="bg-[#f8f8f8] p-[20px_10px]">
            {/* 姓名 */}
             <div className="text-start">*Name</div>
            <div className="flex justify-between items-center gap-3">
              {/* firstname */}
              <input
                type="text"
                placeholder="firstname"
                {...register("first_name", {
                  required: "First name is required",
                })}
                className="w-43 h-11 rounded-sm border border-solid border-[rgba(102,102,102,1)] indent-4 text-[#a6a6a6] text-base leading-11 font-normal"
              />
              {/* lastname */}
              <input
                type="text"
                placeholder="last_name"
                {...register("last_name", {
                  required: "Last name is required",
                })}
                className="w-43 h-11 rounded-sm border border-solid border-[rgba(102,102,102,1)] indent-4 text-[#a6a6a6] text-base leading-11 font-normal box-[unset]"
              />
            </div>
            {errors.first_name && <p className="text-red-500 text-sm mt-1">{errors.first_name.message}</p>}
            {errors.last_name && <p className="text-red-500 text-sm mt-1">{errors.last_name.message}</p>}

            {/* 手机号 */}
            <CustomerAddressPhone />

            {/* 国家 */}
            <div className="mt-4">
              <Select
                placeholder="Country/Region"
                {...register("country", { required: "Country is required" })}
                options={countriesOptions}
                error={errors.country?.message as string}
              />
            </div>

            {/* 邮箱 */}
            <div className="mt-4">
              <label>Email Address*</label>
              <input
                type="email"
                placeholder="Email"
                {...register("email", {
                  required: "Email is required",
                  pattern: { value: /^\S+@\S+\.\S+$/, message: "Invalid email" },
                })}
                className="w-full h-11 rounded-sm border border-[rgba(102,102,102,1)] indent-4 text-base mt-1"
              />
              {errors.email && <p className="text-red-500 text-sm mt-1">{errors.email.message}</p>}
            </div>

            {/* 邮编 */}
            <div className="mt-4">
              <label>Zip/Postal Code</label>
              <input
                type="text"
                placeholder="Postcode"
                {...register("postcode")}
                className="w-full h-11 rounded-sm border border-[rgba(102,102,102,1)] indent-4 text-base mt-1"
              />
            </div>

            {/* 省/州 */}
            <div className="mt-4">
              <label>State / Province</label>
              <input
                type="text"
                placeholder="State"
                {...register("state")}
                className="w-full h-11 rounded-sm border border-[rgba(102,102,102,1)] indent-4 text-base mt-1"
              />
            </div>

            {/* 城市 */}
            <div className="mt-4">
              <label>City</label>
              <input
                type="text"
                placeholder="City"
                {...register("city")}
                className="w-full h-11 rounded-sm border border-[rgba(102,102,102,1)] indent-4 text-base mt-1"
              />
            </div>

            {/* 默认地址 */}
            <label className="flex items-center gap-2 cursor-pointer mt-4">
              <input
                type="checkbox"
                {...register("default_address", { valueAsNumber: true })}
                className="w-5 h-5"
              />
              <span>Use as my default address</span>
            </label>

            {/* 提交按钮 */}
            <button
              className="w-full h-11 leading-11 bg-[#1bbc9b] text-white text-center mt-6 rounded"
              type="submit"
            >
              Save Address
            </button>
          </div>
        </form>
      </FormProvider>
    </div>
  );
}