"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { Inbox, Loader2 } from "lucide-react";
import { useLocale } from "@/components/providers/locale-provider";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { EmailMessageBody } from "@/components/inbox/email-message-body";

type PreviewItem = {
  _id: string;
  subject?: string;
  fromEmail: string;
  receivedAt: string;
  status: string;
  bodyText?: string;
  bodyHtml?: string;
  companyId?: { nameAr?: string; _id?: string };
  leadId?: string;
  lead?: { _id?: string };
  classification?: { intent?: string } | null;
};

export function InboxPreviewPane({ messageId }: { messageId: string | null }) {
  const { locale } = useLocale();
  const isAr = locale === "ar";
  const [item, setItem] = useState<PreviewItem | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!messageId) return;

    let cancelled = false;
    const loadingTimer = window.setTimeout(() => {
      if (!cancelled) setLoading(true);
    }, 0);

    void (async () => {
      try {
        const res = await fetch(`/api/inbox/${messageId}`);
        const json = await res.json();
        if (!cancelled && res.ok) {
          const data = json.data as PreviewItem;
          setItem(
            data
              ? {
                  ...data,
                  leadId: data.leadId ?? data.lead?._id,
                  classification:
                    data.classification ??
                    (data as { classificationId?: { intent?: string } }).classificationId ??
                    null,
                }
              : null
          );
        }
        else if (!cancelled) setItem(null);
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();

    return () => {
      cancelled = true;
      window.clearTimeout(loadingTimer);
    };
  }, [messageId]);

  if (!messageId) {
    return (
      <div className="flex h-full min-h-[280px] flex-col items-center justify-center rounded-xl border border-dashed border-border bg-muted/20 p-8 text-center">
        <Inbox className="mb-3 h-10 w-10 text-muted-foreground/60" />
        <p className="text-sm text-muted-foreground">
          {isAr ? "اختر رسالة للمعاينة" : "Select a message to preview"}
        </p>
      </div>
    );
  }

  if (loading && !item) {
    return (
      <div className="flex h-full min-h-[280px] items-center justify-center rounded-xl border border-border bg-card">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  if (!item || item._id !== messageId) {
    return (
      <div className="rounded-xl border border-border bg-card p-6 text-sm text-muted-foreground">
        {isAr ? "تعذر تحميل الرسالة" : "Could not load message"}
      </div>
    );
  }

  return (
    <div className="flex h-full min-h-0 flex-col overflow-hidden rounded-xl border border-border bg-card shadow-[var(--shadow-sm)]">
      <div className="border-b border-border bg-muted/30 px-4 py-4">
        <h2 className="text-lg font-bold leading-snug">
          {item.subject ?? (isAr ? "(بدون موضوع)" : "(No subject)")}
        </h2>
        <p className="mt-1 text-sm text-muted-foreground" dir="ltr">
          {item.fromEmail}
        </p>
        <p className="text-xs text-muted-foreground">
          {new Date(item.receivedAt).toLocaleString(isAr ? "ar-SA" : "en-US")}
        </p>
        <div className="mt-2 flex flex-wrap gap-1.5">
          <Badge variant="secondary">{item.status}</Badge>
          {item.classification?.intent ? (
            <Badge variant="secondary">AI: {item.classification.intent}</Badge>
          ) : null}
          {item.leadId ? (
            <Badge className="bg-primary/15 text-primary">
              {isAr ? "Lead" : "Lead"}
            </Badge>
          ) : null}
        </div>
        <div className="mt-3 flex flex-wrap gap-2">
          <Button asChild size="sm" variant="default">
            <Link href={`/inbox/${item._id}`}>
              {isAr ? "فتح كامل" : "Open full"}
            </Link>
          </Button>
          {item.companyId?._id ? (
            <Button asChild size="sm" variant="outline">
              <Link href={`/market/companies/${item.companyId._id}`}>
                {item.companyId.nameAr ?? (isAr ? "الشركة" : "Company")}
              </Link>
            </Button>
          ) : null}
        </div>
      </div>
      <div className="flex-1 overflow-y-auto p-4">
        <EmailMessageBody
          bodyHtml={item.bodyHtml}
          bodyText={item.bodyText}
          className="border-0 bg-transparent p-0 shadow-none"
        />
      </div>
    </div>
  );
}
