"use client";

import Link from "next/link";
import { Building2, Factory, Link2, X } from "lucide-react";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { ownerRecordPath } from "../documents/file-utils";
import { humanize } from "../lib/format";

// Small presentational pieces shared by the mailbox panes.

const DISPLAY_TIMEZONE = "Asia/Dhaka";
const timeFormatter = new Intl.DateTimeFormat("en-US", { hour: "numeric", minute: "2-digit", timeZone: DISPLAY_TIMEZONE });
const dayFormatter = new Intl.DateTimeFormat("en-US", { month: "short", day: "numeric", timeZone: DISPLAY_TIMEZONE });
const fullDayFormatter = new Intl.DateTimeFormat("en-US", { dateStyle: "medium", timeZone: DISPLAY_TIMEZONE });
const weekdayFormatter = new Intl.DateTimeFormat("en-US", { weekday: "short", timeZone: DISPLAY_TIMEZONE });
const dhakaDayKey = new Intl.DateTimeFormat("en-CA", { timeZone: DISPLAY_TIMEZONE });
const longFormatter = new Intl.DateTimeFormat("en-US", { weekday: "short", month: "short", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit", timeZone: DISPLAY_TIMEZONE });

/** List time like Outlook: "3:45 PM" today, "Mon" this week, "Sep 24" this year, "Sep 24, 2025" before (Dhaka time). */
export function formatMailTime(value) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  const now = new Date();
  if (dhakaDayKey.format(date) === dhakaDayKey.format(now)) return timeFormatter.format(date);
  const days = (now - date) / 86_400_000;
  if (days < 6) return weekdayFormatter.format(date);
  if (date.getFullYear() === now.getFullYear()) return dayFormatter.format(date);
  return fullDayFormatter.format(date);
}

/** "Tue, Sep 30, 2026, 3:45 PM" for message headers. */
export function formatMailDateTime(value) {
  if (!value) return "";
  const date = new Date(value);
  return Number.isNaN(date.getTime()) ? "" : longFormatter.format(date);
}

/** "just now", "4 min ago", "3 h ago", "2 days ago". */
export function timeAgo(value) {
  if (!value) return "never";
  const minutes = Math.round((Date.now() - new Date(value).getTime()) / 60_000);
  if (Number.isNaN(minutes)) return "never";
  if (minutes < 1) return "just now";
  if (minutes < 60) return `${minutes} min ago`;
  const hours = Math.round(minutes / 60);
  if (hours < 24) return `${hours} h ago`;
  const days = Math.round(hours / 24);
  return `${days} day${days === 1 ? "" : "s"} ago`;
}

export function personLabel(person) {
  return person?.name || person?.email || "Unknown sender";
}

export function initials(person) {
  const source = (person?.name || person?.email || "?").replace(/@.*/, "");
  return source.split(/[\s._-]+/).filter(Boolean).slice(0, 2).map((part) => part[0].toUpperCase()).join("") || "?";
}

export function PersonAvatar({ person, className }) {
  return <Avatar className={cn("size-8", className)} aria-hidden="true">
    <AvatarFallback className={cn("text-xs font-medium", person?.isTeam ? "bg-primary/10 text-primary" : "bg-muted text-muted-foreground")}>{initials(person)}</AvatarFallback>
  </Avatar>;
}

const PARTY_ICONS = { buyer: Building2, factory: Factory };

/** "Buyer · H&M" chip for a contact's party. */
export function PartyBadge({ party, className }) {
  if (!party) return null;
  const Icon = PARTY_ICONS[party.type] || Building2;
  return <Badge variant="neutral" className={cn("h-5 max-w-44 gap-1 px-1.5 font-normal", className)} title={`${humanize(party.type)} · ${party.name || party.code}`}>
    <Icon aria-hidden="true" /><span className="truncate">{humanize(party.type)} · {party.name || party.code}</span>
  </Badge>;
}

/** Record page for a thread link: the API's url, else the shared record-path rules. */
export function linkHref(link) {
  return link?.url || ownerRecordPath({ link: { type: link?.type, code: link?.code } });
}

const LINK_TYPE_SHORT = { purchase_order: "PO", letter_of_credit: "L/C", cost_sheet: "Cost sheet", factory_quote: "Factory quote" };
export const linkTypeLabel = (type) => LINK_TYPE_SHORT[type] || humanize(type);

/** One linked-record chip. `onRemove` shows a × (manual links only). */
export function LinkChip({ link, onRemove, removing = false, className }) {
  const href = linkHref(link);
  const label = link.label || link.code;
  const content = <><Link2 aria-hidden="true" /><span className="truncate">{label}</span></>;
  return <Badge variant="outline" className={cn("h-6 max-w-52 gap-1 rounded-md pr-1.5 font-normal", onRemove && "pr-0.5", className)} title={`${linkTypeLabel(link.type)} ${label}${link.source ? ` · ${humanize(link.source)}` : ""}`}>
    {href ? <Link href={href} className="flex min-w-0 items-center gap-1 hover:underline" onClick={(event) => event.stopPropagation()}>{content}</Link> : <span className="flex min-w-0 items-center gap-1">{content}</span>}
    {onRemove && <button type="button" disabled={removing} className="ml-0.5 rounded-sm p-0.5 text-muted-foreground hover:bg-foreground/10 hover:text-foreground disabled:opacity-50" aria-label={`Unlink ${label}`} onClick={(event) => { event.stopPropagation(); onRemove(link); }}><X className="size-3" /></button>}
  </Badge>;
}

/** First link chip plus "+N" (tooltip lists the rest). Used in thread rows. */
export function LinkChipSummary({ links = [], className }) {
  if (!links.length) return null;
  const [first, ...rest] = links;
  return <span className={cn("flex min-w-0 items-center gap-1", className)}>
    <Badge variant="outline" className="h-5 min-w-0 max-w-40 gap-1 rounded-md px-1.5 font-normal" title={`${linkTypeLabel(first.type)} ${first.label || first.code}`}>
      <Link2 aria-hidden="true" /><span className="truncate">{first.label || first.code}</span>
    </Badge>
    {rest.length > 0 && <Tooltip>
      <TooltipTrigger asChild><Badge variant="outline" className="h-5 rounded-md px-1.5 font-normal tabular-nums" tabIndex={0}>+{rest.length}</Badge></TooltipTrigger>
      <TooltipContent className="max-w-64">{rest.map((link) => link.label || link.code).join(", ")}</TooltipContent>
    </Tooltip>}
  </span>;
}

/** Readable recipients line: "Anna Svensson, qa@hm.com". */
export function recipientsText(list = []) {
  return list.map((person) => person.name || person.email).join(", ");
}

export function formatBytes(size) {
  if (!size) return "0 B";
  if (size < 1024) return `${size} B`;
  if (size < 1024 * 1024) return `${Math.round(size / 1024)} KB`;
  return `${(size / 1024 / 1024).toFixed(1)} MB`;
}
