'use client';

import { useState, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { formatDateDDMMYYYY } from '@/lib/utils';

// ─── Step types ───────────────────────────────────────────────────────────────
type Step = 1 | 2 | 3 | 4 | 5;

interface WizardState {
  eulaAccepted: boolean;
  licenseKey: string;
  licenseInfo: {
    customerName: string;
    edition: string;
    expiresAt: string;
    daysRemaining: number;
    maxUsers: number;
  } | null;
  appName: string;
  appCurrency: string;
  adminUsername: string;
  adminPassword: string;
  adminPasswordConfirm: string;
  adminDisplayName: string;
}

const EULA_TEXT = `AGREEMENT DE LICENCE UTILISATEUR FINAL (CLUF)

Ce logiciel ("Le Système") est protégé par les droits d'auteur et les lois sur la propriété intellectuelle.

1. LICENCE D'UTILISATION
   Cette licence vous accorde le droit non exclusif et non transférable d'utiliser le logiciel sur le nombre d'appareils spécifié dans votre licence.

2. RESTRICTIONS
   Vous n'êtes PAS autorisé à :
   - Copier, modifier, distribuer ou revendre ce logiciel
   - Procéder à la rétro-ingénierie (reverse engineering) du code
   - Transférer la licence à un tiers sans autorisation écrite
   - Utiliser le logiciel au-delà de la période de licence achetée
   - Supprimer ou modifier les mentions de droit d'auteur

3. PROPRIÉTÉ INTELLECTUELLE
   Tous les droits, titres et intérêts dans le logiciel, y compris les droits de propriété intellectuelle, appartiennent exclusivement au fournisseur.

4. RÉSILIATION
   Cette licence est automatiquement résiliée si vous enfreignez l'un de ses termes. En cas de résiliation, vous devez cesser d'utiliser le logiciel et supprimer toutes les copies.

5. LIMITATION DE RESPONSABILITÉ
   Le fournisseur ne pourra être tenu responsable des dommages indirects, accessoires ou consécutifs résultant de l'utilisation ou de l'impossibilité d'utiliser le logiciel.

6. CONFIDENTIALITÉ
   Vous acceptez de maintenir la confidentialité de vos identifiants de licence et de ne pas les partager avec des tiers non autorisés.

7. LOI APPLICABLE
   Ce contrat est régi par les lois en vigueur dans le pays du fournisseur.

En activant et utilisant ce logiciel, vous confirmez avoir lu, compris et accepté tous les termes de cet accord.`;

// ─── Step indicators ──────────────────────────────────────────────────────────
const STEPS = [
  { number: 1, label: 'اتفاقية الترخيص' },
  { number: 2, label: 'مفتاح الترخيص' },
  { number: 3, label: 'معلومات النظام' },
  { number: 4, label: 'حساب المدير' },
  { number: 5, label: 'إطلاق النظام' },
];

// ─── Component ────────────────────────────────────────────────────────────────
export default function SetupWizardPage() {
  const router = useRouter();
  const [step, setStep] = useState<Step>(1);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const eulaRef = useRef<HTMLDivElement>(null);
  const [eulaScrolled, setEulaScrolled] = useState(false);

  const [state, setState] = useState<WizardState>({
    eulaAccepted: false,
    licenseKey: '',
    licenseInfo: null,
    appName: '',
    appCurrency: 'ILS',
    adminUsername: '',
    adminPassword: '',
    adminPasswordConfirm: '',
    adminDisplayName: '',
  });

  const set = (partial: Partial<WizardState>) => setState((s) => ({ ...s, ...partial }));

  // ── EULA scroll handler ──
  const handleEulaScroll = () => {
    const el = eulaRef.current;
    if (!el) return;
    if (el.scrollTop + el.clientHeight >= el.scrollHeight - 20) {
      setEulaScrolled(true);
    }
  };

  // ── Validate license ──
  const handleValidateLicense = async () => {
    if (!state.licenseKey.trim()) { setError('أدخل مفتاح الترخيص'); return; }
    setLoading(true); setError('');
    try {
      const res = await fetch('/api/setup/validate-license', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ licenseKey: state.licenseKey }),
      });
      const data = await res.json();
      if (!data.valid) { setError(data.error ?? 'مفتاح الترخيص غير صالح'); }
      else {
        set({ licenseInfo: {
          customerName: data.customerName,
          edition: data.edition,
          expiresAt: data.expiresAt,
          daysRemaining: data.daysRemaining,
          maxUsers: data.maxUsers,
        }});
      }
    } catch { setError('فشل التحقق من المفتاح. تأكد من الاتصال.'); }
    finally { setLoading(false); }
  };

  // ── Navigation guards ──
  const canProceed = (): boolean => {
    if (step === 1) return state.eulaAccepted;
    if (step === 2) return !!state.licenseInfo;
    if (step === 3) return state.appName.trim().length >= 2;
    if (step === 4) {
      return (
        state.adminUsername.trim().length >= 3 &&
        state.adminPassword.length >= 6 &&
        state.adminPassword === state.adminPasswordConfirm &&
        state.adminDisplayName.trim().length >= 2
      );
    }
    return true;
  };

  const next = () => { if (canProceed()) { setError(''); setStep((s) => (s < 5 ? (s + 1) as Step : s)); } };
  const back = () => { setError(''); setStep((s) => (s > 1 ? (s - 1) as Step : s)); };

  // ── Final submit ──
  const handleLaunch = async () => {
    setLoading(true); setError('');
    try {
      const res = await fetch('/api/setup/complete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          licenseKey: state.licenseKey,
          appName: state.appName,
          appCurrency: state.appCurrency,
          adminUsername: state.adminUsername,
          adminPassword: state.adminPassword,
          adminDisplayName: state.adminDisplayName,
          eulaAcceptedAt: new Date().toISOString(),
        }),
      });
      const data = await res.json();
      if (!data.success) { setError(data.error ?? 'فشل الإعداد'); }
      else { router.replace('/'); }
    } catch { setError('حدث خطأ أثناء الإعداد. حاول مرة أخرى.'); }
    finally { setLoading(false); }
  };

  // ─── Render ───────────────────────────────────────────────────────────────
  return (
    <div className="w-full max-w-2xl">
      {/* Header */}
      <div className="text-center mb-8">
        <div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-blue-600 mb-4">
          <svg className="w-8 h-8 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
          </svg>
        </div>
        <h1 className="text-2xl font-bold text-white">إعداد النظام</h1>
        <p className="text-slate-400 text-sm mt-1">اتبع الخطوات لتهيئة النظام لأول مرة</p>
      </div>

      {/* Step indicators */}
      <div className="flex items-center justify-between mb-8 px-2">
        {STEPS.map((s, i) => (
          <div key={s.number} className="flex items-center flex-1">
            <div className="flex flex-col items-center">
              <div className={`w-9 h-9 rounded-full flex items-center justify-center text-sm font-bold transition-all
                ${step === s.number ? 'bg-blue-600 text-white ring-4 ring-blue-600/30' :
                  step > s.number ? 'bg-green-600 text-white' : 'bg-slate-700 text-slate-400'}`}>
                {step > s.number ? '✓' : s.number}
              </div>
              <span className={`text-xs mt-1 text-center hidden sm:block transition-colors
                ${step === s.number ? 'text-blue-400' : step > s.number ? 'text-green-400' : 'text-slate-500'}`}>
                {s.label}
              </span>
            </div>
            {i < STEPS.length - 1 && (
              <div className={`h-0.5 flex-1 mx-2 transition-colors ${step > s.number ? 'bg-green-600' : 'bg-slate-700'}`} />
            )}
          </div>
        ))}
      </div>

      {/* Card */}
      <div className="bg-slate-800 rounded-2xl shadow-2xl border border-slate-700 p-8">

        {/* ── Step 1: EULA ── */}
        {step === 1 && (
          <div>
            <h2 className="text-lg font-semibold text-white mb-2">اتفاقية ترخيص المستخدم النهائي</h2>
            <p className="text-slate-400 text-sm mb-4">يرجى قراءة الاتفاقية كاملةً قبل المتابعة</p>
            <div
              ref={eulaRef}
              onScroll={handleEulaScroll}
              className="h-56 overflow-y-auto bg-slate-900 rounded-xl p-4 text-slate-300 text-sm leading-relaxed border border-slate-700 mb-5 whitespace-pre-line font-mono"
            >
              {EULA_TEXT}
            </div>
            {!eulaScrolled && (
              <p className="text-amber-400 text-xs mb-3 flex items-center gap-1">
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                اقرأ الاتفاقية حتى النهاية لتفعيل خانة الموافقة
              </p>
            )}
            <label className="flex items-center gap-3 cursor-pointer group">
              <input
                type="checkbox"
                disabled={!eulaScrolled}
                checked={state.eulaAccepted}
                onChange={(e) => set({ eulaAccepted: e.target.checked })}
                className="w-5 h-5 rounded accent-blue-600 disabled:opacity-40"
              />
              <span className={`text-sm ${eulaScrolled ? 'text-white' : 'text-slate-500'}`}>
                أوافق على جميع بنود اتفاقية الترخيص
              </span>
            </label>
          </div>
        )}

        {/* ── Step 2: License Key ── */}
        {step === 2 && (
          <div>
            <h2 className="text-lg font-semibold text-white mb-2">مفتاح الترخيص</h2>
            <p className="text-slate-400 text-sm mb-5">أدخل مفتاح الترخيص الذي حصلت عليه من المورد</p>
            <div className="flex gap-2 mb-4">
              <input
                type="text"
                value={state.licenseKey}
                onChange={(e) => { set({ licenseKey: e.target.value, licenseInfo: null }); setError(''); }}
                placeholder="أدخل مفتاح الترخيص هنا..."
                className="flex-1 bg-slate-900 border border-slate-600 rounded-xl px-4 py-3 text-white text-sm placeholder-slate-500 focus:outline-none focus:border-blue-500 font-mono"
                dir="ltr"
              />
              <button
                onClick={handleValidateLicense}
                disabled={loading || !state.licenseKey.trim()}
                className="px-5 py-3 bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white rounded-xl text-sm font-medium transition-colors"
              >
                {loading ? '...' : 'تحقق'}
              </button>
            </div>

            {state.licenseInfo && (
              <div className="bg-green-900/30 border border-green-700 rounded-xl p-4 mt-3">
                <div className="flex items-center gap-2 mb-3">
                  <svg className="w-5 h-5 text-green-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  <span className="text-green-400 font-medium text-sm">ترخيص صالح</span>
                </div>
                <div className="grid grid-cols-2 gap-2 text-sm">
                  <div><span className="text-slate-400">العميل: </span><span className="text-white">{state.licenseInfo.customerName}</span></div>
                  <div><span className="text-slate-400">النوع: </span><span className="text-white capitalize">{state.licenseInfo.edition === 'local' ? 'محلي' : 'سحابي'}</span></div>
                  <div><span className="text-slate-400">ينتهي: </span><span className="text-white">{formatDateDDMMYYYY(state.licenseInfo.expiresAt)}</span></div>
                  <div><span className="text-slate-400">الأيام المتبقية: </span><span className={`font-bold ${state.licenseInfo.daysRemaining < 30 ? 'text-amber-400' : 'text-green-400'}`}>{state.licenseInfo.daysRemaining}</span></div>
                  <div><span className="text-slate-400">الحد الأقصى للمستخدمين: </span><span className="text-white">{state.licenseInfo.maxUsers}</span></div>
                </div>
              </div>
            )}
          </div>
        )}

        {/* ── Step 3: System Info ── */}
        {step === 3 && (
          <div>
            <h2 className="text-lg font-semibold text-white mb-2">معلومات النظام</h2>
            <p className="text-slate-400 text-sm mb-5">أدخل معلومات شركتك أو مؤسستك</p>
            <div className="space-y-4">
              <div>
                <label className="block text-slate-300 text-sm mb-2">اسم النظام / الشركة *</label>
                <input
                  type="text"
                  value={state.appName}
                  onChange={(e) => set({ appName: e.target.value })}
                  placeholder="مثال: شركة النجوم للتجارة"
                  className="w-full bg-slate-900 border border-slate-600 rounded-xl px-4 py-3 text-white text-sm placeholder-slate-500 focus:outline-none focus:border-blue-500"
                />
              </div>
              <div>
                <label className="block text-slate-300 text-sm mb-2">العملة الرئيسية</label>
                <select
                  value={state.appCurrency}
                  onChange={(e) => set({ appCurrency: e.target.value })}
                  className="w-full bg-slate-900 border border-slate-600 rounded-xl px-4 py-3 text-white text-sm focus:outline-none focus:border-blue-500"
                >
                  <option value="ILS">شيكل إسرائيلي (ILS)</option>
                  <option value="USD">دولار أمريكي (USD)</option>
                  <option value="JOD">دينار أردني (JOD)</option>
                  <option value="SAR">ريال سعودي (SAR)</option>
                  <option value="AED">درهم إماراتي (AED)</option>
                  <option value="EGP">جنيه مصري (EGP)</option>
                  <option value="EUR">يورو (EUR)</option>
                </select>
              </div>
            </div>
          </div>
        )}

        {/* ── Step 4: Admin Account ── */}
        {step === 4 && (
          <div>
            <h2 className="text-lg font-semibold text-white mb-2">حساب المدير</h2>
            <p className="text-slate-400 text-sm mb-5">أنشئ حساب المدير الرئيسي للنظام</p>
            <div className="space-y-4">
              <div>
                <label className="block text-slate-300 text-sm mb-2">الاسم الكامل *</label>
                <input
                  type="text"
                  value={state.adminDisplayName}
                  onChange={(e) => set({ adminDisplayName: e.target.value })}
                  placeholder="مثال: محمد أحمد"
                  className="w-full bg-slate-900 border border-slate-600 rounded-xl px-4 py-3 text-white text-sm placeholder-slate-500 focus:outline-none focus:border-blue-500"
                />
              </div>
              <div>
                <label className="block text-slate-300 text-sm mb-2">اسم المستخدم *</label>
                <input
                  type="text"
                  value={state.adminUsername}
                  onChange={(e) => set({ adminUsername: e.target.value.toLowerCase().replace(/\s/g, '') })}
                  placeholder="admin"
                  className="w-full bg-slate-900 border border-slate-600 rounded-xl px-4 py-3 text-white text-sm placeholder-slate-500 focus:outline-none focus:border-blue-500 font-mono"
                  dir="ltr"
                />
              </div>
              <div>
                <label className="block text-slate-300 text-sm mb-2">كلمة المرور * (6 أحرف على الأقل)</label>
                <input
                  type="password"
                  value={state.adminPassword}
                  onChange={(e) => set({ adminPassword: e.target.value })}
                  placeholder="••••••••"
                  className="w-full bg-slate-900 border border-slate-600 rounded-xl px-4 py-3 text-white text-sm placeholder-slate-500 focus:outline-none focus:border-blue-500"
                  dir="ltr"
                />
              </div>
              <div>
                <label className="block text-slate-300 text-sm mb-2">تأكيد كلمة المرور *</label>
                <input
                  type="password"
                  value={state.adminPasswordConfirm}
                  onChange={(e) => set({ adminPasswordConfirm: e.target.value })}
                  placeholder="••••••••"
                  className={`w-full bg-slate-900 border rounded-xl px-4 py-3 text-white text-sm placeholder-slate-500 focus:outline-none focus:border-blue-500
                    ${state.adminPasswordConfirm && state.adminPassword !== state.adminPasswordConfirm ? 'border-red-500' : 'border-slate-600'}`}
                  dir="ltr"
                />
                {state.adminPasswordConfirm && state.adminPassword !== state.adminPasswordConfirm && (
                  <p className="text-red-400 text-xs mt-1">كلمتا المرور غير متطابقتين</p>
                )}
              </div>
            </div>
          </div>
        )}

        {/* ── Step 5: Launch ── */}
        {step === 5 && (
          <div>
            <h2 className="text-lg font-semibold text-white mb-2">إطلاق النظام</h2>
            <p className="text-slate-400 text-sm mb-6">مراجعة الإعدادات والإطلاق</p>
            <div className="bg-slate-900 rounded-xl p-4 space-y-3 mb-6 text-sm">
              <Row label="اسم النظام" value={state.appName} />
              <Row label="العملة" value={state.appCurrency} />
              <Row label="المدير" value={state.adminDisplayName} />
              <Row label="اسم المستخدم" value={state.adminUsername} />
              <Row label="الترخيص" value={state.licenseInfo?.customerName ?? '-'} />
              <Row label="نوع الترخيص" value={state.licenseInfo?.edition === 'local' ? 'محلي (Local)' : 'سحابي (Cloud)'} />
            </div>
            <div className="bg-blue-900/20 border border-blue-700/50 rounded-xl p-3 text-sm text-blue-300 mb-4">
              <strong>سيقوم النظام بـ:</strong>
              <ul className="mt-1 space-y-1 list-disc list-inside text-blue-300/80">
                <li>تهيئة قاعدة البيانات (migrations)</li>
                <li>إنشاء حساب المدير</li>
                <li>تفعيل الترخيص</li>
                <li>تسجيل الدخول تلقائياً</li>
              </ul>
            </div>
            <button
              onClick={handleLaunch}
              disabled={loading}
              className="w-full py-3.5 bg-green-600 hover:bg-green-700 disabled:opacity-60 text-white rounded-xl font-semibold text-base transition-colors flex items-center justify-center gap-2"
            >
              {loading ? (
                <>
                  <svg className="animate-spin w-5 h-5" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z" />
                  </svg>
                  جارٍ الإعداد...
                </>
              ) : (
                <>
                  <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                  </svg>
                  إطلاق النظام
                </>
              )}
            </button>
          </div>
        )}

        {/* Error message */}
        {error && (
          <div className="mt-4 bg-red-900/30 border border-red-700 rounded-xl px-4 py-3 text-red-300 text-sm flex items-start gap-2">
            <svg className="w-4 h-4 mt-0.5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            {error}
          </div>
        )}

        {/* Navigation */}
        {step < 5 && (
          <div className="flex justify-between mt-8">
            <button
              onClick={back}
              disabled={step === 1}
              className="px-5 py-2.5 bg-slate-700 hover:bg-slate-600 disabled:opacity-30 text-white rounded-xl text-sm transition-colors"
            >
              ← رجوع
            </button>
            <button
              onClick={next}
              disabled={!canProceed()}
              className="px-6 py-2.5 bg-blue-600 hover:bg-blue-700 disabled:opacity-40 text-white rounded-xl text-sm font-medium transition-colors"
            >
              التالي →
            </button>
          </div>
        )}
        {step === 5 && step > 1 && (
          <button
            onClick={back}
            disabled={loading}
            className="mt-4 px-5 py-2 bg-slate-700 hover:bg-slate-600 disabled:opacity-30 text-white rounded-xl text-sm transition-colors"
          >
            ← رجوع
          </button>
        )}
      </div>
    </div>
  );
}

function Row({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex justify-between">
      <span className="text-slate-400">{label}</span>
      <span className="text-white font-medium">{value}</span>
    </div>
  );
}
