"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { ArrowLeftRight, UserRound, WalletCards } from "lucide-react";
import { PageHeader, StatusBadge } from "@/components/shared/page";
import { PreviewLink } from "@/components/layout/preview-context";
import { updateQuery } from "@/lib/list-query";
import type { WalletAuditApiPage } from "./wallet-audit-contract";
import { WalletActivityView } from "./wallet-activity-view";

export type CustomerDetailDisplay = {
  id: string;
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  active: boolean;
  role: string;
  createdAt: string;
  address: {
    streetAndNumber: string;
    city: string;
    state: string;
    postalCode: string;
    country: string;
  };
  basicInformation: {
    dateOfBirth: string;
    placeOfBirth: string;
    gender: string;
  };
  walletBalance: number | null;
  walletCurrency: string | null;
  walletActive: boolean | null;
};

function display(value: string | null | undefined) {
  return value?.trim() || "—";
}

function formatDate(value: string) {
  if (!value) return "—";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "—";
  return new Intl.DateTimeFormat("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    timeZone: "UTC",
  }).format(date);
}

function formatWalletBalance(customer: CustomerDetailDisplay) {
  if (customer.walletBalance === null) return "—";
  const currency = customer.walletCurrency || "IDR";
  try {
    return new Intl.NumberFormat("id-ID", {
      style: "currency",
      currency,
      maximumFractionDigits: 0,
    }).format(customer.walletBalance);
  } catch {
    return `${currency} ${customer.walletBalance.toLocaleString("id-ID")}`;
  }
}

function DetailField({ label, value }: { label: string; value: string }) {
  return (
    <div className="min-w-0">
      <dt className="text-sm text-muted-foreground">{label}</dt>
      <dd className="mt-1 break-words text-sm font-medium">{display(value)}</dd>
    </div>
  );
}

function initials(customer: CustomerDetailDisplay) {
  return `${customer.firstName.trim()[0] ?? "U"}${customer.lastName.trim()[0] ?? ""}`.toUpperCase();
}

export function CustomerDetailView({
  customer,
  source,
  walletActivity,
  walletActivityError,
}: {
  customer: CustomerDetailDisplay;
  source: "connected" | "preview";
  walletActivity?: WalletAuditApiPage;
  walletActivityError?: string;
}) {
  const router = useRouter();
  const params = useSearchParams();
  const customerName = `${customer.firstName} ${customer.lastName}`.trim() || "Customer";
  const hasWallet = customer.walletBalance !== null ||
    customer.walletCurrency !== null || customer.walletActive !== null;
  const requestedTab = params.get("tab");
  const activeTab = requestedTab === "activity" ? "activity" : "wallet";
  const dateOfBirth = customer.basicInformation.dateOfBirth
    ? formatDate(customer.basicInformation.dateOfBirth)
    : "";
  const customerPath = `/customers/${encodeURIComponent(customer.id)}`;
  const customerHref = (updates: Record<string, string | null>) => {
    const query = updateQuery(params.toString(), updates);
    return query ? `${customerPath}?${query}` : customerPath;
  };
  const tabHref = (tab: "wallet" | "activity") => customerHref(
    tab === "wallet"
      ? { tab: null, paginate_page: null }
      : { tab, paginate_page: "1" },
  );
  const changeActivityPage = (page: number) => {
    router.push(customerHref({ tab: "activity", paginate_page: String(page) }), {
      scroll: false,
    });
  };

  return (
    <div className="min-w-0 space-y-6">
      <PageHeader
        title="Customer details"
        currentPage="Details"
        parent={{ label: "Customers", href: "/customers" }}
      />

      <section className="panel p-5 sm:p-6">
        <div className="flex flex-wrap items-center justify-between gap-4">
          <div className="flex min-w-0 items-center gap-4 sm:gap-5">
            <div className="flex size-16 shrink-0 items-center justify-center rounded-full border border-border bg-muted text-lg font-semibold text-foreground">
              {initials(customer)}
            </div>
            <div className="min-w-0 flex-1">
              <h2 className="break-words text-xl font-semibold">{customerName}</h2>
              <div className="mt-2 flex flex-wrap items-center gap-2">
                <span className="inline-flex whitespace-nowrap rounded-full bg-muted px-2.5 py-1 text-xs font-medium text-muted-foreground">
                  {customer.role || "user"}
                </span>
                <StatusBadge>{customer.active ? "Active" : "Inactive"}</StatusBadge>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section className="panel space-y-5 p-5 sm:p-6">
        <div>
          <h3 className="text-lg font-semibold">Profile</h3>
          <p className="mt-1 text-sm text-muted-foreground">
            Personal and address information for {customerName}.
          </p>
        </div>
        <div className="grid min-w-0 gap-4 xl:grid-cols-2">
          <section className="rounded-xl border border-border bg-background p-5 sm:p-6">
            <h4 className="mb-5 text-base font-semibold">Personal Information</h4>
            <dl className="grid gap-x-6 gap-y-5 sm:grid-cols-2">
              <DetailField label="First name" value={customer.firstName} />
              <DetailField label="Last name" value={customer.lastName} />
              <DetailField label="Email address" value={customer.email} />
              <DetailField label="Phone" value={customer.phone} />
              <DetailField label="Date of birth" value={dateOfBirth} />
              <DetailField label="Place of birth" value={customer.basicInformation.placeOfBirth} />
              <DetailField label="Gender" value={customer.basicInformation.gender} />
            </dl>
          </section>
          <section className="rounded-xl border border-border bg-background p-5 sm:p-6">
            <h4 className="mb-5 text-base font-semibold">Address Information</h4>
            <dl className="grid gap-x-6 gap-y-5 sm:grid-cols-2">
              <div className="sm:col-span-2">
                <DetailField label="Street address" value={customer.address.streetAndNumber} />
              </div>
              <DetailField label="City" value={customer.address.city} />
              <DetailField label="State / province" value={customer.address.state} />
              <DetailField label="Country" value={customer.address.country} />
              <DetailField label="Postal code" value={customer.address.postalCode} />
            </dl>
          </section>
        </div>
      </section>

      <section className="panel min-w-0 overflow-hidden">
        <nav
          aria-label="Customer activity"
          className="flex gap-6 overflow-x-auto border-b border-border px-5 sm:px-6"
        >
          {([
            ["wallet", "Wallet", WalletCards],
            ["activity", "Wallet Activity", ArrowLeftRight],
          ] as const).map(([tab, label, Icon]) => (
            <PreviewLink
              key={tab}
              aria-current={activeTab === tab ? "page" : undefined}
              className={`inline-flex shrink-0 items-center gap-2 border-b-2 px-1 py-4 text-sm font-medium ${activeTab === tab ? "border-primary text-primary" : "border-transparent text-muted-foreground hover:text-foreground"}`}
              href={tabHref(tab)}
            >
              <Icon className="size-4" aria-hidden="true" />{label}
            </PreviewLink>
          ))}
        </nav>
        <div className="min-w-0 p-5 sm:p-6">
          {activeTab === "wallet" ? (
            <section className="space-y-5">
              <div>
                <h3 className="text-base font-semibold">Wallet</h3>
                <p className="mt-1 text-sm text-muted-foreground">Wallet balance and account status.</p>
              </div>
              {hasWallet ? (
                <div className="grid gap-4 sm:grid-cols-2">
                  <div className="rounded-xl border border-border bg-background p-5">
                    <div className="flex items-center gap-3 text-sm text-muted-foreground">
                      <WalletCards className="size-4" aria-hidden="true" /> Balance
                    </div>
                    <p className="mt-3 text-2xl font-semibold">{formatWalletBalance(customer)}</p>
                    <p className="mt-1 text-sm text-muted-foreground">{customer.walletCurrency || "IDR"}</p>
                  </div>
                  <div className="rounded-xl border border-border bg-background p-5">
                    <p className="text-sm text-muted-foreground">Wallet status</p>
                    <div className="mt-3">
                      {customer.walletActive === null ? (
                        <span className="text-sm font-medium">—</span>
                      ) : (
                        <StatusBadge>{customer.walletActive ? "Active" : "Inactive"}</StatusBadge>
                      )}
                    </div>
                  </div>
                </div>
              ) : (
                <div className="rounded-xl border border-border bg-background px-5 py-10 text-center">
                  <p className="font-medium">Wallet data unavailable</p>
                  <p className="mt-1 text-sm text-muted-foreground">The user detail response does not include a wallet.</p>
                </div>
              )}
            </section>
          ) : (
            <WalletActivityView
              page={walletActivity}
              currency={customer.walletCurrency || "IDR"}
              error={walletActivityError}
              previewOnly={source === "preview"}
              onPageChange={changeActivityPage}
            />
          )}
        </div>
      </section>

      <p className="flex flex-wrap items-center gap-2 break-all text-xs text-muted-foreground">
        <UserRound className="size-3.5 shrink-0" aria-hidden="true" /> Customer ID: {customer.id}
        {customer.createdAt && <span className="ml-auto">Created {formatDate(customer.createdAt)}</span>}
      </p>
    </div>
  );
}
