"use client";

import { useState } from "react";
import { useSearchParams, useRouter } from "next/navigation";

const TIER_NAMES: Record<string, { en: string; ar: string }> = {
  tier1: { en: "Starter", ar: "المبتدئ" },
  tier2: { en: "Professional", ar: "المحترف" },
  tier3: { en: "Business", ar: "الأعمال" },
  tier4: { en: "Enterprise", ar: "المؤسسات" },
  tier5: { en: "Ultimate", ar: "المتكاملة" },
};

const TIER_FEATURES: Record<string, { en: string[]; ar: string[] }> = {
  tier1: {
    en: ["AI Agent for FAQ & Auto-Reply", "Automated Appointment Booking", "Admin Dashboard", "WhatsApp Integration"],
    ar: ["وكيل ذكي للأسئلة الشائعة والردود التلقائية", "حجز المواعيد الآلي", "لوحة تحكم الإدارة", "تكامل واتساب"],
  },
  tier2: {
    en: ["Everything in Starter", "Send & Receive Quotations", "CRM Dashboard", "Google & Third-Party Integrations"],
    ar: ["كل مزايا الباقة المبتدئة", "إرسال واستقبال عروض الأسعار", "لوحة تحكم CRM", "تكاملات جوجل وأطراف ثالثة"],
  },
  tier3: {
    en: ["Everything in Professional", "Multi-Staff Login", "AI Voice Receptionist", "Advanced Scheduling"],
    ar: ["كل مزايا الباقة المحترفة", "تسجيل دخول متعدد للموظفين", "موظفة استقبال صوتية ذكية", "جدولة متقدمة"],
  },
  tier4: {
    en: ["Everything in Business", "Multi-Inbox Social Management", "AI Social Media Assistant", "Dedicated Account Manager"],
    ar: ["كل مزايا باقة الأعمال", "إدارة وسائل التواصل متعددة الصناديق", "مساعد وسائل تواصل اجتماعي ذكي", "مدير حساب مخصص"],
  },
  tier5: {
    en: ["Everything in Enterprise", "AI Lead Generation", "Advanced CRM with Lead Scoring", "24/7 Premium Support"],
    ar: ["كل مزايا باقة المؤسسات", "توليد العملاء المحتملين بالذكاء الاصطناعي", "CRM متقدم مع تقييم العملاء", "دعم متميز على مدار الساعة"],
  },
};

export default function ReactivateContent({ lang }: { lang: string }) {
  const searchParams = useSearchParams();
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const tierId = searchParams.get("tier") || "";
  const period = searchParams.get("period") || "monthly";
  const currency = searchParams.get("currency") || "QAR";

  const isArabic = lang === "ar";
  const tierName = TIER_NAMES[tierId]?.[isArabic ? "ar" : "en"] || tierId;
  const features = TIER_FEATURES[tierId]?.[isArabic ? "ar" : "en"] || [];

  const billingLabel = isArabic
    ? period === "yearly" ? "سنوي" : "شهري"
    : period === "yearly" ? "Yearly" : "Monthly";

  async function handleStartSubscription() {
    setLoading(true);
    setError(null);

    try {
      const res = await fetch("/api/subscriptions/create-checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          tierId,
          billingPeriod: period,
          currency,
          language: lang,
        }),
      });

      const data = await res.json();

      if (!res.ok) {
        // If 401, redirect to login with return URL
        if (res.status === 401) {
          window.location.href = `/${lang}/clerk-login?redirect_url=${encodeURIComponent(window.location.href)}`;
          return;
        }
        setError(data.error || (isArabic ? "حدث خطأ" : "Something went wrong"));
        setLoading(false);
        return;
      }

      if (data.sessionUrl || data.url) {
        window.location.href = data.sessionUrl || data.url;
      } else {
        setError(isArabic ? "لم يتم إنشاء جلسة الدفع" : "Failed to create checkout session");
        setLoading(false);
      }
    } catch {
      setError(isArabic ? "حدث خطأ في الاتصال" : "Connection error");
      setLoading(false);
    }
  }

  return (
    <div
      className="min-h-screen bg-gradient-to-b from-gray-50 to-white flex items-center justify-center px-4"
      dir={isArabic ? "rtl" : "ltr"}
    >
      <div className="max-w-md w-full bg-white rounded-2xl shadow-lg border border-gray-100 p-8">
        <div className="text-center mb-6">
          <div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <svg className="w-8 h-8 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </div>
          <h1 className="text-2xl font-bold text-gray-900 mb-2">
            {isArabic ? "انتهت فترتك التجريبية" : "Your Trial Has Ended"}
          </h1>
          <p className="text-gray-500 text-sm">
            {isArabic ? "لمواصلة استخدام مويدي، يرجى تفعيل اشتراكك" : "To continue using Mawidi, please activate your subscription"}
          </p>
        </div>

        <div className="bg-blue-50 border border-blue-200 rounded-xl p-5 mb-6">
          <div className="flex items-center justify-between mb-3">
            <span className="text-sm font-medium text-blue-600 uppercase tracking-wide">
              {isArabic ? "باقتك المختارة" : "Your Selected Plan"}
            </span>
            <span className="text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded-full">
              {billingLabel}
            </span>
          </div>
          <h2 className="text-xl font-bold text-gray-900 mb-3">{tierName}</h2>
          {features.length > 0 && (
            <ul className="space-y-1.5">
              {features.map((feature, i) => (
                <li key={i} className="flex items-center gap-2 text-sm text-gray-600">
                  <svg className="w-4 h-4 text-blue-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                  </svg>
                  {feature}
                </li>
              ))}
            </ul>
          )}
        </div>

        {error && (
          <div className="bg-red-50 border border-red-200 text-red-700 rounded-lg p-3 mb-4 text-sm text-center">
            {error}
          </div>
        )}

        <button
          onClick={handleStartSubscription}
          disabled={loading || !tierId}
          className="w-full bg-blue-600 hover:bg-blue-700 disabled:bg-gray-300 text-white font-semibold py-3 px-6 rounded-xl transition-colors duration-200"
        >
          {loading
            ? isArabic ? "جاري التحويل..." : "Redirecting to checkout..."
            : isArabic ? "تفعيل الاشتراك" : "Activate Subscription"}
        </button>

        <div className="text-center mt-4">
          <button
            onClick={() => router.push(`/${lang}/pricing`)}
            className="text-sm text-gray-500 hover:text-blue-600 underline transition-colors"
          >
            {isArabic ? "تغيير الباقة" : "Change Plan"}
          </button>
        </div>
      </div>
    </div>
  );
}
