"use client";

import Link from "next/link";
import { Building2, Megaphone, UserCircle, Sparkles, Mail } from "lucide-react";
import { InboxMessageActions } from "@/components/inbox/inbox-message-actions";
import {
  AiClassificationPanel,
  type AiClassificationView,
} from "@/components/inbox/ai-classification-panel";
import { EmailMessageBody } from "@/components/inbox/email-message-body";
import {
  InboxConversationTimeline,
  type ConversationMessage,
} from "@/components/inbox/inbox-conversation-timeline";
import { Badge } from "@/components/ui/badge";
import { useLocale } from "@/components/providers/locale-provider";

const STATUS_LABELS: Record<string, { ar: string; en: string }> = {
  new: { ar: "جديد", en: "New" },
  classified: { ar: "مُصنَّف", en: "Classified" },
  linked_to_lead: { ar: "مرتبط بعميل", en: "Linked to lead" },
  ignored: { ar: "متجاهل", en: "Ignored" },
  spam: { ar: "مؤرشف", en: "Archived" },
};

export function InboxDetailWorkspace({
  id,
  item,
}: {
  id: string;
  item: {
    subject?: string;
    fromEmail: string;
    toEmail?: string;
    receivedAt: string;
    status: string;
    campaignId?: { name?: string; _id?: string };
    companyId?: { nameAr?: string; _id?: string };
    personId?: { fullName?: string; _id?: string };
    lead?: { _id?: string };
    opportunity?: { _id?: string };
    bodyText?: string;
    bodyHtml?: string;
    messageId?: { subject?: string; sentAt?: string; status?: string };
    activities?: Array<Record<string, unknown>>;
    classification?: AiClassificationView | null;
    relatedThread?: ConversationMessage[];
  };
}) {
  const { locale } = useLocale();
  const isAr = locale === "ar";
  const statusLabel =
    STATUS_LABELS[item.status]?.[isAr ? "ar" : "en"] ?? item.status;

  const thread = (item.relatedThread ?? []) as ConversationMessage[];
  const allMessages: ConversationMessage[] = [
    ...thread,
    {
      _id: id,
      fromEmail: item.fromEmail,
      toEmail: item.toEmail,
      subject: item.subject,
      receivedAt: item.receivedAt,
      status: item.status,
      bodyText: item.bodyText,
      bodyHtml: item.bodyHtml,
    },
  ]
    .filter(
      (msg, index, arr) => arr.findIndex((m) => m._id === msg._id) === index
    )
    .sort(
      (a, b) =>
        new Date(a.receivedAt).getTime() - new Date(b.receivedAt).getTime()
    );

  const showTimeline = allMessages.length > 1;

  return (
    <div className="animate-fade-in space-y-4">
      <Link
        href="/inbox"
        className="inline-flex text-sm text-muted-foreground hover:text-primary"
      >
        {isAr ? "← صندوق الوارد" : "← Inbox"}
      </Link>

      <div className="grid gap-6 lg:grid-cols-12">
        <main className="space-y-4 lg:col-span-8">
          <header className="surface-elevated border-b border-border px-4 py-5 sm:px-6">
            <div className="flex flex-wrap items-start justify-between gap-3">
              <div className="min-w-0 flex-1">
                <h1 className="text-xl font-bold leading-snug sm:text-2xl">
                  {item.subject ?? (isAr ? "(بدون موضوع)" : "(No subject)")}
                </h1>
                <div className="mt-3 flex flex-wrap items-center gap-2 text-sm">
                  <span className="inline-flex items-center gap-1.5 font-medium" dir="ltr">
                    <Mail className="h-4 w-4 text-primary" />
                    {item.fromEmail}
                  </span>
                  {item.toEmail ? (
                    <span className="text-muted-foreground" dir="ltr">
                      → {item.toEmail}
                    </span>
                  ) : null}
                </div>
                <p className="mt-1 text-xs text-muted-foreground">
                  {new Date(item.receivedAt).toLocaleString(
                    isAr ? "ar-SA" : "en-US"
                  )}
                </p>
              </div>
              <Badge variant="secondary" className="text-sm">
                {statusLabel}
              </Badge>
            </div>
            {item.campaignId?.name ? (
              <p className="mt-3 inline-flex items-center gap-1.5 text-sm text-muted-foreground">
                <Megaphone className="h-4 w-4" />
                {isAr ? "الحملة:" : "Campaign:"} {item.campaignId.name}
              </p>
            ) : null}
          </header>

          {!showTimeline ? (
            <EmailMessageBody bodyHtml={item.bodyHtml} bodyText={item.bodyText} />
          ) : null}

          {showTimeline ? (
            <InboxConversationTimeline messages={allMessages} activeId={id} />
          ) : null}

          {item.messageId ? (
            <div className="rounded-xl border border-dashed border-border bg-muted/20 px-4 py-3 text-sm text-muted-foreground">
              {isAr ? "مرتبط برسالة صادرة من الحملة" : "Linked to outbound campaign message"}
              {item.messageId.sentAt
                ? ` · ${new Date(item.messageId.sentAt).toLocaleString(isAr ? "ar-SA" : "en-US")}`
                : ""}
            </div>
          ) : null}
        </main>

        <aside className="space-y-4 lg:col-span-4">
          <div className="surface-elevated p-5">
            <h2 className="mb-4 flex items-center gap-2 text-base font-semibold">
              <Sparkles className="h-4 w-4 text-accent" />
              {isAr ? "سياق CRM" : "CRM context"}
            </h2>
            <dl className="space-y-3 text-sm">
              {item.companyId?.nameAr ? (
                <div>
                  <dt className="text-muted-foreground">
                    {isAr ? "الشركة" : "Company"}
                  </dt>
                  <dd>
                    <Link
                      href={`/market/companies/${item.companyId._id ?? ""}`}
                      className="inline-flex items-center gap-1 font-medium text-primary hover:underline"
                    >
                      <Building2 className="h-4 w-4" />
                      {item.companyId.nameAr}
                    </Link>
                  </dd>
                </div>
              ) : null}
              {item.personId?.fullName ? (
                <div>
                  <dt className="text-muted-foreground">
                    {isAr ? "الشخص" : "Person"}
                  </dt>
                  <dd>
                    <Link
                      href={`/market/people/${item.personId._id ?? ""}`}
                      className="inline-flex items-center gap-1 font-medium text-primary hover:underline"
                    >
                      <UserCircle className="h-4 w-4" />
                      {item.personId.fullName}
                    </Link>
                  </dd>
                </div>
              ) : null}
              {item.lead?._id ? (
                <div>
                  <dt className="text-muted-foreground">Lead</dt>
                  <dd>
                    <Link
                      href={`/leads/${item.lead._id}`}
                      className="text-primary hover:underline"
                    >
                      {isAr ? "عرض العميل المحتمل" : "View lead"}
                    </Link>
                  </dd>
                </div>
              ) : null}
              {item.opportunity?._id ? (
                <div>
                  <dt className="text-muted-foreground">
                    {isAr ? "الفرصة" : "Opportunity"}
                  </dt>
                  <dd>
                    <Link
                      href={`/opportunities/${item.opportunity._id}`}
                      className="text-primary hover:underline"
                    >
                      {isAr ? "عرض الفرصة" : "View opportunity"}
                    </Link>
                  </dd>
                </div>
              ) : null}
            </dl>
          </div>

          <div className="surface-elevated p-5">
            <h2 className="mb-3 text-base font-semibold">
              {isAr ? "إجراءات" : "Actions"}
            </h2>
            <InboxMessageActions
              emailId={id}
              currentStatus={item.status}
              subject={item.subject}
            />
          </div>

          <AiClassificationPanel
            emailReplyId={id}
            classification={item.classification ?? null}
          />
        </aside>
      </div>
    </div>
  );
}
