import { createResource, createSignal, Show } from 'solid-js';
import AdminShell from '~/components/AdminShell';

const API = '/api/gateway';

async function loadTaxes(): Promise<any[]> {
  try {
    const res = await fetch(`${API}/api/admin/tax`);
    if (!res.ok) throw new Error('Failed to load');
    const data = await res.json();
    return Array.isArray(data) ? data : (data.taxes || data.tax || []);
  } catch {
    return [];
  }
}

export default function TaxPage() {
  const [taxes, { refetch }] = createResource(loadTaxes);
  const [deleting, setDeleting] = createSignal('');
  const [showForm, setShowForm] = createSignal(false);
  const [saving, setSaving] = createSignal(false);
  const [formError, setFormError] = createSignal('');

  const [name, setName] = createSignal('');
  const [rate, setRate] = createSignal('');
  const [description, setDescription] = createSignal('');

  const handleSave = async (e: Event) => {
    e.preventDefault();
    try {
      setSaving(true);
      setFormError('');
      const res = await fetch(`${API}/api/admin/tax`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: name(), rate: Number(rate()), description: description() }),
      });
      if (!res.ok) throw new Error('Failed to create tax');
      setName('');
      setRate('');
      setDescription('');
      setShowForm(false);
      refetch();
    } catch (err: any) {
      setFormError(err.message || 'Failed to save');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string, taxName: string) => {
    if (!confirm(`Delete tax "${taxName}"?`)) return;
    try {
      setDeleting(id);
      const res = await fetch(`${API}/api/admin/tax/${id}`, { method: 'DELETE' });
      if (!res.ok) throw new Error('Failed to delete');
      refetch();
    } catch {
      // ignore
    } finally {
      setDeleting('');
    }
  };

  return (
    <AdminShell>
      <div class="page-actions">
        <div>
          <h1 class="page-title">Tax Management</h1>
          <p class="page-subtitle">Configure tax rates for platform transactions.</p>
        </div>
        <button class="btn navy" onClick={() => setShowForm(!showForm())}>
          {showForm() ? 'Cancel' : 'Add Tax'}
        </button>
      </div>

      <Show when={showForm()}>
        <section class="card" style="margin-bottom:16px">
          <h2 style="margin:0 0 16px;font-size:16px;font-weight:700">New Tax</h2>
          <Show when={formError()}>
            <div class="error-box" style="margin-bottom:12px">{formError()}</div>
          </Show>
          <form onSubmit={handleSave} style="display:flex;flex-direction:column;gap:12px;max-width:400px">
            <div>
              <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Name</label>
              <input
                type="text"
                value={name()}
                onInput={(e) => setName(e.currentTarget.value)}
                required
                style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px"
              />
            </div>
            <div>
              <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Rate (%)</label>
              <input
                type="number"
                value={rate()}
                onInput={(e) => setRate(e.currentTarget.value)}
                required
                min="0"
                max="100"
                step="0.01"
                style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px"
              />
            </div>
            <div>
              <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Description</label>
              <input
                type="text"
                value={description()}
                onInput={(e) => setDescription(e.currentTarget.value)}
                style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px"
              />
            </div>
            <div>
              <button class="btn navy" type="submit" disabled={saving()}>
                {saving() ? 'Saving...' : 'Save Tax'}
              </button>
            </div>
          </form>
        </section>
      </Show>

      <section class="card" style="padding: 0; overflow: hidden;">
        <div class="table-wrap">
          <table class="list-table">
            <thead>
              <tr>
                <th>Name</th>
                <th>Rate (%)</th>
                <th>Description</th>
                <th>Status</th>
                <th class="align-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              <Show when={taxes.loading}>
                <tr><td colspan="5" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr>
              </Show>
              <Show when={!taxes.loading && taxes.error}>
                <tr><td colspan="5" style="text-align:center;padding:32px;color:#b91c1c">Failed to load. Is the backend running?</td></tr>
              </Show>
              <Show when={!taxes.loading && !taxes.error && taxes()?.length === 0}>
                <tr><td colspan="5" style="text-align:center;padding:32px;color:#94a3b8">No records found.</td></tr>
              </Show>
              <Show when={!taxes.loading && !taxes.error && (taxes()?.length ?? 0) > 0}>
                {taxes()!.map((item) => (
                  <tr>
                    <td style="font-weight:600;color:#0f172a">{item.name}</td>
                    <td style="color:#475569">{item.rate}%</td>
                    <td style="color:#475569">{item.description || '—'}</td>
                    <td>
                      <span class={`status-chip ${item.is_active !== false ? 'active' : ''}`}>
                        {item.is_active !== false ? 'Active' : 'Inactive'}
                      </span>
                    </td>
                    <td>
                      <div class="table-actions">
                        <a class="btn" href={`/admin/tax/${item.id}/edit`}>Edit</a>
                        <button
                          class="btn danger"
                          disabled={deleting() === item.id}
                          onClick={() => handleDelete(item.id, item.name)}
                        >
                          {deleting() === item.id ? '...' : 'Delete'}
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </Show>
            </tbody>
          </table>
        </div>
      </section>
    </AdminShell>
  );
}
