'use client';

import { useState, useEffect, useCallback } from 'react';
import { Plus, Pencil, Trash2 } from 'lucide-react';
import { businessRulesService } from '@/services/business-rules.service';
import { getErrorMessage } from '@/lib/errors';
import { TableSkeleton } from '@/components/priority/skeletons';
import { cn } from '@/lib/utils';
import { Banner, Field, NumberInput, TextInput, useToasts } from './_shared';

export default function TiersTab({ sysConfig }: any) {
  const [tiers, setTiers] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const { error, setError, success, setSuccess, Banners } = useToasts();
  const [showForm, setShowForm] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [form, setForm] = useState<any>({ name: '', minAmount: '', maxAmount: '', bonusPercentage: '0', commissionRate: '', priority: '0', isActive: true, description: '' });

  const load = useCallback(async () => {
    setLoading(true);
    try { setTiers(await businessRulesService.getTiers(true)); }
    catch (e: any) { setError(getErrorMessage(e)); }
    finally { setLoading(false); }
  }, [setError]);

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

  const openNew = () => { setEditing(null); setForm({ name: '', minAmount: '', maxAmount: '', bonusPercentage: '0', commissionRate: '', priority: '0', isActive: true, description: '' }); setShowForm(true); };
  const openEdit = (t: any) => { setEditing(t); setForm({ name: t.name, minAmount: String(t.minAmount), maxAmount: t.maxAmount ? String(t.maxAmount) : '', bonusPercentage: String(t.bonusPercentage ?? 0), commissionRate: t.commissionRate != null ? String(t.commissionRate) : '', priority: String(t.priority ?? 0), isActive: t.isActive, description: t.description ?? '' }); setShowForm(true); };

  const save = async () => {
    setSaving(true); setError(null); setSuccess(null);
    try {
      const payload: any = { name: form.name, minAmount: Number(form.minAmount), maxAmount: form.maxAmount ? Number(form.maxAmount) : null, bonusPercentage: Number(form.bonusPercentage) || 0, commissionRate: form.commissionRate ? Number(form.commissionRate) : null, priority: Number(form.priority) || 0, isActive: !!form.isActive, description: form.description || null, currency: sysConfig.currency };
      if (editing) { await businessRulesService.updateTier(editing.id, payload); setSuccess('Tier updated'); }
      else { await businessRulesService.createTier(payload); setSuccess('Tier created'); }
      setShowForm(false); load();
    } catch (e: any) { setError(getErrorMessage(e)); }
    finally { setSaving(false); }
  };

  const remove = async (id: string) => {
    if (!confirm('Delete this tier?')) return;
    try { await businessRulesService.deleteTier(id); setSuccess('Tier deleted'); load(); }
    catch (e: any) { setError(getErrorMessage(e)); }
  };

  return (
    <div className="space-y-4">
      <Banners />
      <div className="flex items-center justify-between">
        <p className="text-sm text-slate-400">Tiers define the bands users fall into based on cumulative purchases.</p>
        <button onClick={openNew} className="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700"><Plus className="h-4 w-4" />Add Tier</button>
      </div>
      {showForm && (
        <div className="rounded-xl border border-white/10 bg-slate-900/50 p-5">
          <h3 className="mb-4 font-semibold text-white">{editing ? 'Edit' : 'New'} Tier</h3>
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <Field label="Name" required><TextInput value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Beginner" /></Field>
            <Field label={`Min Amount (${sysConfig.currency})`} required><NumberInput step="0.01" value={form.minAmount} onChange={(e) => setForm({ ...form, minAmount: e.target.value })} /></Field>
            <Field label={`Max Amount (${sysConfig.currency})`} hint="Optional. Leave blank for the top tier."><NumberInput step="0.01" value={form.maxAmount} onChange={(e) => setForm({ ...form, maxAmount: e.target.value })} /></Field>
            <Field label="Commission Rate (0-1)" hint="e.g. 0.05 = 5%"><NumberInput step="0.001" min="0" max="1" value={form.commissionRate} onChange={(e) => setForm({ ...form, commissionRate: e.target.value })} /></Field>
            <Field label="Bonus % (0-1)" hint="e.g. 0.02 = 2%"><NumberInput step="0.001" min="0" max="1" value={form.bonusPercentage} onChange={(e) => setForm({ ...form, bonusPercentage: e.target.value })} /></Field>
            <Field label="Priority"><NumberInput value={form.priority} onChange={(e) => setForm({ ...form, priority: e.target.value })} /></Field>
            <div className="md:col-span-2"><Field label="Description"><textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} rows={2} className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white" /></Field></div>
            <div className="md:col-span-2 flex items-center gap-2">
              <input id="tier-active" type="checkbox" checked={!!form.isActive} onChange={(e) => setForm({ ...form, isActive: e.target.checked })} className="h-4 w-4 rounded" />
              <label htmlFor="tier-active" className="text-sm text-slate-300">Active</label>
            </div>
          </div>
          <div className="mt-4 flex gap-2">
            <button onClick={save} disabled={saving} className="rounded-lg bg-emerald-600 px-4 py-2 text-sm font-semibold text-white hover:bg-emerald-700 disabled:opacity-50">{saving ? 'Saving...' : 'Save'}</button>
            <button onClick={() => setShowForm(false)} className="rounded-lg border border-white/10 px-4 py-2 text-sm text-slate-300 hover:bg-white/5">Cancel</button>
          </div>
        </div>
      )}
      {loading ? <TableSkeleton rows={3} /> : tiers.length === 0 ? <p className="rounded-lg border border-white/10 bg-slate-900/30 p-6 text-center text-sm text-slate-400">No tiers configured yet</p> : (
        <div className="overflow-x-auto rounded-xl border border-white/10 bg-slate-900/30">
          <table className="w-full text-sm">
            <thead><tr className="border-b border-white/10 text-left text-slate-400">
              <th className="px-3 py-2">Name</th><th className="px-3 py-2">Min</th><th className="px-3 py-2">Max</th><th className="px-3 py-2">Commission</th><th className="px-3 py-2">Bonus</th><th className="px-3 py-2">Priority</th><th className="px-3 py-2">Status</th><th className="px-3 py-2">Actions</th>
            </tr></thead>
            <tbody>
              {tiers.map((t: any) => (
                <tr key={t.id} className="border-b border-white/5">
                  <td className="px-3 py-3 text-white">{t.name}</td>
                  <td className="px-3 py-3 text-slate-300">{Number(t.minAmount).toFixed(2)} {t.currency || sysConfig.currency}</td>
                  <td className="px-3 py-3 text-slate-300">{t.maxAmount ? Number(t.maxAmount).toFixed(2) + ' ' + (t.currency || sysConfig.currency) : '-'}</td>
                  <td className="px-3 py-3 text-slate-300">{t.commissionRate != null ? (Number(t.commissionRate) * 100).toFixed(1) + '%' : '-'}</td>
                  <td className="px-3 py-3 text-slate-300">{(Number(t.bonusPercentage) * 100).toFixed(1)}%</td>
                  <td className="px-3 py-3 text-slate-300">{t.priority || 0}</td>
                  <td className="px-3 py-3"><span className={cn('rounded-full px-2 py-1 text-xs', t.isActive ? 'bg-emerald-500/20 text-emerald-300' : 'bg-slate-500/20 text-slate-300')}>{t.isActive ? 'Active' : 'Inactive'}</span></td>
                  <td className="px-3 py-3 flex gap-2">
                    <button onClick={() => openEdit(t)} className="rounded-lg p-1 text-blue-400 hover:bg-blue-500/10"><Pencil className="h-4 w-4" /></button>
                    <button onClick={() => remove(t.id)} className="rounded-lg p-1 text-red-400 hover:bg-red-500/10"><Trash2 className="h-4 w-4" /></button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
