"use client";
import { useState, useEffect } from "react";
import { clientFetch } from "@/lib/restApiClient";
import Link from "next/link";
export default function DefaultAddress() {
  const [addressDatas, setAddressDatas] = useState<any[]>([]); // 加 any[] 提示

  useEffect(() => {
    const load = async () => {
      // const page = 1;
      const resp = await clientFetch(
        `/api/customer/token/address`, ///api/shop/customer-addresses?page=${page}
      );
      console.log("完整返回：", resp.data);
      resp.data.data= Array.isArray(resp.data.data) ? resp.data.data : [];
      const sortedList = [...resp.data.data].sort((a, b) => {
        // true(1) 排在 false(0) 前面
        if (a.default_address !== b.default_address) {
          return b.default_address ? 1 : -1;
        }
        // 相同状态，保留原顺序（返回0即可）
        return 0;
      });
      setAddressDatas(sortedList);
      console.log("aaaa",sortedList,addressDatas);
      
    };
    load();
  }, []);
  return (
    <>
      {(addressDatas || []).map((item) => (
        <div key={item.id} className="mb-6">
          {item.default_address ? (
            <h2 className="text-xl font-bold uppercase mb-3">
              Default Billing Address
            </h2>
          ) : null}
          <div className="border border-gray-200 p-4">
            <p className="mb-1">{item.first_name + item.last_name}</p>
            <p className="mb-1">{item.address}</p>
            <p className="mb-1">{item.city + "," + item.postcode}</p>
            <p className="mb-1">{item.country}</p>
            <p className="mb-4">T: {item.phone}</p>
            <div className="text-right">
              <Link
                href={`/customer/address/eidt/${item.id}`}
                className="text-blue-600 underline hover:text-blue-800"
              >
                Change Billing Address
              </Link>
            </div>
          </div>
        </div>
      ))}
    </>
  );
}
