// app/dashboard/[clientId]/addresses/[addressesId]/page.tsx
"use client";

import { useCallback, useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";

import { Alert, Spinner, Button } from "@/src/Components/UI";
import { AddressDetails } from "@/src/Components/Client_Adress/AddressDetails";
import { clientAddressService } from "@/src/services/clientAddress.service";
import { getStoredToken } from "@/src/lib/auth";
import type { ClientAddress } from "@/src/types/client_adresses";

export default function AddressDetailsPage() {
  const params = useParams();
  const router = useRouter();

  const clientId  = params?.clientId as string | undefined;
  const addressId = params?.addressesId as string | undefined;

  const [address, setAddress] = useState<ClientAddress | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError]     = useState<string | null>(null);

  const loadAddress = useCallback(async () => {
    if (!clientId || !addressId) return;
    setLoading(true);
    setError(null);
    try {
      const token = getStoredToken();
      const res = await clientAddressService.getById(clientId, addressId, token);
      // normalize in case the API returns _id instead of id
      const raw = res.data as ClientAddress & { _id?: string };
      setAddress({ ...raw, id: raw.id ?? raw._id ?? "" });
    } catch {
      setError("تعذّر تحميل بيانات العنوان. يرجى المحاولة لاحقاً.");
    } finally {
      setLoading(false);
    }
  }, [clientId, addressId]);

  useEffect(() => {
    loadAddress();
  }, [loadAddress]);

  // ── Loading ──────────────────────────────────────────────────────────────
  if (loading) {
    return (
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: "60vh", gap: 12 }}>
        <Spinner size="sm" className="text-blue-600" />
        <span style={{ fontSize: 13, color: "var(--color-text-muted)" }}>جارٍ تحميل بيانات العنوان…</span>
      </div>
    );
  }

  // ── Error ────────────────────────────────────────────────────────────────
  if (error || !address) {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: "1rem", maxWidth: 640, margin: "2rem auto" }}>
        <Alert type="error" message={error ?? "العنوان غير موجود."} />
        <Button
          type="button"
          variant="secondary"
          onClick={() => router.push(`/dashboard/${clientId}/addresses`)}
        >
          العودة إلى العناوين
        </Button>
      </div>
    );
  }

  // ── Content ──────────────────────────────────────────────────────────────
  return (
    <section style={{ display: "flex", flexDirection: "column", gap: "1.25rem", maxWidth: 720, margin: "0 auto", padding: "2rem 1rem" }}>
      <button
        type="button"
        onClick={() => router.push(`/dashboard/${clientId}/addresses`)}
        style={{
          display: "inline-flex",
          alignItems: "center",
          gap: 6,
          fontSize: 12,
          fontWeight: 600,
          color: "var(--color-text-muted)",
          background: "none",
          border: "none",
          cursor: "pointer",
          alignSelf: "flex-start",
          fontFamily: "var(--font-sans)",
        }}
      >
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <path d="M15 18l-6-6 6-6" />
        </svg>
        كل العناوين
      </button>

      <AddressDetails address={address} />
    </section>
  );
}