"use client";

import * as React from "react";
import { UserIcon } from "lucide-react";

import { Badge } from "@/components/ui/badge";
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Typography } from "@/components/ui/typography";
import { useTranslation } from "@/hooks/useTranslation";
import type { WashCustomers } from "@/types/customers";

interface CustomerDetailsDialogProps {
  /** The customer to view details for, or null when no dialog should be shown */
  target: WashCustomers | null;
  onClose: () => void;
}

function formatDate(value: string, language: string) {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "—";

  return new Intl.DateTimeFormat(language, {
    dateStyle: "medium",
    timeStyle: "short",
  }).format(date);
}

/**
 * Read-only customer details view for the admin list.
 *
 * The table already has the data we need, so this dialog stays local to the
 * screen instead of navigating to a separate detail route.
 */
export function CustomerDetailsDialog({
  target,
  onClose,
}: CustomerDetailsDialogProps) {
  const { t, language } = useTranslation();

  // Keep the last customer visible while the dialog animates out.
  const [lastTarget, setLastTarget] = React.useState<WashCustomers | null>(
    null,
  );
  if (target && target !== lastTarget) setLastTarget(target);

  const shown = target ?? lastTarget;
  if (!shown) return null;

  const initials = `${shown.firstName?.trim().charAt(0) ?? ""}${
    shown.lastName?.trim().charAt(0) ?? ""
  }`.toUpperCase();

  return (
    <Dialog
      open={!!target}
      onOpenChange={(next) => {
        if (!next) onClose();
      }}
    >
      <DialogContent className="sm:max-w-2xl">
        <DialogHeader>
          <DialogTitle>
            {shown.firstName} {shown.lastName}
          </DialogTitle>
          <DialogDescription>
            {shown.isActive
              ? t("customers.status.active")
              : t("customers.status.inactive")}
          </DialogDescription>
        </DialogHeader>

        <DialogBody className="flex flex-col gap-5">
          <div className="flex items-center gap-3 rounded-2xl bg-muted/50 p-4">
            <div className="flex size-12 items-center justify-center rounded-full bg-information-light text-primary-sky-blue">
              <UserIcon className="size-5" />
            </div>
            <div className="min-w-0 flex-1">
              <Typography as="h3" variant="h3" className="truncate">
                {shown.firstName} {shown.lastName}
              </Typography>
              <div className="mt-1 flex flex-wrap items-center gap-2">
                <Badge variant={shown.isActive ? "complete" : "closed"}>
                  {shown.isActive
                    ? t("customers.status.active")
                    : t("customers.status.inactive")}
                </Badge>
                {shown.icon && (
                  <Typography as="span" variant="caption" color="secondary">
                    {shown.icon}
                  </Typography>
                )}
              </div>
            </div>
            <div
              aria-hidden
              className="flex size-12 shrink-0 items-center justify-center rounded-full border bg-background text-sm font-semibold"
            >
              {initials || "?"}
            </div>
          </div>

          <div className="grid gap-4 sm:grid-cols-2">
            <DetailItem label={t("customers.detail.overview.name")}>
              {shown.firstName} {shown.lastName}
            </DetailItem>
            <DetailItem label={t("customers.detail.overview.email")}>
              {shown.email}
            </DetailItem>
            <DetailItem label={t("customers.detail.overview.phone")}>
              {shown.phoneNumber || "—"}
            </DetailItem>
            <DetailItem label={t("customers.detail.overview.joined")}>
              {formatDate(shown.createdAt, language)}
            </DetailItem>
          </div>

          <div className="grid gap-4 sm:grid-cols-2">
            <DetailItem label="Customer ID">{shown.id}</DetailItem>
            <DetailItem label="Last updated">
              {formatDate(shown.updatedAt, language)}
            </DetailItem>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
}

function DetailItem({
  label,
  children,
}: {
  label: React.ReactNode;
  children: React.ReactNode;
}) {
  return (
    <div className="flex flex-col gap-1.5 rounded-2xl border bg-background p-4">
      <Typography as="span" variant="caption" color="secondary">
        {label}
      </Typography>
      <Typography as="div" variant="body" className="break-words">
        {children}
      </Typography>
    </div>
  );
}
