'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, SelectInput, useToasts } from './_shared';

export default function CommissionRangesTab({ sysConfig }: any) {
  const [ranges, setRanges] = 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: '', description: '', minAmount: '', maxAmount: '', commissionType: 'PERCENTAGE', percentage: '', flatFee: '', currency: sysConfig.currency, priority: '0', isActive: true });

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

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

  const openNew = () => { setEditing(null); setForm({ name: '', description: '', minAmount: '', maxAmount: '', commissionType: 'PERCENTAGE', percentage: '', flatFee: '', currency: sysConfig.currency, priority: '0', isActive: true }); setShowForm(true); };
  const openEdit = (r: any) => { setEditing(r); setForm({ name: r.name, description: r.description || '', minAmount: String(r.minAmount), maxAmount: r.maxAmount ? String(r.maxAmount) : '', commissionType: r.commissionType, percentage: r.percentage != null ? String(r.percentage) : '', flatFee: r.flatFee != null ? String(r.flatFee) : '', currency: r.currency || sysConfig.currency, priority: String(r.priority ?? 0), isActive: r.isActive }); setShowForm(true); };

  const save = async () => {
    setSaving(true); setError(null); setSuccess(null);
    try {
      const payload: any = { name: form.name, description: form.description || null, minAmount: Number(form.minAmount) || 0, maxAmount: form.maxAmount ? Number(form.maxAmount) : null, commissionType: form.commissionType, percentage: form.commissionType === 'PERCENTAGE' ? Number(form.percentage) || 0 : null, flatFee: form.commissionType === 'FIXED' ? Number(form.flatFee) || 0 : null, currency: form.currency || sysConfig.currency, priority: Number(form.priority) || 0, isActive: !!form.isActive };
      if (editing) { await businessRulesService.updateCommissionRange(editing.id, payload); setSuccess('Range updated'); }
      else { await businessRulesService.createCommissionRange(payload); setSuccess('Range created'); }
      setShowForm(false); load();
    } catch (e: any) { setError(getErrorMessage(e)); }
    finally { setSaving(false); }
  };

  const remove = async (id: string) => {
    if (!confirm('Delete this commission range?')) return;
    try { await businessRulesService.deleteCommissionRange(id); setSuccess('Range 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">Amount-banded commission ranges. A trade's amount falls into one range and pays that commission.</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 Range</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'} Commission Range</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 })} /></Field>
            <Field label="Priority"><NumberInput value={form.priority} onChange={(e) => setForm({ ...form, priority: e.target.value })} /></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 open-ended."><NumberInput step="0.01" value={form.maxAmount} onChange={(e) => setForm({ ...form, maxAmount: e.target.value })} /></Field>
            <Field label="Commission Type">
              <SelectInput value={form.commissionType} onChange={(e) => setForm({ ...form, commissionType: e.target.value })}>
                <option value="PERCENTAGE">Percentage</option>
                <option value="FIXED">Fixed</option>
              </SelectInput>
            </Field>
            <Field label="Percentage (0-1)"><NumberInput step="0.001" min="0" max="1" value={form.percentage} onChange={(e) => setForm({ ...form, percentage: e.target.value })} /></Field>
            <Field label={`Flat Fee (${sysConfig.currency})`}><NumberInput step="0.01" value={form.flatFee} onChange={(e) => setForm({ ...form, flatFee: e.target.value })} /></Field>
            <Field label="Currency"><TextInput value={form.currency} onChange={(e) => setForm({ ...form, currency: 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="range-active" type="checkbox" checked={!!form.isActive} onChange={(e) => setForm({ ...form, isActive: e.target.checked })} className="h-4 w-4 rounded" />
              <label htmlFor="range-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} /> : ranges.length === 0 ? <p className="rounded-lg border border-white/10 bg-slate-900/30 p-6 text-center text-sm text-slate-400">No ranges 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">Type</th><th className="px-3 py-2">Value</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>
              {ranges.map((r: any) => (
                <tr key={r.id} className="border-b border-white/5">
                  <td className="px-3 py-3 text-white">{r.name}</td>
                  <td className="px-3 py-3 text-slate-300">{Number(r.minAmount).toFixed(2)} {r.currency || sysConfig.currency}</td>
                  <td className="px-3 py-3 text-slate-300">{r.maxAmount ? Number(r.maxAmount).toFixed(2) : '∞'}</td>
                  <td className="px-3 py-3 text-slate-300">{r.commissionType}</td>
                  <td className="px-3 py-3 text-slate-300">{r.commissionType === 'PERCENTAGE' ? `${(Number(r.percentage || 0) * 100).toFixed(2)}%` : `${Number(r.flatFee || 0).toFixed(2)} ${r.currency || sysConfig.currency}`}</td>
                  <td className="px-3 py-3 text-slate-300">{r.priority || 0}</td>
                  <td className="px-3 py-3"><span className={cn('rounded-full px-2 py-1 text-xs', r.isActive ? 'bg-emerald-500/20 text-emerald-300' : 'bg-slate-500/20 text-slate-300')}>{r.isActive ? 'Active' : 'Inactive'}</span></td>
                  <td className="px-3 py-3 flex gap-2">
                    <button onClick={() => openEdit(r)} className="rounded-lg p-1 text-blue-400 hover:bg-blue-500/10"><Pencil className="h-4 w-4" /></button>
                    <button onClick={() => remove(r.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>
  );
}
