"use client";

import { useMemo, useState } from "react";
import { ChevronDown, ChevronUp } from "lucide-react";
import { formatEmailBody } from "@/lib/email-body/format-email-body";
import { useLocale } from "@/components/providers/locale-provider";
import { cn } from "@/lib/utils";

export function EmailMessageBody({
  bodyHtml,
  bodyText,
  className,
}: {
  bodyHtml?: string | null;
  bodyText?: string | null;
  className?: string;
}) {
  const { locale } = useLocale();
  const isAr = locale === "ar";
  const [showQuoted, setShowQuoted] = useState(false);

  const formatted = useMemo(
    () => formatEmailBody({ bodyHtml, bodyText }),
    [bodyHtml, bodyText]
  );

  return (
    <article
      dir={formatted.direction}
      className={cn(
        "email-message-body rounded-xl border border-border bg-card p-4 sm:p-6",
        formatted.direction === "rtl" ? "text-right" : "text-left",
        className
      )}
    >
      <div
        className={cn(
          "email-message-main prose prose-sm max-w-none dark:prose-invert",
          formatted.direction === "rtl" ? "prose-p:text-right" : "prose-p:text-left"
        )}
        dangerouslySetInnerHTML={{ __html: formatted.mainHtml }}
      />

      {formatted.quotedHtml ? (
        <div className="mt-4 border-t border-border pt-3">
          <button
            type="button"
            onClick={() => setShowQuoted((open) => !open)}
            className={cn(
              "inline-flex items-center gap-2 rounded-lg border border-border bg-muted/40 px-3 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-muted",
              formatted.direction === "rtl" ? "flex-row-reverse" : ""
            )}
          >
            {showQuoted ? (
              <ChevronUp className="h-3.5 w-3.5" />
            ) : (
              <ChevronDown className="h-3.5 w-3.5" />
            )}
            {showQuoted
              ? isAr
                ? "إخفاء الرسائل السابقة"
                : "Hide previous messages"
              : isAr
                ? "عرض الرسائل السابقة"
                : "Show previous messages"}
          </button>
          {showQuoted ? (
            <div
              className="email-message-quoted mt-3 rounded-lg border border-dashed border-border bg-muted/20 p-4"
              dangerouslySetInnerHTML={{ __html: formatted.quotedHtml }}
            />
          ) : null}
        </div>
      ) : null}
    </article>
  );
}
