"use client";

/** مدیریت آدرس‌ها */
import { useState } from "react";
import { addresses, useAddresses, type SavedAddress } from "@/lib/client/store";
import { faDigits } from "@/lib/format";
import { Icon } from "@/components/ui/Icon";
import { AddressForm } from "./AddressForm";

export function AddressBook() {
  const list = useAddresses();
  const [editing, setEditing] = useState<SavedAddress | "new" | null>(null);

  if (editing) {
    return (
      <AddressForm
        initial={editing === "new" ? undefined : editing}
        onSave={async (a) => {
          const res = await addresses.save(a);
          if (res.errors) return res;
          setEditing(null);
        }}
        onCancel={() => setEditing(null)}
      />
    );
  }

  return (
    <div className="space-y-3">
      {list.length === 0 && <p className="card-surface p-6 text-center text-sm text-muted">هنوز آدرسی ثبت نکرده‌اید.</p>}
      {list.map((a) => (
        <div key={a.id} className="rounded-2xl border border-line p-4 text-sm">
          <p className="font-bold">{a.title} · {a.receiver}</p>
          <p className="mt-1 text-xs leading-6 text-muted">
            {a.province}، {a.city}، {a.line}
            <br />
            کد پستی {faDigits(a.postalCode)} · موبایل <bdi>{faDigits(a.phone)}</bdi>
          </p>
          <div className="mt-3 flex gap-4 text-xs">
            <button className="flex items-center gap-1 underline" onClick={() => setEditing(a)}><Icon name="edit" size={14} />ویرایش</button>
            <button className="flex items-center gap-1 underline" onClick={() => confirm("این آدرس حذف شود؟") && void addresses.remove(a.id)}><Icon name="trash" size={14} />حذف</button>
          </div>
        </div>
      ))}
      <button className="btn-outline w-full" onClick={() => setEditing("new")}>
        <Icon name="plus" size={18} /> افزودن آدرس جدید
      </button>
    </div>
  );
}
