import { createResource, createSignal, Show } from 'solid-js';

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 (
      <div class="flex flex-col -mx-6 -mt-6 min-h-full">
        <div class="bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between">
          <div>
            <h1 class="text-xl font-semibold text-gray-900">Tax Management</h1>
            <p class="text-sm text-gray-500 mt-0.5">Configure tax rates for platform transactions.</p>
          </div>
          <button class="btn-primary" onClick={() => setShowForm(!showForm())}>
            {showForm() ? 'Cancel' : 'Add Tax'}
          </button>
        </div>

        <div class="flex-1 p-6">
          <Show when={showForm()}>
            <section class="rounded-xl border border-gray-200 bg-white shadow-sm" style="margin-bottom:16px">
              <h2 style="margin:0 0 16px;font-size:16px;font-weight:700">New Tax</h2>
              <Show when={formError()}>
                <div class="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700" 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-primary" type="submit" disabled={saving()}>
                    {saving() ? 'Saving...' : 'Save Tax'}
                  </button>
                </div>
              </form>
            </section>
          </Show>

          <div class="table-card">
            <div class="overflow-x-auto">
              <table class="data-table w-full text-sm">
                <thead>
                  <tr>
                    <th>Name</th>
                    <th>Rate (%)</th>
                    <th>Description</th>
                    <th>Status</th>
                    <th class="text-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 class="hover:bg-slate-50">
                        <td class="font-semibold text-slate-900">{item.name}</td>
                        <td class="text-slate-500">{item.rate}%</td>
                        <td class="text-slate-500">{item.description || '—'}</td>
                        <td>
                          <span class={`inline-flex items-center rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-600 ${item.is_active !== false ? 'active' : ''}`}>
                            {item.is_active !== false ? 'Active' : 'Inactive'}
                          </span>
                        </td>
                        <td>
                          <div class="flex items-center justify-end gap-1">
                            <a class="inline-flex items-center rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors" href={`/admin/tax/${item.id}/edit`}>Edit</a>
                            <button
                              class="inline-flex items-center rounded-lg border border-red-200 bg-red-50 px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-100 transition-colors"
                              disabled={deleting() === item.id}
                              onClick={() => handleDelete(item.id, item.name)}
                            >
                              {deleting() === item.id ? '...' : 'Delete'}
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </Show>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
  );
}
