"use client";

import Link from "next/link";
import { useState } from "react";
import { authHref } from "@/lib/account";
import type { CheckoutDetails } from "@/lib/commerce";
import { useAccount } from "./account-store";
import { useDemoStore } from "@/components/shop/demo-store";

export function CheckoutAddresses({ onApplied }: { onApplied: (fields: (keyof CheckoutDetails)[]) => void }) {
  const { profile, ready } = useAccount();
  const { updateCheckoutDraft, setDeliveryZone } = useDemoStore();
  const [message, setMessage] = useState("");
  if (!ready) return null;
  if (!profile) return <p className="checkout-account-prompt"><Link href={authHref("login", "/checkout")}>Sign in</Link> for saved addresses, or continue as a guest.</p>;
  function useAddress(id: string) {
    const address = profile?.addresses.find((item) => item.id === id);
    if (address) { const { id: _id, label: _label, ...details } = address; setDeliveryZone(address.deliveryZone); updateCheckoutDraft({ ...details, notes: "", payment: "cod" }); onApplied(["name", "phone", "email", "address", "district", "area", "deliveryZone", "notes", "payment"]); setMessage(`${address.label} address applied. You can edit the details below.`); }
  }
  return <div className="checkout-saved-addresses"><p>Shopping as <strong>{profile.name}</strong></p><button type="button" className="text-link" onClick={() => { updateCheckoutDraft({ name: profile.name, email: profile.email, phone: profile.phone }); onApplied(["name", "email", "phone"]); setMessage("Profile details applied."); }}>Use my profile details</button>{profile.addresses.length > 0 ? <label className="form-field"><span>Fill from saved address</span><select value="" onChange={(event) => useAddress(event.target.value)}><option value="">Choose an address</option>{profile.addresses.map((address) => <option key={address.id} value={address.id}>{address.label}{address.id === profile.defaultAddressId ? " (Default)" : ""}</option>)}</select></label> : <Link href="/account/addresses" className="text-link">Add an address to your account</Link>}{message && <p role="status" className="checkout-address-notice">{message}</p>}</div>;
}
