"use client";

import { useState, useEffect, useCallback } from "react";
import { DollarSign, Plus, Save, RefreshCw, Trash2, GripVertical } from "lucide-react";

interface PricingPlan {
  id: string;
  key: string;
  nameEn: string;
  nameAr: string;
  descEn: string;
  descAr: string;
  priceEn: string;
  priceAr: string;
  currency: string;
  period: string;
  popular: boolean;
  isTrial: boolean;
  isBase: boolean;
  trialDays: number;
  stripePriceId: string;
  instanceLimit: number;
  isActive: boolean;
  featuresEn: string[];
  featuresAr: string[];
  ctaEn: string;
  ctaAr: string;
  sortOrder: number;
}

const emptyPlan = (sortOrder: number): Omit<PricingPlan, "id"> => ({
  key: "",
  nameEn: "",
  nameAr: "",
  descEn: "",
  descAr: "",
  priceEn: "",
  priceAr: "",
  currency: "USD",
  period: "month",
  popular: false,
  isTrial: false,
  isBase: false,
  trialDays: 14,
  stripePriceId: "",
  instanceLimit: 1,
  isActive: true,
  featuresEn: [""],
  featuresAr: [""],
  ctaEn: "Start Free Trial",
  ctaAr: "ابدأ الفترة التجريبية",
  sortOrder
});

export default function AdminPricingPage() {
  const [plans, setPlans] = useState<PricingPlan[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  const fetchPlans = useCallback(async () => {
    try {
      const res = await fetch("/api/landing/pricing");
      if (res.ok) {
        const data = await res.json();
        setPlans(data.plans);
      }
    } catch (err) {
      console.error("Failed to fetch plans:", err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { fetchPlans(); }, [fetchPlans]);

  const showMessage = (type: "success" | "error", text: string) => {
    setMessage({ type, text });
    setTimeout(() => setMessage(null), 5000);
  };

  const updatePlan = (index: number, field: string, value: unknown) => {
    setPlans(prev => prev.map((p, i) => i === index ? { ...p, [field]: value } as PricingPlan : p));
  };

  const updateFeature = (planIndex: number, lang: "en" | "ar", featureIndex: number, value: string) => {
    setPlans(prev => prev.map((p, i) => {
      if (i !== planIndex) return p;
      const key = lang === "en" ? "featuresEn" : "featuresAr";
      const features = [...p[key]];
      features[featureIndex] = value;
      return { ...p, [key]: features };
    }));
  };

  const addFeature = (planIndex: number, lang: "en" | "ar") => {
    setPlans(prev => prev.map((p, i) => {
      if (i !== planIndex) return p;
      const key = lang === "en" ? "featuresEn" : "featuresAr";
      return { ...p, [key]: [...p[key], ""] };
    }));
  };

  const removeFeature = (planIndex: number, lang: "en" | "ar", featureIndex: number) => {
    setPlans(prev => prev.map((p, i) => {
      if (i !== planIndex) return p;
      const key = lang === "en" ? "featuresEn" : "featuresAr";
      return { ...p, [key]: p[key].filter((_, j) => j !== featureIndex) };
    }));
  };

  const addPlan = () => {
    const maxOrder = Math.max(...plans.map(p => p.sortOrder), -1);
    const newPlan = { ...emptyPlan(maxOrder + 1), id: `new-${Date.now()}` } as PricingPlan;
    setPlans(prev => [...prev, newPlan]);
  };

  const removePlan = async (index: number) => {
    const plan = plans[index];
    if (plan.id.startsWith("new-")) {
      setPlans(prev => prev.filter((_, i) => i !== index));
      return;
    }
    try {
      const res = await fetch(`/api/landing/pricing`, {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id: plan.id })
      });
      if (res.ok) {
        setPlans(prev => prev.filter((_, i) => i !== index));
        showMessage("success", "Plan deleted");
      } else {
        showMessage("error", "Failed to delete plan");
      }
    } catch {
      showMessage("error", "Failed to delete plan");
    }
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const res = await fetch("/api/landing/pricing", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ plans })
      });
      if (res.ok) {
        const data = await res.json();
        setPlans(data.plans);
        showMessage("success", "Pricing plans saved successfully");
      } else {
        showMessage("error", "Failed to save pricing plans");
      }
    } catch {
      showMessage("error", "Failed to save pricing plans");
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <RefreshCw className="animate-spin text-brand" size={32} />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-slate-50 text-slate-900">
      <div className="bg-white border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <DollarSign size={28} className="text-slate-700" />
              <div>
                <h1 className="text-2xl font-bold text-slate-900">Pricing Plans</h1>
                <p className="mt-1 text-sm text-slate-600">
                  Manage landing page pricing plans, features, and translations
                </p>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <button
                onClick={addPlan}
                className="px-4 py-2 border border-slate-300 text-slate-700 rounded-md hover:bg-slate-50 flex items-center gap-2 text-sm"
              >
                <Plus size={16} />
                Add Plan
              </button>
              <button
                onClick={handleSave}
                disabled={saving}
                className="px-6 py-2 bg-brand text-white rounded-md hover:opacity-90 disabled:opacity-50 flex items-center gap-2 text-sm"
              >
                <Save size={16} />
                {saving ? "Saving..." : "Save All"}
              </button>
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-6">
        {message && (
          <div className={`p-4 rounded-md ${message.type === "success" ? "bg-green-50 text-green-800" : "bg-red-50 text-red-800"}`}>
            {message.text}
          </div>
        )}

        {plans.map((plan, i) => (
          <div key={plan.id} className="bg-white rounded-lg border">
            <div className="p-6 border-b flex items-center justify-between">
              <div className="flex items-center gap-3">
                <GripVertical size={18} className="text-slate-300" />
                <h2 className="text-lg font-semibold text-slate-900">{plan.nameEn || "New Plan"}</h2>
                {plan.popular && (
                  <span className="px-2 py-0.5 bg-blue-100 text-blue-700 text-xs font-medium rounded-full">Popular</span>
                )}
              </div>
              <button
                onClick={() => removePlan(i)}
                className="p-2 text-red-500 hover:bg-red-50 rounded-md"
                title="Delete plan"
              >
                <Trash2 size={16} />
              </button>
            </div>

            <div className="p-6 space-y-6">
              {/* Key & Order */}
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Plan Key</label>
                  <input
                    value={plan.key}
                    onChange={e => updatePlan(i, "key", e.target.value)}
                    className="w-full px-3 py-2 border rounded-md text-sm text-slate-900 font-mono"
                    placeholder="e.g. starter"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Sort Order</label>
                  <input
                    type="number"
                    value={plan.sortOrder}
                    onChange={e => updatePlan(i, "sortOrder", parseInt(e.target.value) || 0)}
                    className="w-24 px-3 py-2 border rounded-md text-sm text-slate-900"
                  />
                </div>
                <div className="flex items-end pb-2">
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={plan.popular}
                      onChange={e => updatePlan(i, "popular", e.target.checked)}
                      className="w-4 h-4"
                    />
                    <span className="text-sm font-medium text-slate-700">Popular / Highlighted</span>
                  </label>
                </div>
              </div>

              {/* Plan type, trial, limits & Stripe */}
              <div className="border rounded-md p-4 bg-slate-50">
                <h3 className="text-sm font-semibold text-slate-500 mb-3 uppercase tracking-wider">Type · Trial · Limits · Stripe</h3>
                <div className="flex flex-wrap items-center gap-x-6 gap-y-3 mb-4">
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input type="checkbox" checked={plan.isActive} onChange={e => updatePlan(i, "isActive", e.target.checked)} className="w-4 h-4" />
                    <span className="text-sm font-medium text-slate-700">Active (show on landing)</span>
                  </label>
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input type="checkbox" checked={plan.isTrial} onChange={e => updatePlan(i, "isTrial", e.target.checked)} className="w-4 h-4" />
                    <span className="text-sm font-medium text-slate-700">Trial plan</span>
                  </label>
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input type="checkbox" checked={plan.isBase} onChange={e => updatePlan(i, "isBase", e.target.checked)} className="w-4 h-4" />
                    <span className="text-sm font-medium text-slate-700">Base plan (default)</span>
                  </label>
                </div>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">Trial days</label>
                    <input type="number" min={0} value={plan.trialDays} disabled={!plan.isTrial}
                      onChange={e => updatePlan(i, "trialDays", parseInt(e.target.value) || 0)}
                      className="w-full px-3 py-2 border rounded-md text-sm text-slate-900 disabled:bg-slate-100 disabled:text-slate-400" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">Instance limit</label>
                    <input type="number" min={0} value={plan.instanceLimit}
                      onChange={e => updatePlan(i, "instanceLimit", parseInt(e.target.value) || 0)}
                      className="w-full px-3 py-2 border rounded-md text-sm text-slate-900" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">Currency</label>
                    <select value={plan.currency} onChange={e => updatePlan(i, "currency", e.target.value)}
                      className="w-full px-3 py-2 border rounded-md text-sm text-slate-900 bg-white">
                      {["USD", "EGP", "SAR", "AED", "EUR"].map(c => <option key={c} value={c}>{c}</option>)}
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">Billing period</label>
                    <select value={plan.period} onChange={e => updatePlan(i, "period", e.target.value)}
                      className="w-full px-3 py-2 border rounded-md text-sm text-slate-900 bg-white">
                      <option value="month">Monthly</option>
                      <option value="year">Yearly</option>
                      <option value="once">One-time</option>
                    </select>
                  </div>
                </div>
                <div className="mt-4">
                  <label className="block text-sm font-medium text-slate-700 mb-1">Stripe Price ID {plan.isTrial && <span className="text-slate-400">(optional for trial)</span>}</label>
                  <input value={plan.stripePriceId} onChange={e => updatePlan(i, "stripePriceId", e.target.value)}
                    placeholder="price_1AbC..." className="w-full px-3 py-2 border rounded-md text-sm text-slate-900 font-mono" />
                  <p className="mt-1 text-xs text-slate-500">Links this plan to a Stripe recurring price. Paid plans need this for checkout.</p>
                </div>
              </div>

              {/* English Fields */}
              <div className="border rounded-md p-4">
                <h3 className="text-sm font-semibold text-slate-500 mb-3 uppercase tracking-wider">English</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">Plan Name</label>
                    <input value={plan.nameEn} onChange={e => updatePlan(i, "nameEn", e.target.value)} className="w-full px-3 py-2 border rounded-md text-sm text-slate-900" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">Price</label>
                    <input value={plan.priceEn} onChange={e => updatePlan(i, "priceEn", e.target.value)} className="w-full px-3 py-2 border rounded-md text-sm text-slate-900" placeholder="299 or Custom" />
                  </div>
                </div>
                <div className="mt-3">
                  <label className="block text-sm font-medium text-slate-700 mb-1">Description</label>
                  <input value={plan.descEn} onChange={e => updatePlan(i, "descEn", e.target.value)} className="w-full px-3 py-2 border rounded-md text-sm text-slate-900" />
                </div>
                <div className="mt-3">
                  <label className="block text-sm font-medium text-slate-700 mb-1">CTA Button</label>
                  <input value={plan.ctaEn} onChange={e => updatePlan(i, "ctaEn", e.target.value)} className="w-full px-3 py-2 border rounded-md text-sm text-slate-900" />
                </div>
                <div className="mt-3">
                  <label className="block text-sm font-medium text-slate-700 mb-1">Features</label>
                  {plan.featuresEn.map((feat, j) => (
                    <div key={j} className="flex items-center gap-2 mt-2">
                      <input value={feat} onChange={e => updateFeature(i, "en", j, e.target.value)} className="flex-1 px-3 py-2 border rounded-md text-sm text-slate-900" />
                      {plan.featuresEn.length > 1 && (
                        <button onClick={() => removeFeature(i, "en", j)} className="p-1.5 text-red-400 hover:text-red-600">
                          <Trash2 size={14} />
                        </button>
                      )}
                    </div>
                  ))}
                  <button onClick={() => addFeature(i, "en")} className="mt-2 text-sm text-brand hover:underline">+ Add feature</button>
                </div>
              </div>

              {/* Arabic Fields */}
              <div className="border rounded-md p-4" dir="rtl">
                <h3 className="text-sm font-semibold text-slate-500 mb-3 uppercase tracking-wider">العربية</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">اسم الخطة</label>
                    <input value={plan.nameAr} onChange={e => updatePlan(i, "nameAr", e.target.value)} className="w-full px-3 py-2 border rounded-md text-sm text-slate-900" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">السعر</label>
                    <input value={plan.priceAr} onChange={e => updatePlan(i, "priceAr", e.target.value)} className="w-full px-3 py-2 border rounded-md text-sm text-slate-900" />
                  </div>
                </div>
                <div className="mt-3">
                  <label className="block text-sm font-medium text-slate-700 mb-1">الوصف</label>
                  <input value={plan.descAr} onChange={e => updatePlan(i, "descAr", e.target.value)} className="w-full px-3 py-2 border rounded-md text-sm text-slate-900" />
                </div>
                <div className="mt-3">
                  <label className="block text-sm font-medium text-slate-700 mb-1">زر الإجراء</label>
                  <input value={plan.ctaAr} onChange={e => updatePlan(i, "ctaAr", e.target.value)} className="w-full px-3 py-2 border rounded-md text-sm text-slate-900" />
                </div>
                <div className="mt-3">
                  <label className="block text-sm font-medium text-slate-700 mb-1">المميزات</label>
                  {plan.featuresAr.map((feat, j) => (
                    <div key={j} className="flex items-center gap-2 mt-2">
                      <input value={feat} onChange={e => updateFeature(i, "ar", j, e.target.value)} className="flex-1 px-3 py-2 border rounded-md text-sm text-slate-900" />
                      {plan.featuresAr.length > 1 && (
                        <button onClick={() => removeFeature(i, "ar", j)} className="p-1.5 text-red-400 hover:text-red-600">
                          <Trash2 size={14} />
                        </button>
                      )}
                    </div>
                  ))}
                  <button onClick={() => addFeature(i, "ar")} className="mt-2 text-sm text-brand hover:underline">+ أضف ميزة</button>
                </div>
              </div>
            </div>
          </div>
        ))}

        {plans.length === 0 && (
          <div className="text-center py-16 text-slate-500">
            <p className="text-lg">No pricing plans yet.</p>
            <button onClick={addPlan} className="mt-4 px-4 py-2 bg-brand text-white rounded-md text-sm">Create First Plan</button>
          </div>
        )}
      </div>
    </div>
  );
}
