"use client";

import { useState } from "react";
import {
  X,
  Users,
  Minus,
  Plus,
  CreditCard,
  Loader2,
  CheckCircle,
  ShieldCheck,
} from "lucide-react";
import type { Lang } from "@/lib/config";
import { ADDITIONAL_SEAT_PRICE_ANNUAL_QAR } from "@/lib/types/organization.types";

interface PurchaseSeatsModalProps {
  lang: Lang;
  isOpen: boolean;
  onClose: () => void;
  currentSeats: number;
  onSuccess?: () => void;
}

export default function PurchaseSeatsModal({
  lang,
  isOpen,
  onClose,
  currentSeats,
  onSuccess,
}: PurchaseSeatsModalProps) {
  const isAr = lang === "ar";
  const [quantity, setQuantity] = useState(1);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const t = {
    title: isAr ? "شراء مقاعد إضافية" : "Purchase Additional Seats",
    subtitle: isAr
      ? "أضف أعضاء فريق إضافيين إلى مؤسستك"
      : "Add more team members to your organization",
    seatQuantity: isAr ? "عدد المقاعد" : "Number of Seats",
    pricePerSeat: isAr ? "سعر المقعد الواحد" : "Price per Seat",
    perYear: isAr ? "/سنة" : "/year",
    totalPrice: isAr ? "المجموع السنوي" : "Annual Total",
    currentSeats: isAr ? "المقاعد الحالية" : "Current Seats",
    newTotal: isAr ? "المجموع الجديد" : "New Total",
    seats: isAr ? "مقاعد" : "seats",
    checkout: isAr ? "الدفع الآن" : "Proceed to Checkout",
    cancel: isAr ? "إلغاء" : "Cancel",
    securePayment: isAr ? "دفع آمن عبر Stripe" : "Secure payment via Stripe",
    benefits: isAr ? "المزايا المشمولة" : "Included Benefits",
    benefit1: isAr
      ? "الوصول الفوري للأعضاء الجدد"
      : "Instant access for new members",
    benefit2: isAr
      ? "إدارة الأدوار والصلاحيات"
      : "Role and permission management",
    benefit3: isAr ? "سجل نشاط الفريق" : "Team activity tracking",
    benefit4: isAr ? "دعم فني على مدار الساعة" : "24/7 technical support",
    error: isAr ? "فشل إنشاء جلسة الدفع" : "Failed to create checkout session",
  };

  const pricePerSeat = ADDITIONAL_SEAT_PRICE_ANNUAL_QAR;
  const totalPrice = quantity * pricePerSeat;

  const handleQuantityChange = (delta: number) => {
    const newQuantity = quantity + delta;
    if (newQuantity >= 1 && newQuantity <= 20) {
      setQuantity(newQuantity);
    }
  };

  const handleCheckout = async () => {
    try {
      setLoading(true);
      setError(null);

      const response = await fetch("/api/organization/seats/purchase", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ quantity }),
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || "Failed to create checkout session");
      }

      const { url } = await response.json();

      if (url) {
        window.location.href = url;
      } else {
        throw new Error("No checkout URL returned");
      }
    } catch (err) {
      console.error("Checkout error:", err);
      setError(err instanceof Error ? err.message : t.error);
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
      <div
        className="bg-white rounded-2xl shadow-2xl w-full max-w-lg mx-4 overflow-hidden border border-slate-200"
        dir={isAr ? "rtl" : "ltr"}
      >
        {/* Header */}
        <div className="px-6 py-4 border-b border-slate-200 bg-gradient-to-r from-brand-green/10 to-emerald-50 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-brand-green rounded-xl">
              <Users className="w-5 h-5 text-white" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-slate-900">
                {t.title}
              </h3>
              <p className="text-sm text-slate-500">{t.subtitle}</p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-lg transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="p-6 space-y-6">
          {/* Quantity Selector */}
          <div className="bg-slate-50 rounded-xl p-5">
            <label className="block text-sm font-medium text-slate-700 mb-3">
              {t.seatQuantity}
            </label>
            <div className="flex items-center justify-center gap-4">
              <button
                onClick={() => handleQuantityChange(-1)}
                disabled={quantity <= 1}
                className="w-12 h-12 flex items-center justify-center rounded-xl border-2 border-slate-200 bg-white text-slate-600 hover:border-brand-green hover:text-brand-green transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <Minus className="w-5 h-5" />
              </button>
              <div className="w-24 text-center">
                <span className="text-4xl font-bold text-slate-900">
                  {quantity}
                </span>
                <p className="text-sm text-slate-500 mt-1">{t.seats}</p>
              </div>
              <button
                onClick={() => handleQuantityChange(1)}
                disabled={quantity >= 20}
                className="w-12 h-12 flex items-center justify-center rounded-xl border-2 border-slate-200 bg-white text-slate-600 hover:border-brand-green hover:text-brand-green transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <Plus className="w-5 h-5" />
              </button>
            </div>
          </div>

          {/* Pricing Summary */}
          <div className="space-y-3">
            <div className="flex items-center justify-between text-sm">
              <span className="text-slate-600">{t.pricePerSeat}</span>
              <span className="font-medium text-slate-900">
                {pricePerSeat} {isAr ? "ر.ق" : "QAR"}
                {t.perYear}
              </span>
            </div>
            <div className="flex items-center justify-between text-sm">
              <span className="text-slate-600">{t.currentSeats}</span>
              <span className="font-medium text-slate-900">{currentSeats}</span>
            </div>
            <div className="flex items-center justify-between text-sm">
              <span className="text-slate-600">{t.newTotal}</span>
              <span className="font-medium text-brand-green">
                {currentSeats + quantity} {t.seats}
              </span>
            </div>
            <div className="border-t border-slate-200 pt-3 flex items-center justify-between">
              <span className="font-semibold text-slate-900">
                {t.totalPrice}
              </span>
              <span className="text-2xl font-bold text-brand-green">
                {totalPrice} {isAr ? "ر.ق" : "QAR"}
              </span>
            </div>
          </div>

          {/* Benefits */}
          <div className="bg-emerald-50 rounded-xl p-4">
            <h4 className="text-sm font-semibold text-emerald-800 mb-2 flex items-center gap-2">
              <CheckCircle className="w-4 h-4" />
              {t.benefits}
            </h4>
            <ul className="space-y-1.5 text-sm text-emerald-700">
              <li className="flex items-center gap-2">
                <span className="w-1.5 h-1.5 rounded-full bg-emerald-500" />
                {t.benefit1}
              </li>
              <li className="flex items-center gap-2">
                <span className="w-1.5 h-1.5 rounded-full bg-emerald-500" />
                {t.benefit2}
              </li>
              <li className="flex items-center gap-2">
                <span className="w-1.5 h-1.5 rounded-full bg-emerald-500" />
                {t.benefit3}
              </li>
              <li className="flex items-center gap-2">
                <span className="w-1.5 h-1.5 rounded-full bg-emerald-500" />
                {t.benefit4}
              </li>
            </ul>
          </div>

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

        {/* Footer */}
        <div className="px-6 py-4 border-t border-slate-200 bg-slate-50">
          <div className="flex items-center justify-between gap-4">
            <div className="flex items-center gap-2 text-xs text-slate-500">
              <ShieldCheck className="w-4 h-4" />
              {t.securePayment}
            </div>
            <div className="flex items-center gap-3">
              <button
                onClick={onClose}
                className="px-4 py-2.5 text-slate-600 hover:text-slate-800 hover:bg-slate-100 rounded-lg transition-colors font-medium"
              >
                {t.cancel}
              </button>
              <button
                onClick={handleCheckout}
                disabled={loading}
                className="flex items-center gap-2 px-5 py-2.5 bg-gradient-to-r from-brand-green to-emerald-600 text-white rounded-xl font-medium shadow-lg shadow-brand-green/25 hover:shadow-xl hover:shadow-brand-green/30 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {loading ? (
                  <Loader2 className="w-5 h-5 animate-spin" />
                ) : (
                  <CreditCard className="w-5 h-5" />
                )}
                {t.checkout}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
