"use client";
import { useEffect, useState } from "react";
import { apiFetch, formatApiMsg } from "@/lib/api";

export type LegalPageData = {
  content: string;
  image?: string;
};

const BLOCK_LEVEL_START =
  /^\s*<(p|div|h[1-6]|ul|ol|table|section|article|blockquote)\b/i;
const WRAPPED_PARAGRAPH = /^\s*<p\b[^>]*>[\s\S]*<\/p>\s*$/i;

function escapeHtml(text: string): string {
  return text
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;");
}

function formatLegalBlock(block: string): string {
  const trimmed = block.trim();
  if (!trimmed) {
    return "";
  }

  const withLineBreaks = trimmed.replace(/\n/g, "<br>");

  if (WRAPPED_PARAGRAPH.test(trimmed) || BLOCK_LEVEL_START.test(trimmed)) {
    return withLineBreaks;
  }

  const hasHtml = /<[a-z][\s\S]*>/i.test(trimmed);
  const inner = hasHtml ? withLineBreaks : escapeHtml(withLineBreaks);

  return `<p>${inner}</p>`;
}

function formatLegalContent(content: string): string {
  const normalized = content.replace(/\r\n/g, "\n");

  return normalized
    .split(/\n{2,}/)
    .map(formatLegalBlock)
    .filter((block) => block.length > 0)
    .join("");
}

function renderLegalContent(content: string) {
  return (
    <div
      className="text-gray-300 text-sm text-right leading-relaxed [&_a]:text-[#FCD704] [&_a]:hover:underline [&_br]:block [&_h1]:font-bold [&_h1]:mb-3 [&_h1]:text-white [&_h2]:font-bold [&_h2]:mb-3 [&_h2]:text-white [&_h3]:font-bold [&_h3]:mb-2 [&_h3]:text-white [&_li]:mb-1 [&_ol]:mb-3 [&_ol]:list-decimal [&_ol]:pr-5 [&_p]:mb-3 [&_strong]:font-bold [&_strong]:text-white [&_ul]:mb-3 [&_ul]:list-disc [&_ul]:pr-5"
      dangerouslySetInnerHTML={{ __html: formatLegalContent(content) }}
    />
  );
}

type LegalContentModalProps = Readonly<{
  isOpen: boolean;
  onClose: () => void;
  title: string;
  endpoint: "/terms" | "/privacy";
}>;

function renderLoadingState() {
  return (
    <div className="text-center py-10">
      <i className="ri-loader-4-line animate-spin text-[#FCD704] text-3xl" />
    </div>
  );
}

function renderErrorState(error: string) {
  return (
    <div className="bg-red-500/10 border border-red-500/30 rounded-xl p-4 text-center">
      <p className="text-red-400 text-sm">{error}</p>
    </div>
  );
}

export default function LegalContentModal({
  isOpen,
  onClose,
  title,
  endpoint,
}: LegalContentModalProps) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [data, setData] = useState<LegalPageData | null>(null);

  useEffect(() => {
    let active = true;

    if (isOpen) {
      setLoading(true);
      setError("");
      setData(null);

      apiFetch<LegalPageData>(endpoint, {
        method: "GET",
        successCase: (res) => {
          if (active && res.data) {
            setData(res.data);
          }
        },
        errorCase: (res) => {
          if (active) {
            setError(formatApiMsg(res.msg) || "تعذر تحميل المحتوى");
          }
        },
      }).finally(() => {
        if (active) {
          setLoading(false);
        }
      });
    }

    return () => {
      active = false;
    };
  }, [isOpen, endpoint]);

  if (!isOpen) {
    return null;
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <button
        type="button"
        aria-label="إغلاق النافذة"
        className="absolute inset-0 bg-black/60 backdrop-blur-sm cursor-default"
        onClick={onClose}
        onKeyDown={(event) => {
          if (event.key === "Escape") {
            onClose();
          }
        }}
      />
      <dialog
        open
        aria-labelledby="legal-modal-title"
        className="relative bg-[#2A2D36] rounded-2xl w-full max-w-xl overflow-hidden flex flex-col max-h-[90vh] border-0 p-0 m-0"
      >
        <div className="flex items-center justify-between p-6 border-b border-white/5">
          <h2 id="legal-modal-title" className="text-white font-bold text-lg">
            {title}
          </h2>
          <button
            type="button"
            onClick={onClose}
            className="w-8 h-8 flex items-center justify-center rounded-xl bg-white/5 hover:bg-white/10 text-gray-400 hover:text-white transition-colors cursor-pointer"
          >
            <i className="ri-close-line text-lg" />
          </button>
        </div>

        <div className="p-6 overflow-y-auto">
          {loading && renderLoadingState()}
          {!loading && error && renderErrorState(error)}
          {!loading && !error && data && (
            <div className="flex flex-col gap-4">
              {data.image ? (
                <img
                  src={data.image}
                  alt=""
                  className="w-full rounded-xl object-cover"
                />
              ) : null}
              {renderLegalContent(data.content)}
            </div>
          )}
        </div>
      </dialog>
    </div>
  );
}
