'use client';

import { useState, useEffect, useCallback } from 'react';
import { Plus, Pencil, Trash2 } from 'lucide-react';
import { minBalanceService, type MinBalanceConfig, type CreateMinBalanceConfigDto, type UpdateMinBalanceConfigDto } from '@/services/min-balance.service';
import { getErrorMessage } from '@/lib/errors';
import { TableSkeleton } from '@/components/priority/skeletons';
import { cn } from '@/lib/utils';
import { Banner, Field, NumberInput, SelectInput, useToasts } from './_shared';

const TYPE_COLORS: Record<string, string> = {
  GLOBAL: 'bg-blue-500/20 text-blue-300',
  BUY: 'bg-emerald-500/20 text-emerald-300',
  SELL: 'bg-amber-500/20 text-amber-300',
  WITHDRAW: 'bg-purple-500/20 text-purple-300',
  TRANSFER: 'bg-cyan-500/20 text-cyan-300',
};

export default function MinBalanceTab({ sysConfig }: any) {
  const [configs, setConfigs] = useState<MinBalanceConfig[]>([]);
  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<MinBalanceConfig | null>(null);
  const [form, setForm] = useState<Partial<CreateMinBalanceConfigDto>>({ actionType: 'BUY', minAmount: '50', currency: sysConfig.currency, isActive: true, maxBuysPerDay: 0, percentageIncrement: 0, maxAmount: 0 });
  const [filter, setFilter] = useState<string>('ALL');

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await minBalanceService.getConfigs({ actionType: filter !== 'ALL' ? filter : undefined, page: 1, limit: 50 });
      setConfigs((res as any).data || []);
    } catch (e: any) { setError(getErrorMessage(e)); }
    finally { setLoading(false); }
  }, [filter, setError]);

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

  const openNew = () => { setEditing(null); setForm({ actionType: 'BUY', minAmount: '50', currency: sysConfig.currency, isActive: true, maxBuysPerDay: 0, percentageIncrement: 0, maxAmount: 0 }); setShowForm(true); };
  const openEdit = (c: MinBalanceConfig) => { setEditing(c); setForm({ actionType: c.actionType, minAmount: c.minAmount.toString(), currency: c.currency, isActive: c.isActive, maxBuysPerDay: c.maxBuysPerDay, percentageIncrement: c.percentageIncrement, maxAmount: c.maxAmount ?? 0 }); setShowForm(true); };

  const save = async () => {
    setSaving(true); setError(null); setSuccess(null);
    try {
      if (editing) {
        const payload: UpdateMinBalanceConfigDto = { actionType: form.actionType, minAmount: form.minAmount, currency: form.currency, isActive: form.isActive, maxBuysPerDay: Number(form.maxBuysPerDay) || 0, percentageIncrement: Number(form.percentageIncrement) || 0, maxAmount: Number(form.maxAmount) || 0 };
        await minBalanceService.updateConfig(editing.id, payload);
        setSuccess('Config updated');
      } else {
        const payload: CreateMinBalanceConfigDto = { actionType: form.actionType!, minAmount: form.minAmount!, currency: form.currency, isActive: form.isActive ?? true, maxBuysPerDay: Number(form.maxBuysPerDay) || 0, percentageIncrement: Number(form.percentageIncrement) || 0, maxAmount: Number(form.maxAmount) || 0 };
        await minBalanceService.createConfig(payload);
        setSuccess('Config created');
      }
      setShowForm(false); load();
    } catch (e: any) { setError(getErrorMessage(e)); }
    finally { setSaving(false); }
  };

  const remove = async (id: string) => {
    if (!confirm('Delete this config?')) return;
    try { await minBalanceService.deleteConfig(id); setSuccess('Config 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">Per-action minimum balance rules, daily buy limits, and percentage increments.</p>
        <div className="flex items-center gap-3">
          <SelectInput value={filter} onChange={(e) => setFilter(e.target.value)} className="!py-1.5 !text-sm">
            <option value="ALL">All Types</option>
            <option value="GLOBAL">GLOBAL</option>
            <option value="BUY">BUY</option>
            <option value="SELL">SELL</option>
            <option value="WITHDRAW">WITHDRAW</option>
            <option value="TRANSFER">TRANSFER</option>
          </SelectInput>
          <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 Config</button>
        </div>
      </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'} Min-Balance Config</h3>
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <Field label="Action Type" required>
              <SelectInput value={form.actionType} onChange={(e) => setForm({ ...form, actionType: e.target.value as any })}>
                <option value="GLOBAL">GLOBAL (applies to all actions)</option>
                <option value="BUY">BUY (buy orders)</option>
                <option value="SELL">SELL (sell orders)</option>
                <option value="WITHDRAW">WITHDRAW</option>
                <option value="TRANSFER">TRANSFER</option>
              </SelectInput>
            </Field>
            <Field label={`Minimum Amount (${sysConfig.currency})`} required>
              <NumberInput step="0.01" min="0" value={form.minAmount} onChange={(e) => setForm({ ...form, minAmount: e.target.value })} />
            </Field>
            <Field label="Currency"><input type="text" value={form.currency} onChange={(e) => setForm({ ...form, currency: e.target.value })} className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white" /></Field>
            <Field label="Max Buys Per Day" hint="0 = unlimited">
              <NumberInput min="0" value={form.maxBuysPerDay} onChange={(e) => setForm({ ...form, maxBuysPerDay: parseInt(e.target.value, 10) || 0 })} />
            </Field>
            <Field label="Percentage Increment (%)" hint="0.5 = 0.5% per buy">
              <NumberInput step="0.01" min="0" value={form.percentageIncrement} onChange={(e) => setForm({ ...form, percentageIncrement: parseFloat(e.target.value) || 0 })} />
            </Field>
            <Field label="Max Buy Amount (0 = unlimited)" hint="Maximum single buy when balance is in this range">
              <NumberInput step="0.01" min="0" value={form.maxAmount} onChange={(e) => setForm({ ...form, maxAmount: parseFloat(e.target.value) || 0 })} />
            </Field>
            <div className="flex items-center gap-2 pt-6">
              <input id="mb-active" type="checkbox" checked={!!form.isActive} onChange={(e) => setForm({ ...form, isActive: e.target.checked })} className="h-4 w-4 rounded" />
              <label htmlFor="mb-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={4} /> : configs.length === 0 ? <p className="rounded-lg border border-white/10 bg-slate-900/30 p-6 text-center text-sm text-slate-400">No configs 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">Action</th><th className="px-3 py-2">Min</th><th className="px-3 py-2">Max</th><th className="px-3 py-2">Max Buys/Day</th><th className="px-3 py-2">% Increment</th><th className="px-3 py-2">Status</th><th className="px-3 py-2">Actions</th>
            </tr></thead>
            <tbody>
              {configs.map((c) => (
                <tr key={c.id} className="border-b border-white/5">
                  <td className="px-3 py-3"><span className={cn('rounded-full px-2 py-1 text-xs font-medium', TYPE_COLORS[c.actionType] || 'bg-slate-500/20 text-slate-300')}>{c.actionType}</span></td>
                   <td className="px-3 py-3 text-slate-300 font-mono">{Number(c.minAmount).toFixed(2)} {c.currency}</td>
                   <td className="px-3 py-3 text-slate-300 font-mono">{c.maxAmount ? `${Number(c.maxAmount).toFixed(2)} ${c.currency}` : <span className="text-slate-500">Unlimited</span>}</td>
                   <td className="px-3 py-3 text-slate-300">{c.maxBuysPerDay > 0 ? c.maxBuysPerDay : <span className="text-slate-500">Unlimited</span>}</td>
                  <td className="px-3 py-3 text-slate-300">{Number(c.percentageIncrement) > 0 ? `${Number(c.percentageIncrement)}%` : <span className="text-slate-500">0%</span>}</td>
                  <td className="px-3 py-3"><span className={cn('rounded-full px-2 py-1 text-xs', c.isActive ? 'bg-emerald-500/20 text-emerald-300' : 'bg-red-500/20 text-red-300')}>{c.isActive ? 'Active' : 'Inactive'}</span></td>
                  <td className="px-3 py-3 flex gap-2">
                    <button onClick={() => openEdit(c)} className="rounded-lg p-1 text-blue-400 hover:bg-blue-500/10"><Pencil className="h-4 w-4" /></button>
                    <button onClick={() => remove(c.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>
  );
}
