'use client';

import React, { useState, useEffect } from 'react';
import { Coins, Save, RotateCcw, ShieldCheck, CheckCircle2 } from 'lucide-react';
import SmartAuthCard from '@/components/ui/smartauth/SmartAuthCard';
import SmartAuthButton from '@/components/ui/smartauth/SmartAuthButton';
import SmartAuthBadge from '@/components/ui/smartauth/SmartAuthBadge';

export default function SuperAdminUnitPricingPage() {
  const [pricing, setPricing] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [successMsg, setSuccessMsg] = useState<string | null>(null);

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

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

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

  const handleSave = async () => {
    setSaving(true);
    setSuccessMsg(null);
    try {
      const res = await fetch('/api/v1/admin/pricing', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ pricing }),
      });
      const data = await res.json();
      if (data.success) {
        setSuccessMsg('Unit pricing updated in MySQL database.');
        setTimeout(() => setSuccessMsg(null), 3000);
      }
    } catch {}
    finally {
      setSaving(false);
    }
  };

  return (
    <div className="space-y-7 max-w-4xl animate-in fade-in duration-150">
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-extrabold text-slate-900 tracking-tight">Dynamic Unit Pricing Console</h1>
          <p className="text-xs text-slate-500 mt-1">Configure real-time unit consumption costs per identity lookup.</p>
        </div>
        <SmartAuthButton variant="primary" size="md" icon={Save} loading={saving} onClick={handleSave}>
          Save Pricing Configuration
        </SmartAuthButton>
      </div>

      {successMsg && (
        <div className="p-3 bg-emerald-50 border border-emerald-200 text-emerald-800 rounded-xl text-xs font-semibold">
          {successMsg}
        </div>
      )}

      <SmartAuthCard title="Verification Service Deduction Costs" headerIcon={Coins}>
        <div className="space-y-4">
          {pricing.map((p) => (
            <div key={p.id || p.itemKey} className="p-4 rounded-xl border border-slate-200 flex flex-wrap items-center justify-between gap-4 bg-slate-50/50">
              <div>
                <span className="font-bold text-slate-900 text-xs block">{p.displayName}</span>
                <span className="text-[11px] font-mono text-slate-400">Key: {p.itemKey} • Category: {p.category}</span>
              </div>

              <div className="flex items-center gap-3">
                <input
                  type="number"
                  min={1}
                  max={500}
                  value={p.unitCost}
                  onChange={(e) => handlePriceChange(p.itemKey, parseFloat(e.target.value) || 0)}
                  className="w-24 px-3 py-1.5 text-xs font-mono font-bold rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-emerald-500/20 bg-white"
                />
                <span className="text-xs font-mono font-bold text-slate-600">Units</span>
              </div>
            </div>
          ))}
        </div>
      </SmartAuthCard>
    </div>
  );
}
