"use client";

import { formatDateMDY } from "@/app/lib/dateFormat";
import { useEffect, useState } from "react";
import { Calendar, Clock, History, MapPin, MessageSquare, Phone, User } from "lucide-react";

import CustomerAvatar from "@/app/components/astrologer/CustomerAvatar";
import { CustomerInfo, getCustomerInfo } from "@/app/lib/astrologer";

function formatDate(value?: string) {
  if (!value) return "";
  return formatDateMDY(value);
}

function formatDateTime(value?: string) {
  if (!value) return "";
  const d = new Date(value.replace(" ", "T"));
  if (Number.isNaN(d.getTime())) return value;
  return `${formatDate(value)}, ${d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}`;
}

/*
 * One customer card for the Orders hub (Queue, Waiting, Chat and Call
 * tabs). The header is whatever the tab already knows (name, status line);
 * the details grid is the customer's real profile from
 * GET /astrologer/get-customer-by-id - gender, birth details, member
 * since, how many chats/calls they have had, and their last session.
 * Rows only render for fields the API actually returned.
 */
export default function CustomerOrderCard({
  userId,
  fallbackName,
  subtitle,
  badge,
  children,
}: {
  userId?: number | string | null;
  fallbackName?: string;
  subtitle?: React.ReactNode;
  badge?: { label: string; tone?: "gold" | "green" | "red" | "muted" };
  children?: React.ReactNode; // action buttons
}) {
  const [info, setInfo] = useState<CustomerInfo | null>(null);

  useEffect(() => {
    let cancelled = false;

    getCustomerInfo(userId).then((result) => {
      if (!cancelled) setInfo(result);
    });

    return () => {
      cancelled = true;
    };
  }, [userId]);

  const name = info?.name || fallbackName || "Customer";

  const born = [formatDate(info?.birth_date), info?.birth_time].filter(Boolean).join(" · ");
  const place = info?.birth_place || info?.location || "";
  const sessions =
    info && (info.total_chats != null || info.total_calls != null)
      ? `${info.total_chats ?? 0} chats · ${info.total_calls ?? 0} calls`
      : "";

  const rows: { icon: React.ReactNode; label: string; value: string }[] = [
    { icon: <User size={14} />, label: "Gender", value: info?.gender || "" },
    { icon: <Calendar size={14} />, label: "Born", value: born },
    { icon: <MapPin size={14} />, label: "Birth place", value: place },
    { icon: <History size={14} />, label: "History", value: sessions },
    { icon: <Clock size={14} />, label: "Last session", value: formatDateTime(info?.last_session_at) },
    { icon: <Calendar size={14} />, label: "Member since", value: formatDate(info?.member_since) },
  ].filter((row) => row.value);

  return (
    <div className="order-card">
      <div className="order-card-top">
        <CustomerAvatar userId={userId} name={name} className="waiting-user-avatar" />

        <div className="order-card-id">
          <div className="waiting-user-name">{name}</div>
          {subtitle && <div className="order-card-sub">{subtitle}</div>}
        </div>

        {badge && <span className={`order-card-badge ${badge.tone ?? "gold"}`}>{badge.label}</span>}
      </div>

      {rows.length > 0 && (
        <div className="order-card-details">
          {rows.map((row) => (
            <div key={row.label} className="order-card-detail">
              <span className="order-card-detail-label">
                {row.icon}
                {row.label}
              </span>
              <span className="order-card-detail-value">{row.value}</span>
            </div>
          ))}
        </div>
      )}

      {children && <div className="order-card-actions">{children}</div>}
    </div>
  );
}

// Re-exported so the Orders page can use the same icons for its buttons.
export { MessageSquare as ChatIcon, Phone as CallIcon };
