'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { useAuth } from '@/components/auth-provider';
import { callFunction } from '@/lib/firebase';
import { toast } from '@/hooks/use-toast';
import { useLanguage } from '@/hooks/use-language';
import { Shield, Loader2, CheckCircle2, AlertCircle } from 'lucide-react';

export default function AdminSetupPage() {
  const router = useRouter();
  const { user, loading: authLoading } = useAuth();
  const { lang } = useLanguage();
  const isAr = lang === 'ar';
  const [bootstrapping, setBootstrapping] = useState(false);
  const [done, setDone] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleBootstrap = async () => {
    if (!user) {
      router.push('/auth?redirect=/admin/setup');
      return;
    }
    setBootstrapping(true);
    setError(null);
    try {
      await callFunction('bootstrapAdmin')({});
      setDone(true);
      toast({
        title: isAr ? 'تم تعيينك كمدير!' : 'You are now the admin!',
        variant: 'success',
      });
      // Reload to refresh auth context
      setTimeout(() => {
        window.location.href = '/admin';
      }, 1500);
    } catch (err: any) {
      const msg = err?.message || err?.code || 'Failed';
      if (msg.includes('already-exists') || msg.includes('ALREADY_EXISTS')) {
        setError(isAr ? 'يوجد مدير مسجل بالفعل. سجّل دخولك بحساب المدير.' : 'An admin already exists. Log in with the admin account.');
      } else {
        setError(msg);
      }
    } finally {
      setBootstrapping(false);
    }
  };

  if (authLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <Loader2 className="h-8 w-8 animate-spin text-zinc-500" />
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-background px-6" dir={isAr ? 'rtl' : 'ltr'}>
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <div className="h-16 w-16 rounded-2xl bg-indigo-500/10 border border-indigo-500/20 flex items-center justify-center mx-auto mb-4">
            <Shield className="h-8 w-8 text-indigo-400" />
          </div>
          <h1 className="text-2xl font-bold mb-2">
            {isAr ? 'إعداد حساب المدير' : 'Admin Setup'}
          </h1>
          <p className="text-zinc-400 text-sm">
            {isAr
              ? 'هذه الصفحة تتيح لك تعيين أول مدير للنظام. يمكن استخدامها مرة واحدة فقط.'
              : 'This page lets you set the first admin. It can only be used once.'}
          </p>
        </div>

        {!user ? (
          <div className="rounded-2xl border border-zinc-800 bg-zinc-900/30 p-6 text-center">
            <p className="text-zinc-400 text-sm mb-4">
              {isAr ? 'يجب تسجيل الدخول أولاً' : 'You need to sign in first'}
            </p>
            <Link
              href="/auth?redirect=/admin/setup"
              className="inline-flex items-center justify-center h-11 px-6 rounded-xl bg-gradient-to-r from-indigo-500 to-purple-600 text-white font-medium text-sm hover:from-indigo-600 hover:to-purple-700 transition-all"
            >
              {isAr ? 'تسجيل الدخول' : 'Sign In'}
            </Link>
          </div>
        ) : done ? (
          <div className="rounded-2xl border border-emerald-800 bg-emerald-950/20 p-6 text-center">
            <CheckCircle2 className="h-10 w-10 text-emerald-400 mx-auto mb-3" />
            <h2 className="text-lg font-bold text-emerald-300 mb-1">
              {isAr ? 'تم بنجاح!' : 'Success!'}
            </h2>
            <p className="text-zinc-400 text-sm mb-4">
              {isAr ? 'جاري التحويل للوحة الإدارة...' : 'Redirecting to admin panel...'}
            </p>
            <Loader2 className="h-5 w-5 animate-spin text-emerald-400 mx-auto" />
          </div>
        ) : (
          <div className="rounded-2xl border border-zinc-800 bg-zinc-900/30 p-6 space-y-4">
            <div className="text-sm text-zinc-300 space-y-2">
              <p>
                {isAr ? 'الحساب الحالي:' : 'Current account:'}
                <span className="font-mono text-white ms-2">{user.phoneNumber || user.uid}</span>
              </p>
              <p className="text-zinc-500 text-xs">
                {isAr
                  ? 'سيتم تعيين هذا الحساب كمدير النظام. لا يمكن التراجع عن هذه الخطوة إلا من خلال مدير آخر.'
                  : 'This account will become the system admin. This can only be undone by another admin.'}
              </p>
            </div>

            {error && (
              <div className="rounded-xl bg-red-500/10 border border-red-500/30 p-3 text-sm text-red-300 flex items-start gap-2">
                <AlertCircle className="h-4 w-4 mt-0.5 shrink-0" />
                <span>{error}</span>
              </div>
            )}

            <button
              onClick={handleBootstrap}
              disabled={bootstrapping}
              className="w-full h-11 rounded-xl bg-gradient-to-r from-indigo-500 to-purple-600 text-white font-medium text-sm hover:from-indigo-600 hover:to-purple-700 transition-all shadow-md shadow-indigo-500/20 disabled:opacity-50 flex items-center justify-center gap-2"
            >
              {bootstrapping ? (
                <><Loader2 className="h-4 w-4 animate-spin" /> {isAr ? 'جاري التعيين...' : 'Setting up...'}</>
              ) : (
                <><Shield className="h-4 w-4" /> {isAr ? 'تعييني كمدير' : 'Make me Admin'}</>
              )}
            </button>
          </div>
        )}

        <div className="text-center mt-6">
          <Link href="/" className="text-sm text-zinc-500 hover:text-zinc-300 transition-colors">
            {isAr ? 'العودة للرئيسية' : 'Back to Home'}
          </Link>
        </div>
      </div>
    </div>
  );
}
