'use client';

import React, { useState, useEffect } from 'react';
import AdminSidebar from '@/components/admin/AdminSidebar';
import {
  Coins,
  Save,
  CheckCircle2,
  RefreshCw,
  Plus,
  Edit2,
  DollarSign,
  Layers,
  Sparkles,
} from 'lucide-react';

export default function AdminPricingPage() {
  const [unitPricings, setUnitPricings] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [savingKey, setSavingKey] = useState<string | null>(null);
  const [savedSuccess, setSavedSuccess] = useState<string | null>(null);

  const fetchPricing = async () => {
    try {
      setLoading(true);
      const res = await fetch('/api/v1/admin/pricing');
      const data = await res.json();
      if (data.success) {
        setUnitPricings(data.data.unitPricings || []);
      }
    } catch {}
    finally {
      setLoading(false);
    }
  };

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

  const handlePriceChange = (itemKey: string, newCost: number) => {
    setUnitPricings((prev) =>
      prev.map((p) => (p.itemKey === itemKey ? { ...p, unitCost: newCost } : p))
    );
  };

  const handleSavePrice = async (p: any) => {
    setSavingKey(p.itemKey);

    try {
      const res = await fetch('/api/v1/admin/pricing', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          itemKey: p.itemKey,
          unitCost: p.unitCost,
          displayName: p.displayName,
          category: p.category,
        }),
      });
      const data = await res.json();
      if (data.success) {
        setSavedSuccess(p.itemKey);
        setTimeout(() => setSavedSuccess(null), 2000);
      }
    } catch {}
    finally {
      setSavingKey(null);
    }
  };

  return (
    <div className="flex min-h-screen bg-[#f8fafc] text-slate-900 font-sans selection:bg-emerald-500/20">
      <AdminSidebar />

      <div className="flex-1 flex flex-col min-w-0">
        <header className="h-16 border-b border-slate-200 bg-white px-6 flex items-center justify-between sticky top-0 z-30 shadow-sm">
          <div className="flex items-center gap-2">
            <span className="w-2 h-2 rounded-full bg-amber-500"></span>
            <span className="text-xs font-bold text-amber-800 font-mono">Dynamic Units Configuration</span>
          </div>
          <button
            onClick={fetchPricing}
            className="px-3.5 py-1.5 bg-slate-50 hover:bg-slate-100 border border-slate-200 text-slate-700 text-xs font-semibold rounded-xl flex items-center gap-1.5 transition-colors"
          >
            <RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
            <span>Refresh</span>
          </button>
        </header>

        <main className="flex-1 p-6 sm:p-8 space-y-6 overflow-y-auto max-w-5xl">
          <div>
            <h1 className="text-xl font-bold text-slate-900 flex items-center gap-2">
              <Coins className="w-6 h-6 text-amber-600" />
              <span>Units & Verification Fee Architecture</span>
            </h1>
            <p className="text-xs text-slate-500 mt-1">
              Configure the units deducted per verification type and the purchase rate per unit for standard and API user tiers.
            </p>
          </div>

          <div className="bg-white rounded-2xl p-6 border border-slate-200/90 shadow-sm space-y-6">
            <div className="space-y-4">
              {unitPricings.map((p) => {
                const isVerificationCost = p.category === 'VERIFICATION_COST';
                return (
                  <div
                    key={p.itemKey}
                    className="p-5 rounded-xl bg-slate-50 border border-slate-200 flex flex-col sm:flex-row sm:items-center justify-between gap-4"
                  >
                    <div className="space-y-1">
                      <div className="flex items-center gap-2">
                        <span className="text-sm font-bold text-slate-900">{p.displayName}</span>
                        <span className="px-2 py-0.5 rounded bg-amber-50 border border-amber-200 text-amber-800 text-[10px] font-mono font-bold">
                          {p.itemKey}
                        </span>
                      </div>
                      <p className="text-xs text-slate-500">
                        {isVerificationCost
                          ? 'Units deducted per query'
                          : 'NGN (₦) purchase price per Unit'}
                      </p>
                    </div>

                    <div className="flex items-center gap-3">
                      <div className="relative">
                        <input
                          type="number"
                          step={isVerificationCost ? '1' : '0.5'}
                          value={p.unitCost}
                          onChange={(e) =>
                            handlePriceChange(p.itemKey, parseFloat(e.target.value) || 0)
                          }
                          className="w-36 bg-white border border-slate-200 rounded-xl px-3 py-1.5 text-xs font-mono font-bold text-amber-700 text-right focus:outline-none focus:border-amber-500 shadow-sm"
                        />
                        <span className="absolute right-10 top-2 text-[10px] text-slate-400 font-mono pointer-events-none">
                          {isVerificationCost ? 'Units' : 'NGN'}
                        </span>
                      </div>

                      <button
                        onClick={() => handleSavePrice(p)}
                        disabled={savingKey === p.itemKey}
                        className="px-4 py-1.5 bg-amber-500 hover:bg-amber-400 text-slate-950 font-bold text-xs rounded-xl shadow-md transition-all flex items-center gap-1.5 disabled:opacity-50"
                      >
                        {savingKey === p.itemKey ? (
                          <RefreshCw className="w-3.5 h-3.5 animate-spin" />
                        ) : savedSuccess === p.itemKey ? (
                          <CheckCircle2 className="w-3.5 h-3.5" />
                        ) : (
                          <Save className="w-3.5 h-3.5" />
                        )}
                        <span>{savedSuccess === p.itemKey ? 'Saved!' : 'Save'}</span>
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </main>
      </div>
    </div>
  );
}
