'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { api, apiPaths } from '@/lib/api';
import { getUser, isLoggedIn, logout, setUser } from '@/lib/auth';
import type { ApiUser } from '@/lib/auth';
import { useAuthGuard } from '@/lib/useAuthGuard';

export default function AccountPendingPage() {
  const router = useRouter();
  const { checked, authenticated } = useAuthGuard('/login', { requireApproval: false });
  const [checking, setChecking] = useState(false);

  const refreshStatus = () => {
    setChecking(true);
    api.get<ApiUser>(apiPaths.user.profile)
      .then((res) => {
        if (res.key === 'success' && res.data) {
          const u = res.data as ApiUser;
          setUser(u);
          if (u.is_approved === true) {
            router.replace('/');
          }
        }
      })
      .finally(() => setChecking(false));
  };

  useEffect(() => {
    if (!checked || !authenticated) return;
    const u = getUser();
    if (u?.is_approved === true) {
      router.replace('/');
    }
  }, [checked, authenticated, router]);

  useEffect(() => {
    if (!checked || !authenticated) return;
    const t = setInterval(refreshStatus, 30000);
    return () => clearInterval(t);
  }, [checked, authenticated]);

  if (!checked) return null;

  if (!isLoggedIn()) return null;

  return (
    <div dir="rtl" className="min-h-screen bg-gradient-to-br from-amber-50 via-white to-gray-50 flex items-center justify-center px-4">
      <div className="w-full max-w-lg">
        <div className="bg-white rounded-2xl shadow-xl p-8 text-center">
          <div className="w-20 h-20 bg-amber-100 rounded-full flex items-center justify-center mx-auto mb-6">
            <i className="ri-time-line text-4xl text-amber-600"></i>
          </div>
          <h1 className="text-2xl font-bold text-gray-900 mb-3">حسابك قيد المراجعة</h1>
          <p className="text-gray-600 leading-relaxed mb-6">
            تم استلام بياناتك بنجاح. فريق الإدارة يتحقق من حسابك وفق الشروط المعتمدة.
            ستصلك إشعارات عند تفعيل الحساب بالكامل.
          </p>
          <div className="flex flex-col sm:flex-row gap-3 justify-center">
            <button
              type="button"
              onClick={refreshStatus}
              disabled={checking}
              className="inline-flex items-center justify-center gap-2 bg-blue-600 text-white px-6 py-3 rounded-xl font-semibold hover:bg-blue-700 disabled:opacity-60 cursor-pointer"
            >
              {checking ? (
                <span className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
              ) : (
                <i className="ri-refresh-line text-xl"></i>
              )}
              تحديث الحالة
            </button>
            <Link
              href="/profile"
              className="inline-flex items-center justify-center gap-2 border border-gray-200 text-gray-800 px-6 py-3 rounded-xl font-semibold hover:bg-gray-50"
            >
              الملف الشخصي
            </Link>
            <button
              type="button"
              onClick={() => {
                void (async () => {
                  await logout();
                  router.push('/login');
                })();
              }}
              className="inline-flex items-center justify-center text-gray-500 hover:text-gray-800 font-semibold py-3"
            >
              تسجيل الخروج
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
