"use client";

import Link from "next/link";
import { ArrowUpRight, Mail, Paperclip } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { SectionCard } from "@/components/app/page";
import { cn } from "@/lib/utils";
import { EmptyState, ErrorState } from "../components/ui/page-states";
import { EmailActionButton } from "./email-action-button";
import { formatMailTime, PartyBadge, PersonAvatar, timeAgo } from "./mail-shared";
import { useMailAccess } from "./useMailAccess";
import { useRecordEmails } from "./useRecordEmails";

/**
 * "Emails" section of a record page: threads linked to the record (and, with includeRelated, to its child records),
 * with a compact summary while collapsed and one "Email …" action that opens the pre-filled compose sheet.
 *   <RecordEmails record={{ type: "purchase_order", code: po.poNo }} action="record.email" actionLabel="Email buyer" includeRelated />
 * Hidden entirely for users without mail.view.
 */
export function RecordEmails({ record, action = "record.email", actionLabel = "Email", includeRelated = false, id = "emails" }) {
  const { canView } = useMailAccess();
  const emails = useRecordEmails(record, { includeRelated, enabled: canView });
  if (!canView || !record?.code) return null;

  const { threads, total, latest } = emails;
  const summary = emails.isLoading ? "Loading…" : total ? `${total} ${total === 1 ? "thread" : "threads"} · ${latestSummary(latest)}` : "No emails yet";
  const alerts = [
    emails.failed > 0 && { label: `${emails.failed} not sent`, tone: "danger" },
    emails.needsReply > 0 && { label: `${emails.needsReply} awaiting reply`, tone: "warning" },
  ];

  return <SectionCard
    id={id}
    title="Emails"
    icon={Mail}
    collapsible
    summary={summary}
    alerts={alerts}
    description="Buyer and factory email about this record. Replies land here automatically."
    primaryAction={<EmailActionButton action={action || emails.meta?.defaultAction || "record.email"} record={record} label={actionLabel} />}
  >
    {emails.isLoading
      ? <div className="grid gap-2" aria-busy="true" aria-label="Loading emails">{[0, 1, 2].map((index) => <Skeleton key={index} className="h-14" />)}</div>
      : emails.error && !threads.length
        ? <ErrorState error={emails.error} title="Emails could not be loaded" onRetry={emails.refresh} compact />
        : !threads.length
          ? <EmptyState compact icon={Mail} title="No emails yet" detail="Emails you send from here, and replies to them, are linked to this record automatically." />
          : <div className={cn("grid gap-1 transition-opacity", emails.isRefreshing && "opacity-60")}>
            <ul className="divide-y rounded-lg border">
              {threads.map((thread) => <ThreadRow key={thread.id} thread={thread} />)}
            </ul>
            <div className="flex flex-wrap items-center justify-between gap-2">
              {emails.hasMore ? <Button variant="ghost" size="sm" onClick={emails.loadMore} disabled={emails.isRefreshing}>Show more</Button> : <span />}
              <Button variant="ghost" size="sm" asChild><Link href={mailRecordHref(record)}>Open in Mail<ArrowUpRight /></Link></Button>
            </div>
          </div>}
  </SectionCard>;
}

// Folder "all": a record's emails are often sent-only or archived, which the inbox would not show.
const mailRecordHref = (record) => `/mail?folder=all&record=${encodeURIComponent(`${record.type}:${record.code}`)}`;

function latestSummary(thread) {
  if (!thread) return "";
  const who = thread.participants?.[0];
  const party = who?.party?.name || who?.name || who?.email || "";
  if (thread.latestStatus === "failed") return `Last: not sent ${timeAgo(thread.lastMessageAt)}`;
  return thread.lastDirection === "in" ? `Last: reply from ${party} ${timeAgo(thread.lastMessageAt)}` : `Last: sent ${timeAgo(thread.lastMessageAt)}`;
}

function ThreadRow({ thread }) {
  const person = thread.participants?.[0] || null;
  const unread = thread.unreadCount > 0;
  return <li>
    <Link href={`/mail?thread=${encodeURIComponent(thread.id)}`} className="flex min-w-0 items-start gap-3 px-3 py-2.5 transition-colors outline-none hover:bg-muted/50 focus-visible:bg-muted/50 focus-visible:ring-2 focus-visible:ring-ring/50">
      <PersonAvatar person={person} className="mt-0.5" />
      <span className="grid min-w-0 flex-1 gap-0.5">
        <span className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
          <span className={cn("truncate text-sm", unread ? "font-semibold" : "font-medium")}>{thread.lastDirection === "out" ? `To ${person?.name || person?.email || "recipient"}` : person?.name || person?.email}</span>
          <PartyBadge party={person?.party} />
          {thread.messageCount > 1 && <span className="text-xs tabular-nums text-muted-foreground">{thread.messageCount}</span>}
          <span className="ml-auto flex shrink-0 items-center gap-1.5 text-xs tabular-nums text-muted-foreground">
            {thread.hasAttachments && <Paperclip className="size-3.5" aria-label="Has attachments" />}
            {formatMailTime(thread.lastMessageAt)}
          </span>
        </span>
        <span className={cn("truncate text-sm", unread ? "font-medium text-foreground" : "text-foreground/90")}>{thread.subject || "(no subject)"}</span>
        <span className="flex min-w-0 items-center gap-2">
          <span className="truncate text-xs text-muted-foreground">{thread.snippet}</span>
          {thread.latestStatus === "failed" && <Badge variant="danger" className="h-5 shrink-0 px-1.5">Not sent</Badge>}
          {thread.latestStatus === "queued" && <Badge variant="info" className="h-5 shrink-0 px-1.5">Sending</Badge>}
          {thread.needsReply && <Badge variant="warning" className="h-5 shrink-0 px-1.5">Needs reply</Badge>}
        </span>
      </span>
    </Link>
  </li>;
}
