"use client";

import { useState, useEffect, useCallback } from "react";

type Prices = { usd: number; lkr: number; eur: number };
type Tier = { name: string; prices: Prices; features: string[] };
type Service = { id: string; name: string; emoji: string; tiers: Tier[] };
type Combo = { id: string; name: string; prices: Prices; saving: string; desc: string; tag: string | null; features: string[] };
type PricingData = { services: Service[]; combos: Combo[] };

const CURRENCIES: { key: keyof Prices; symbol: string; label: string }[] = [
  { key: "usd", symbol: "$", label: "USD" },
  { key: "lkr", symbol: "Rs.", label: "LKR" },
  { key: "eur", symbol: "€", label: "EUR" },
];

const TIER_COLORS: Record<string, { color: string; bg: string; border: string }> = {
  Basic: { color: "#9ca3af", bg: "rgba(156,163,175,0.1)", border: "rgba(156,163,175,0.2)" },
  Pro: { color: "#28c76f", bg: "rgba(40,199,111,0.1)", border: "rgba(40,199,111,0.2)" },
  Enterprise: { color: "#a78bfa", bg: "rgba(167,139,250,0.1)", border: "rgba(167,139,250,0.2)" },
};

export default function AdminPage() {
  const [password, setPassword] = useState("");
  const [authed, setAuthed] = useState(false);
  const [authError, setAuthError] = useState("");
  const [data, setData] = useState<PricingData | null>(null);
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [saveError, setSaveError] = useState("");
  const [activeTab, setActiveTab] = useState<"services" | "combos">("services");

  const fetchData = useCallback(async () => {
    setLoading(true);
    const res = await fetch("/api/pricing");
    setData(await res.json());
    setLoading(false);
  }, []);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setAuthError("");
    const current = await (await fetch("/api/pricing")).json();
    const res = await fetch("/api/pricing", {
      method: "POST",
      headers: { "Content-Type": "application/json", "x-admin-password": password },
      body: JSON.stringify(current),
    });
    if (res.ok) { setAuthed(true); fetchData(); }
    else setAuthError("Invalid password. Please try again.");
  };

  const handleSave = async () => {
    if (!data) return;
    setSaving(true); setSaved(false); setSaveError("");
    const res = await fetch("/api/pricing", {
      method: "POST",
      headers: { "Content-Type": "application/json", "x-admin-password": password },
      body: JSON.stringify(data),
    });
    setSaving(false);
    if (res.ok) { setSaved(true); setTimeout(() => setSaved(false), 3000); }
    else setSaveError("Failed to save.");
  };

  const updatePrice = (sIdx: number, tIdx: number, currency: keyof Prices, value: string) => {
    if (!data) return;
    const d = structuredClone(data);
    d.services[sIdx].tiers[tIdx].prices[currency] = parseFloat(value) || 0;
    setData(d);
  };

  const updateFeature = (sIdx: number, tIdx: number, fIdx: number, value: string) => {
    if (!data) return;
    const d = structuredClone(data);
    d.services[sIdx].tiers[tIdx].features[fIdx] = value;
    setData(d);
  };

  const addFeature = (sIdx: number, tIdx: number) => {
    if (!data) return;
    const d = structuredClone(data);
    d.services[sIdx].tiers[tIdx].features.push("New feature");
    setData(d);
  };

  const removeFeature = (sIdx: number, tIdx: number, fIdx: number) => {
    if (!data) return;
    const d = structuredClone(data);
    d.services[sIdx].tiers[tIdx].features.splice(fIdx, 1);
    setData(d);
  };

  const updateComboPrice = (cIdx: number, currency: keyof Prices, value: string) => {
    if (!data) return;
    const d = structuredClone(data);
    d.combos[cIdx].prices[currency] = parseFloat(value) || 0;
    setData(d);
  };

  const updateComboField = (cIdx: number, field: "saving" | "desc", value: string) => {
    if (!data) return;
    const d = structuredClone(data);
    d.combos[cIdx][field] = value;
    setData(d);
  };

  const updateComboFeature = (cIdx: number, fIdx: number, value: string) => {
    if (!data) return;
    const d = structuredClone(data);
    d.combos[cIdx].features[fIdx] = value;
    setData(d);
  };

  const addComboFeature = (cIdx: number) => {
    if (!data) return;
    const d = structuredClone(data);
    d.combos[cIdx].features.push("New feature");
    setData(d);
  };

  const removeComboFeature = (cIdx: number, fIdx: number) => {
    if (!data) return;
    const d = structuredClone(data);
    d.combos[cIdx].features.splice(fIdx, 1);
    setData(d);
  };

  if (!authed) {
    return (
      <div className="min-h-screen flex items-center justify-center px-4" style={{ background: "#0b0b0b" }}>
        <div className="w-full max-w-sm">
          <div className="text-center mb-8">
            <div className="w-14 h-14 rounded-2xl bg-[#28c76f]/10 text-[#28c76f] flex items-center justify-center mx-auto mb-4 text-2xl">🔐</div>
            <h1 className="text-2xl font-bold text-white mb-1">Admin Panel</h1>
            <p className="text-gray-500 text-sm">Paid2Marketing Pricing Editor</p>
          </div>
          <form onSubmit={handleLogin} className="space-y-4">
            <div>
              <label className="block text-gray-400 text-xs font-medium mb-1.5">Admin Password</label>
              <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Enter password" required
                className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white text-sm placeholder-gray-600 focus:outline-none focus:border-[#28c76f]/50 transition-all" />
            </div>
            {authError && <p className="text-red-400 text-xs bg-red-400/10 border border-red-400/20 rounded-lg px-3 py-2">{authError}</p>}
            <button type="submit" className="w-full py-3 rounded-xl bg-[#28c76f] hover:bg-[#22b965] text-white font-semibold text-sm transition-all shadow-lg shadow-[#28c76f]/20">Sign In</button>
          </form>
          <p className="text-center text-gray-600 text-xs mt-5">Default: <span className="text-gray-400">admin123</span> · Change in <span className="text-gray-400">.env.local</span></p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen" style={{ background: "#0b0b0b" }}>
      {/* Top bar */}
      <header className="sticky top-0 z-40 bg-[#141414]/95 backdrop-blur border-b border-white/10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <span className="text-xl">💰</span>
            <div>
              <p className="text-white font-bold text-sm leading-none">Pricing Editor</p>
              <p className="text-gray-500 text-xs">Paid2Marketing Admin</p>
            </div>
          </div>
          <div className="flex items-center gap-3">
            {saveError && <p className="text-red-400 text-xs">{saveError}</p>}
            {saved && <span className="text-[#28c76f] text-xs font-medium flex items-center gap-1">✓ Saved!</span>}
            <button onClick={handleSave} disabled={saving} className="px-4 py-2 rounded-lg bg-[#28c76f] hover:bg-[#22b965] disabled:opacity-50 text-white text-sm font-semibold transition-all shadow-md shadow-[#28c76f]/20">
              {saving ? "Saving…" : "Save Changes"}
            </button>
            <button onClick={() => { setAuthed(false); setData(null); }} className="px-3 py-2 rounded-lg border border-white/10 text-gray-400 hover:text-white text-xs transition-all">
              Logout
            </button>
          </div>
        </div>
      </header>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {loading ? (
          <div className="flex items-center justify-center py-32">
            <div className="w-8 h-8 border-2 border-[#28c76f]/30 border-t-[#28c76f] rounded-full animate-spin" />
          </div>
        ) : data ? (
          <>
            {/* Tabs */}
            <div className="flex gap-2 mb-8 bg-white/5 p-1 rounded-xl w-fit">
              {(["services", "combos"] as const).map((tab) => (
                <button key={tab} onClick={() => setActiveTab(tab)}
                  className={`px-5 py-2 rounded-lg text-sm font-semibold capitalize transition-all ${activeTab === tab ? "bg-[#28c76f] text-white shadow-md" : "text-gray-400 hover:text-white"}`}>
                  {tab} ({tab === "services" ? data.services.length : data.combos.length})
                </button>
              ))}
            </div>

            {/* Services tab */}
            {activeTab === "services" && (
              <div className="space-y-6">
                {data.services.map((service, sIdx) => (
                  <div key={service.id} className="bg-[#141414] border border-white/8 rounded-2xl overflow-hidden">
                    <div className="px-6 py-4 border-b border-white/8 flex items-center gap-3">
                      <span className="text-2xl">{service.emoji}</span>
                      <h2 className="text-white font-bold text-base">{service.name}</h2>
                    </div>
                    <div className="grid grid-cols-1 lg:grid-cols-3 divide-y lg:divide-y-0 lg:divide-x divide-white/8">
                      {service.tiers.map((tier, tIdx) => {
                        const tc = TIER_COLORS[tier.name];
                        return (
                          <div key={tier.name} className="p-5 space-y-4">
                            <div className="flex items-center gap-2 mb-3">
                              <span className="text-xs font-semibold px-2.5 py-1 rounded-full border" style={{ color: tc.color, background: tc.bg, borderColor: tc.border }}>
                                {tier.name}
                              </span>
                            </div>

                            {/* Multi-currency prices */}
                            <div>
                              <p className="text-gray-500 text-xs font-medium uppercase tracking-wider mb-2">Prices</p>
                              <div className="space-y-2">
                                {CURRENCIES.map(({ key, symbol, label }) => (
                                  <div key={key} className="flex items-center gap-2">
                                    <span className="text-xs font-bold w-8 text-right" style={{ color: tc.color }}>{symbol}</span>
                                    <input type="number" step={key === "lkr" ? "1" : "0.01"} min="0" value={tier.prices[key]}
                                      onChange={(e) => updatePrice(sIdx, tIdx, key, e.target.value)}
                                      className="flex-1 bg-white/5 border border-white/10 rounded-lg px-3 py-1.5 text-white text-sm font-bold focus:outline-none focus:border-[#28c76f]/50 transition-all" />
                                    <span className="text-gray-600 text-xs w-8">{label}</span>
                                  </div>
                                ))}
                              </div>
                            </div>

                            {/* Features */}
                            <div>
                              <p className="text-gray-500 text-xs font-medium uppercase tracking-wider mb-2">Features</p>
                              <div className="space-y-1.5">
                                {tier.features.map((feature, fIdx) => (
                                  <div key={fIdx} className="flex items-center gap-2">
                                    <svg className="w-3 h-3 text-[#28c76f] flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" /></svg>
                                    <input type="text" value={feature} onChange={(e) => updateFeature(sIdx, tIdx, fIdx, e.target.value)}
                                      className="flex-1 bg-white/5 border border-white/8 rounded-lg px-2.5 py-1.5 text-gray-300 text-xs focus:outline-none focus:border-[#28c76f]/50 transition-all" />
                                    <button onClick={() => removeFeature(sIdx, tIdx, fIdx)} className="text-gray-600 hover:text-red-400 transition-colors" title="Remove">
                                      <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>
                                    </button>
                                  </div>
                                ))}
                              </div>
                              <button onClick={() => addFeature(sIdx, tIdx)} className="mt-2 w-full text-xs text-[#28c76f] hover:text-[#22b965] border border-dashed border-[#28c76f]/30 hover:border-[#28c76f]/60 rounded-lg py-1.5 transition-all">+ Add feature</button>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                ))}
              </div>
            )}

            {/* Combos tab */}
            {activeTab === "combos" && (
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                {data.combos.map((combo, cIdx) => (
                  <div key={combo.id} className={`bg-[#141414] rounded-2xl overflow-hidden border ${combo.tag ? "border-[#28c76f]/40" : "border-white/8"}`}>
                    <div className="px-5 py-4 border-b border-white/8 flex items-center gap-2">
                      <h2 className="text-white font-bold text-base">{combo.name}</h2>
                      {combo.tag && <span className="text-xs px-2 py-0.5 rounded-full bg-[#28c76f] text-white font-medium">{combo.tag}</span>}
                    </div>
                    <div className="p-5 space-y-4">
                      {/* Multi-currency prices */}
                      <div>
                        <p className="text-gray-500 text-xs font-medium uppercase tracking-wider mb-2">Monthly Prices</p>
                        <div className="space-y-2">
                          {CURRENCIES.map(({ key, symbol, label }) => (
                            <div key={key} className="flex items-center gap-2">
                              <span className="text-xs font-bold w-8 text-right text-[#28c76f]">{symbol}</span>
                              <input type="number" step={key === "lkr" ? "1" : "0.01"} min="0" value={combo.prices[key]}
                                onChange={(e) => updateComboPrice(cIdx, key, e.target.value)}
                                className="flex-1 bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-white text-base font-bold focus:outline-none focus:border-[#28c76f]/50 transition-all" />
                              <span className="text-gray-600 text-xs w-8">{label}</span>
                            </div>
                          ))}
                        </div>
                      </div>

                      <div>
                        <label className="block text-gray-500 text-xs font-medium uppercase tracking-wider mb-1.5">Saving Badge</label>
                        <input type="text" value={combo.saving} onChange={(e) => updateComboField(cIdx, "saving", e.target.value)}
                          className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-[#28c76f] text-sm font-medium focus:outline-none focus:border-[#28c76f]/50 transition-all" />
                      </div>

                      <div>
                        <label className="block text-gray-500 text-xs font-medium uppercase tracking-wider mb-1.5">Description</label>
                        <input type="text" value={combo.desc} onChange={(e) => updateComboField(cIdx, "desc", e.target.value)}
                          className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-gray-300 text-sm focus:outline-none focus:border-[#28c76f]/50 transition-all" />
                      </div>

                      <div>
                        <label className="block text-gray-500 text-xs font-medium uppercase tracking-wider mb-2">Features</label>
                        <div className="space-y-1.5">
                          {combo.features.map((feature, fIdx) => (
                            <div key={fIdx} className="flex items-center gap-2">
                              <svg className="w-3 h-3 text-[#28c76f] flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" /></svg>
                              <input type="text" value={feature} onChange={(e) => updateComboFeature(cIdx, fIdx, e.target.value)}
                                className="flex-1 bg-white/5 border border-white/8 rounded-lg px-2.5 py-1.5 text-gray-300 text-xs focus:outline-none focus:border-[#28c76f]/50 transition-all" />
                              <button onClick={() => removeComboFeature(cIdx, fIdx)} className="text-gray-600 hover:text-red-400 transition-colors">
                                <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>
                              </button>
                            </div>
                          ))}
                        </div>
                        <button onClick={() => addComboFeature(cIdx)} className="mt-2 w-full text-xs text-[#28c76f] hover:text-[#22b965] border border-dashed border-[#28c76f]/30 hover:border-[#28c76f]/60 rounded-lg py-1.5 transition-all">+ Add feature</button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}

            {/* Sticky save bar */}
            <div className="sticky bottom-6 mt-10 flex justify-end">
              <button onClick={handleSave} disabled={saving} className="px-8 py-3 rounded-xl bg-[#28c76f] hover:bg-[#22b965] disabled:opacity-50 text-white font-semibold text-sm transition-all shadow-xl shadow-[#28c76f]/30 hover:-translate-y-0.5">
                {saving ? "Saving…" : saved ? "✓ Saved!" : "Save All Changes"}
              </button>
            </div>
          </>
        ) : null}
      </div>
    </div>
  );
}
