'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { api } from '@/lib/api';
import type { FixedPagePayload } from '@/lib/types/page';
import { isLoggedIn } from '@/lib/auth';
import { useI18n } from '@/lib/i18n/context';

type Props = {
  /** مسار الـ API (مثل `/general/about`) */
  apiPath: string;
  /** مفتاح ترجمة للعنوان إذا لم يُرجع الـ API عنواناً */
  titleFallbackKey: string;
};

function looksLikeHtml(text: string): boolean {
  return /<[a-z][\s\S]*>/i.test(text.trim());
}

function PageBody({ content }: { content: string }) {
  if (!content.trim()) {
    return <p className="text-gray-500">—</p>;
  }
  if (looksLikeHtml(content)) {
    return (
      <div
        className="prose prose-neutral max-w-none prose-headings:text-gray-900 prose-p:text-gray-700 prose-li:text-gray-700 text-start"
        dir="auto"
        dangerouslySetInnerHTML={{ __html: content }}
      />
    );
  }
  return (
    <div className="whitespace-pre-wrap text-gray-700 leading-relaxed text-base" dir="auto">
      {content}
    </div>
  );
}

export default function PageFromApi({ apiPath, titleFallbackKey }: Props) {
  const { t, isRtl, locale } = useI18n();
  const [data, setData] = useState<FixedPagePayload | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const settingsHref = isLoggedIn() ? '/profile/settings' : '/settings';
  const backIcon = isRtl ? 'ri-arrow-right-line' : 'ri-arrow-left-line';

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    setError(null);

    void api
      .get<FixedPagePayload>(apiPath)
      .then((res) => {
        if (cancelled) return;
        if (res.key === 'success' && res.data) {
          setData({
            title: typeof res.data.title === 'string' ? res.data.title : '',
            content: typeof res.data.content === 'string' ? res.data.content : '',
          });
        } else {
          setError(res.msg || t('common.error'));
          setData(null);
        }
      })
      .catch(() => {
        if (!cancelled) {
          setError(t('common.error'));
          setData(null);
        }
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });

    return () => {
      cancelled = true;
    };
  }, [apiPath, locale]);

  const displayTitle = (data?.title && data.title.trim() !== '' ? data.title : t(titleFallbackKey)) || '';

  return (
    <div dir={isRtl ? 'rtl' : 'ltr'} className="flex flex-col flex-1">
      <main className="flex-1 max-w-4xl w-full mx-auto px-4 sm:px-6 py-8">
        <div className="flex items-center gap-4 mb-8">
          <Link
            href={settingsHref}
            className="w-10 h-10 flex items-center justify-center bg-white border border-gray-200 rounded-xl hover:bg-gray-50 transition-colors shadow-sm"
            aria-label={t('common.back')}
          >
            <i className={`${backIcon} text-xl text-gray-700`} />
          </Link>
          <h1 className="text-2xl sm:text-3xl font-bold text-[#1e3a5f]">{displayTitle}</h1>
        </div>

        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 sm:p-8">
          {loading && (
            <div className="flex justify-center py-16">
              <div className="w-10 h-10 border-4 border-[#1e3a5f] border-t-transparent rounded-full animate-spin" />
            </div>
          )}
          {!loading && error && (
            <p className="text-red-600 text-center py-8">{error}</p>
          )}
          {!loading && !error && data && <PageBody content={data.content} />}
        </div>
      </main>
    </div>
  );
}
