import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Form, useLoaderData } from "@remix-run/react";
import { requireAuthLevel } from "~/lib/auth-helpers.server";
import { AUTH_LEVELS } from "~/types/auth";

export async function loader({ request }: LoaderFunctionArgs) {
  // Only superadmins can access this route
  const user = await requireAuthLevel(request, AUTH_LEVELS.SUPERADMIN);
  
  return json({ user });
}

export async function action({ request }: ActionFunctionArgs) {
  // Only superadmins can perform this action
  await requireAuthLevel(request, AUTH_LEVELS.SUPERADMIN);
  
  const formData = await request.formData();
  const action = formData.get("action");
  
  if (action === "enable_signup") {
    // Redirect to signup with a special parameter that bypasses the check
    return redirect("/signup?admin_override=true");
  }
  
  return redirect("/admin/enable-signup");
}

export default function EnableSignup() {
  const { user } = useLoaderData<typeof loader>();
  
  return (
    <div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8" dir="rtl">
      <div className="max-w-md mx-auto">
        <div className="bg-white shadow rounded-lg p-6">
          <h2 className="text-lg font-medium text-gray-900 mb-4">
            تفعيل التسجيل للمسؤولين
          </h2>
          <p className="text-sm text-gray-600 mb-6">
            مرحباً {user.name}، يمكنك تفعيل صفحة التسجيل مؤقتاً لإنشاء حسابات جديدة.
          </p>
          
          <Form method="post">
            <button
              type="submit"
              name="action"
              value="enable_signup"
              className="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-md"
            >
              الانتقال إلى صفحة التسجيل
            </button>
          </Form>
          
          <div className="mt-4">
            <a
              href="/dashboard"
              className="text-sm text-blue-600 hover:text-blue-500"
            >
              العودة إلى لوحة التحكم
            </a>
          </div>
        </div>
      </div>
    </div>
  );
}