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

const API = '';

function getToken(): string {
  return typeof sessionStorage !== "undefined"
    ? sessionStorage.getItem("nxtgauge_admin_access_token") || ""
    : "";
}

function authHeaders(): Record<string, string> {
  const token = getToken();
  return {
    Accept: "application/json",
    "Content-Type": "application/json",
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  };
}

async function loadTaxes(): Promise<any[]> {
  try {
    const res = await fetch(`${API}/api/admin/tax`, {
      headers: authHeaders(),
      credentials: "include",
    });
    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 [search, setSearch] = createSignal('');
  const [statusFilter, setStatusFilter] = createSignal<'all' | 'active' | 'inactive'>('all');
  const [sortBy, setSortBy] = createSignal<'name_asc' | 'name_desc' | 'rate_desc' | 'rate_asc'>('name_asc');
  const [sortMenuOpen, setSortMenuOpen] = createSignal(false);
  const [filterMenuOpen, setFilterMenuOpen] = createSignal(false);

  const [name, setName] = createSignal('');
  const [rate, setRate] = createSignal('');
  const [description, setDescription] = createSignal('');
  const [taxType, setTaxType] = createSignal('GST');
  const [appliesTo, setAppliesTo] = createSignal('ALL');

  const handleSave = async (e: Event) => {
    e.preventDefault();
    try {
      setSaving(true);
      setFormError('');
      const res = await fetch(`${API}/api/admin/tax`, {
        method: 'POST',
        headers: authHeaders(),
        credentials: "include",
        body: JSON.stringify({
          name: name(),
          tax_type: taxType(),
          tax_rate: Number(rate()),
          applies_to: appliesTo(),
          description: description(),
          is_active: true,
        }),
      });
      if (!res.ok) throw new Error('Failed to create tax');
      setName('');
      setRate('');
      setDescription('');
      setTaxType('GST');
      setAppliesTo('ALL');
      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',
        headers: authHeaders(),
        credentials: "include",
      });
      if (!res.ok) throw new Error('Failed to delete');
      refetch();
    } catch {
      // ignore
    } finally {
      setDeleting('');
    }
  };

  const filteredTaxes = createMemo(() => {
    let data = taxes() ?? [];
    const q = search().toLowerCase().trim();
    if (q) {
      data = data.filter((item) =>
        String(item.name || '').toLowerCase().includes(q)
        || String(item.description || '').toLowerCase().includes(q)
      );
    }
    if (statusFilter() === 'active') data = data.filter((item) => item.is_active !== false);
    if (statusFilter() === 'inactive') data = data.filter((item) => item.is_active === false);
    const sorted = [...data];
    sorted.sort((a, b) => {
      if (sortBy() === 'name_desc') return String(b.name || '').localeCompare(String(a.name || ''));
      if (sortBy() === 'rate_desc') return Number(b.rate ?? 0) - Number(a.rate ?? 0);
      if (sortBy() === 'rate_asc') return Number(a.rate ?? 0) - Number(b.rate ?? 0);
      return String(a.name || '').localeCompare(String(b.name || ''));
    });
    return sorted;
  });

  const exportCsv = () => {
    const headers = ['Name', 'Rate', 'Description', 'Status'];
    const rows = filteredTaxes().map((item) => [
      item.name || '',
      `${item.rate ?? 0}%`,
      item.description || '—',
      item.is_active !== false ? 'Active' : 'Inactive',
    ]);
    const csv = [headers, ...rows].map((line) => line.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'tax-management.csv';
    link.click();
    URL.revokeObjectURL(url);
  };

  return (
      <div class="w-full space-y-6 pb-8">
        <div style="margin-bottom:1.5rem;display:flex;align-items:center;justify-content:space-between;gap:12px">
          <div>
            <h1 class="text-[28px] font-bold leading-tight text-[#111827]">Tax Management</h1>
            <p class="mt-1 text-[14px] text-[#6B7280]">Configure tax rates for platform transactions.</p>
          </div>
          <button class="btn-primary" onClick={() => setShowForm(!showForm())}>
            {showForm() ? 'Cancel' : 'Add Tax'}
          </button>
        </div>

        <div>
          <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 style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
                  <div>
                    <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Tax Type</label>
                    <select
                      value={taxType()}
                      onChange={(e) => setTaxType(e.currentTarget.value)}
                      style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px"
                    >
                      <option value="GST">GST</option>
                      <option value="CGST">CGST</option>
                      <option value="SGST">SGST</option>
                      <option value="IGST">IGST</option>
                      <option value="VAT">VAT</option>
                      <option value="CESS">CESS</option>
                    </select>
                  </div>
                  <div>
                    <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Applies To</label>
                    <select
                      value={appliesTo()}
                      onChange={(e) => setAppliesTo(e.currentTarget.value)}
                      style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px"
                    >
                      <option value="ALL">All</option>
                      <option value="PACKAGES">Packages</option>
                      <option value="AI_CREDITS">AI Credits</option>
                      <option value="LEAD_REQUESTS">Lead Requests</option>
                    </select>
                  </div>
                </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 style="position:relative;margin-top:1.5rem;margin-left:-24px;margin-right:-24px;border-radius:0;border-left:none;border-right:none;overflow:visible;border-top:1px solid #E5E7EB;border-bottom:1px solid #E5E7EB;background:white;box-shadow:0 1px 3px rgba(0,0,0,0.06)">
          <div style="display:flex;align-items:center;gap:8px;padding:14px 20px;border-bottom:1px solid #F3F4F6;position:relative;z-index:20;margin-bottom:0">
            <input
              type="text"
              placeholder="Search by name or description..."
              value={search()}
              onInput={(e) => setSearch(e.currentTarget.value)}
              style="height:34px;flex:1;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;color:#111827;outline:none"
            />
            <div style="position:relative;">
              <button type="button" onClick={() => { setSortMenuOpen((v) => !v); setFilterMenuOpen(false); }} style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:500;color:#374151;cursor:pointer">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 4v13"/><path d="m3 13 4 4 4-4"/><path d="M17 20V7"/><path d="m21 11-4-4-4 4"/></svg>
                Sort
              </button>
              <Show when={sortMenuOpen()}>
                <div style="position:absolute;right:0;top:38px;z-index:40;min-width:180px;border:1px solid #E5E7EB;border-radius:12px;background:#fff;box-shadow:0 12px 24px rgba(2,6,23,0.12);padding:8px">
                  <For each={[
                    { key: 'name_asc', label: 'Name A-Z' },
                    { key: 'name_desc', label: 'Name Z-A' },
                    { key: 'rate_desc', label: 'Rate High-Low' },
                    { key: 'rate_asc', label: 'Rate Low-High' },
                  ] as { key: 'name_asc' | 'name_desc' | 'rate_desc' | 'rate_asc'; label: string }[]}>
                    {(item) => (
                      <button type="button" onClick={() => { setSortBy(item.key); setSortMenuOpen(false); }} style={`display:block;width:100%;border-radius:8px;padding:8px 12px;text-align:left;font-size:13px;background:none;border:none;cursor:pointer;color:${sortBy() === item.key ? '#FF5E13' : '#374151'};background:${sortBy() === item.key ? '#FFF1EB' : 'transparent'}`}>{item.label}</button>
                    )}
                  </For>
                </div>
              </Show>
            </div>
            <div style="position:relative;">
              <button type="button" onClick={() => { setFilterMenuOpen((v) => !v); setSortMenuOpen(false); }} style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:500;color:#374151;cursor:pointer">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18M6 12h12M10 19h4"/></svg>
                Filters
              </button>
              <Show when={filterMenuOpen()}>
                <div style="position:absolute;right:0;top:38px;z-index:40;min-width:180px;border:1px solid #E5E7EB;border-radius:12px;background:#fff;box-shadow:0 12px 24px rgba(2,6,23,0.12);padding:8px">
                  <For each={[
                    { key: 'all', label: 'All Status' },
                    { key: 'active', label: 'Active' },
                    { key: 'inactive', label: 'Inactive' },
                  ] as { key: 'all' | 'active' | 'inactive'; label: string }[]}>
                    {(item) => (
                      <button type="button" onClick={() => { setStatusFilter(item.key); setFilterMenuOpen(false); }} style={`display:block;width:100%;border-radius:8px;padding:8px 12px;text-align:left;font-size:13px;background:none;border:none;cursor:pointer;color:${statusFilter() === item.key ? '#FF5E13' : '#374151'};background:${statusFilter() === item.key ? '#FFF1EB' : 'transparent'}`}>{item.label}</button>
                    )}
                  </For>
                </div>
              </Show>
            </div>
            <button type="button" onClick={exportCsv} style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;background:#0D0D2A;padding:0 12px;font-size:12px;font-weight:600;color:white;border:none;cursor:pointer">
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
              Export
            </button>
          </div>

          <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 && filteredTaxes().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 && filteredTaxes().length > 0}>
                    <For each={filteredTaxes()}>
                      {(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">
                              <button
                                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"
                                disabled={deleting() === item.id}
                                onClick={() => handleDelete(item.id, item.name)}
                              >
                                {deleting() === item.id ? 'Deleting...' : 'Delete'}
                              </button>
                            </div>
                          </td>
                        </tr>
                      )}
                    </For>
                  </Show>
                </tbody>
              </table>
            </div>
          </div>
          </div>
        </div>
      </div>
  );
}
