import Link from "next/link";
import { ArrowLeftRight, ArrowUpRight, UserRound, WalletCards, Zap } from "lucide-react";
import { PageHeader } from "@/components/shared/page-header";
import { StatusBadge } from "@/components/shared/status-badge";
import { sessionDate, sessionStatusLabel, sessionTone } from "@/features/sessions/presentation";
import type { Session } from "@/features/sessions/types";
import type { Pagination } from "@/lib/list-query";
import { WalletActivityPanel } from "./wallet-activity-panel";
import { CustomerEditDialog } from "./customer-edit-dialog";
import type { CustomerDetailRecord, WalletActivityEntry } from "./types";

type CustomerDetailViewProps = {
  customer: CustomerDetailRecord;
  previewOnly?: boolean;
  canManage?: boolean;
  canOpenSessions?: boolean;
  activeTab: "wallet" | "activity" | "sessions";
  sessions: Session[];
  walletActivity: WalletActivityEntry[];
  walletActivityPagination?: Pagination;
  walletActivityError?: string;
  walletActivityPreview?: boolean;
  sessionsError?: string;
  sessionsNotice?: string;
};

function fullName(customer: CustomerDetailRecord) {
  return `${customer.firstName} ${customer.lastName}`.trim() || "Customer";
}

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

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: CustomerDetailRecord) {
  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 ProfileCard({ customer, previewOnly, canManage }: { customer: CustomerDetailRecord; previewOnly?: boolean; canManage: boolean }) {
  const name = fullName(customer);
  const role = customer.roles.find((value) => value.toLowerCase() === "user") ?? customer.roles[0] ?? "User";

  return (
    <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">{name}</h2>
            <div className="mt-2 flex flex-wrap items-center gap-2">
              <StatusBadge>{role}</StatusBadge>
              <StatusBadge tone={customer.active ? "success" : "neutral"}>
                {customer.active ? "Active" : "Inactive"}
              </StatusBadge>
            </div>
          </div>
        </div>
        {!previewOnly && canManage && <CustomerEditDialog customer={customer} />}
      </div>
    </section>
  );
}

function WalletPanel({ customer }: { customer: CustomerDetailRecord }) {
  const hasWallet = customer.walletBalance !== null || customer.walletCurrency !== null || customer.walletActive !== null;
  return (
    <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 tone={customer.walletActive ? "success" : "neutral"}>
                  {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>
  );
}

function SessionsPanel({
  customer,
  sessions,
  error,
  notice,
  canOpenSessions,
}: {
  customer: CustomerDetailRecord;
  sessions: Session[];
  error?: string;
  notice?: string;
  canOpenSessions: boolean;
}) {
  const allSessionsHref = `/sessions?user_id=${encodeURIComponent(customer.id)}`;
  return (
    <section className="space-y-4">
      <div className="flex flex-wrap items-end justify-between gap-3">
        <div>
          <h3 className="text-base font-semibold">Sessions</h3>
          <p className="mt-1 text-sm text-muted-foreground">Charging sessions associated with this customer.</p>
        </div>
        {canOpenSessions && <Link className="inline-flex items-center gap-1 text-sm font-medium text-primary hover:underline" href={allSessionsHref}>
          View all sessions <ArrowUpRight className="size-4" aria-hidden="true" />
        </Link>}
      </div>
      {notice && <p role="status" className="text-sm text-muted-foreground">{notice}</p>}
      {error ? (
        <p role="alert" className="rounded-lg border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">{error}</p>
      ) : sessions.length ? (
        <div className="overflow-x-auto rounded-xl border border-border">
          <table className="data-table min-w-[760px]">
            <caption className="sr-only">Recent sessions for {fullName(customer)}</caption>
            <thead>
              <tr>
                <th>Status</th>
                <th>Session</th>
                <th>Start time</th>
                <th>Chargepoint</th>
                <th>Energy</th>
              </tr>
            </thead>
            <tbody>
              {sessions.slice(0, 10).map((session) => (
                <tr key={session.id}>
                  <td><StatusBadge tone={sessionTone(session.status)}>{sessionStatusLabel(session.status)}</StatusBadge></td>
                  <td className="max-w-56 truncate">
                    {canOpenSessions ? <Link className="underline decoration-border underline-offset-4 hover:text-primary" href={`/sessions/${encodeURIComponent(session.id)}`}>
                      {session.id}
                    </Link> : session.id}
                  </td>
                  <td className="whitespace-nowrap">{sessionDate(session.start)}</td>
                  <td>{display(session.chargepointName)}</td>
                  <td className="whitespace-nowrap">{session.energy.toLocaleString("id-ID", { maximumFractionDigits: 2 })} kWh</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div className="rounded-xl border border-border bg-background px-5 py-10 text-center">
          <p className="font-medium">No sessions found</p>
          <p className="mt-1 text-sm text-muted-foreground">No charging sessions are linked to this customer.</p>
        </div>
      )}
    </section>
  );
}

export function CustomerDetailView({
  customer,
  previewOnly,
  canManage = true,
  canOpenSessions = true,
  activeTab,
  sessions,
  walletActivity,
  walletActivityPagination,
  walletActivityError,
  walletActivityPreview,
  sessionsError,
  sessionsNotice,
}: CustomerDetailViewProps) {
  const customerName = fullName(customer);
  const dateOfBirth = customer.basicInformation.dateOfBirth
    ? formatDate(customer.basicInformation.dateOfBirth)
    : "";
  const tabHref = (tab: "wallet" | "activity" | "sessions") =>
    `/customers/${encodeURIComponent(customer.id)}${tab === "wallet" ? "" : `?tab=${tab}`}`;

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

      <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],
            ["sessions", "Sessions", Zap],
          ] as const).map(([tab, label, Icon]) => (
            <Link
              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}
            </Link>
          ))}
        </nav>
        <div className="min-w-0 p-5 sm:p-6">
          {activeTab === "wallet" ? (
            <WalletPanel customer={customer} />
          ) : activeTab === "activity" ? (
            <WalletActivityPanel
              entries={walletActivity}
              currency={customer.walletCurrency || "IDR"}
              pagination={walletActivityPagination}
              error={walletActivityError}
              previewOnly={walletActivityPreview}
            />
          ) : (
            <SessionsPanel customer={customer} sessions={sessions} error={sessionsError} notice={sessionsNotice} canOpenSessions={canOpenSessions} />
          )}
        </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>
  );
}
