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}` } : {}),
  };
}

const ROLE_OPTIONS = [
  'company',
  'customer',
  'job_seeker',
  'photographer',
  'video_editor',
  'graphic_designer',
  'social_media_manager',
  'fitness_trainer',
  'catering_services',
  'makeup_artist',
  'tutor',
  'developer',
];

type Discount = {
  id: string;
  title: string;
  scope: 'ROLE' | 'PACKAGE';
  role_key?: string;
  package_id?: string;
  type: 'PERCENT' | 'FIXED';
  value: number;
  is_active: boolean;
};

type Package = {
  id: string;
  name: string;
  role_key?: string;
};

async function loadDiscounts(): Promise<Discount[]> {
  try {
    const res = await fetch(`${API}/api/admin/discounts`, {
      headers: authHeaders(),
      credentials: "include",
    });
    if (!res.ok) throw new Error('Failed to load');
    const data = await res.json();
    return Array.isArray(data) ? data : (data.discounts || []);
  } catch {
    return [];
  }
}

async function loadPackages(): Promise<Package[]> {
  try {
    const res = await fetch(`${API}/api/admin/tracecoin-packages`, {
      headers: authHeaders(),
      credentials: "include",
    });
    if (!res.ok) throw new Error('Failed to load');
    const data = await res.json();
    return Array.isArray(data) ? data : (data.packages || []);
  } catch {
    return [];
  }
}

const defaultForm = () => ({
  id: '',
  title: '',
  scope: 'ROLE' as 'ROLE' | 'PACKAGE',
  role_key: 'company',
  package_id: '',
  type: 'PERCENT' as 'PERCENT' | 'FIXED',
  value: 5,
});

export default function DiscountPage() {
  const [discounts, { refetch: refetchDiscounts }] = createResource(loadDiscounts);
  const [packages] = createResource(loadPackages);
  const [activeTab, setActiveTab] = createSignal<'list' | 'create'>('list');
  const [form, setForm] = createSignal(defaultForm());
  const [saving, setSaving] = createSignal(false);
  const [toggling, setToggling] = createSignal('');
  const [formError, setFormError] = createSignal('');
  const [search, setSearch] = createSignal('');
  const [statusFilter, setStatusFilter] = createSignal<'all' | 'active' | 'inactive'>('all');
  const [sortBy, setSortBy] = createSignal<'newest' | 'oldest' | 'title_asc' | 'title_desc'>('newest');
  const [sortMenuOpen, setSortMenuOpen] = createSignal(false);
  const [filterMenuOpen, setFilterMenuOpen] = createSignal(false);

  const resetForm = () => {
    setForm(defaultForm());
    setFormError('');
  };

  const getTarget = (item: Discount) => {
    if (item.scope === 'ROLE') return item.role_key || '—';
    const pkgs = packages();
    if (pkgs) {
      const pkg = pkgs.find((p) => p.id === item.package_id);
      if (pkg) return pkg.name;
    }
    return item.package_id || '—';
  };

  const filteredDiscounts = createMemo(() => {
    let data = discounts() ?? [];
    const q = search().toLowerCase().trim();
    if (q) {
      data = data.filter((item) =>
        String(item.title || '').toLowerCase().includes(q)
        || String(item.scope || '').toLowerCase().includes(q)
        || String(getTarget(item) || '').toLowerCase().includes(q)
      );
    }
    if (statusFilter() === 'active') data = data.filter((item) => item.is_active);
    if (statusFilter() === 'inactive') data = data.filter((item) => !item.is_active);
    const sorted = [...data];
    sorted.sort((a, b) => {
      if (sortBy() === 'oldest') return String(a.id || '').localeCompare(String(b.id || ''));
      if (sortBy() === 'title_asc') return String(a.title || '').localeCompare(String(b.title || ''));
      if (sortBy() === 'title_desc') return String(b.title || '').localeCompare(String(a.title || ''));
      return String(b.id || '').localeCompare(String(a.id || ''));
    });
    return sorted;
  });

  const exportCsv = () => {
    const headers = ['Title', 'Scope', 'Target', 'Type', 'Value', 'Status'];
    const rows = filteredDiscounts().map((item) => [
      item.title || '',
      item.scope,
      getTarget(item),
      item.type,
      item.type === 'PERCENT' ? `${item.value}%` : `₹${item.value}`,
      item.is_active ? '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 = 'discount-management.csv';
    link.click();
    URL.revokeObjectURL(url);
  };

  const handleSave = async (e: Event) => {
    e.preventDefault();
    try {
      setSaving(true);
      setFormError('');
      const f = form();
      const body: Record<string, unknown> = {
        title: f.title,
        scope: f.scope,
        type: f.type,
        value: Number(f.value),
      };
      if (f.scope === 'ROLE') {
        body.role_key = f.role_key;
      } else {
        body.package_id = f.package_id;
      }

      const url = f.id ? `${API}/api/admin/discounts/${f.id}` : `${API}/api/admin/discounts`;
      const method = f.id ? 'PATCH' : 'POST';
      const res = await fetch(url, {
        method,
        headers: authHeaders(),
        credentials: "include",
        body: JSON.stringify(body),
      });
      if (!res.ok) throw new Error('Failed to save discount');
      resetForm();
      refetchDiscounts();
      setActiveTab('list');
    } catch (err: unknown) {
      setFormError(err instanceof Error ? err.message : 'Failed to save');
    } finally {
      setSaving(false);
    }
  };

  const handleToggle = async (discount: Discount) => {
    try {
      setToggling(discount.id);
      const res = await fetch(`${API}/api/admin/discounts/${discount.id}`, {
        method: 'PATCH',
        headers: authHeaders(),
        credentials: "include",
        body: JSON.stringify({ is_active: !discount.is_active }),
      });
      if (!res.ok) throw new Error('Failed to toggle');
      refetchDiscounts();
    } catch {
      // ignore
    } finally {
      setToggling('');
    }
  };

  return (
      <div class="w-full space-y-6 pb-8">
        <div style="margin-bottom:1.5rem">
          <h1 class="text-[28px] font-bold leading-tight text-[#111827]">Discount Management</h1>
          <p class="mt-1 text-[14px] text-[#6B7280]">Automatic discounts applied before coupons</p>
        </div>

        {/* Tabs */}
        <div class="bg-white border-b border-gray-200 px-6 flex items-center gap-8 sticky top-0 z-10">
          <button
            type="button"
            class={activeTab() === 'list' ? 'py-3 border-b-2 border-orange-500 text-orange-600 text-sm font-medium' : 'py-3 border-b-2 border-transparent text-gray-500 hover:text-gray-700 text-sm font-medium transition-colors'}
            onClick={() => setActiveTab('list')}
          >
            Discounts
          </button>
          <button
            type="button"
            class={activeTab() === 'create' ? 'py-3 border-b-2 border-orange-500 text-orange-600 text-sm font-medium' : 'py-3 border-b-2 border-transparent text-gray-500 hover:text-gray-700 text-sm font-medium transition-colors'}
            onClick={() => { resetForm(); setActiveTab('create'); }}
          >
            {form().id ? 'Edit Discount' : 'Create Discount'}
          </button>
        </div>

        <div>
          <Show when={activeTab() === 'list'}>
            <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 title, scope, or target..."
                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: 'newest', label: 'Newest First' },
                      { key: 'oldest', label: 'Oldest First' },
                      { key: 'title_asc', label: 'Title A-Z' },
                      { key: 'title_desc', label: 'Title Z-A' },
                    ] as { key: 'newest' | 'oldest' | 'title_asc' | 'title_desc'; 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>Title</th>
                      <th>Scope</th>
                      <th>Target</th>
                      <th>Type</th>
                      <th>Value</th>
                      <th>Status</th>
                      <th class="text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    <Show when={discounts.loading}>
                      <tr><td colspan="7" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr>
                    </Show>
                    <Show when={!discounts.loading && discounts.error}>
                      <tr><td colspan="7" style="text-align:center;padding:32px;color:#b91c1c">Failed to load. Is the backend running?</td></tr>
                    </Show>
                    <Show when={!discounts.loading && !discounts.error && filteredDiscounts().length === 0}>
                      <tr><td colspan="7" style="text-align:center;padding:32px;color:#94a3b8">No discounts found.</td></tr>
                    </Show>
                    <Show when={!discounts.loading && !discounts.error && filteredDiscounts().length > 0}>
                      <For each={filteredDiscounts()}>
                        {(item) => (
                          <tr class="hover:bg-slate-50">
                            <td class="font-semibold text-slate-900">{item.title || '—'}</td>
                            <td class="text-slate-500">{item.scope}</td>
                            <td class="text-slate-500">{getTarget(item)}</td>
                            <td class="text-slate-500">{item.type}</td>
                            <td class="text-slate-500">{item.type === 'PERCENT' ? `${item.value}%` : `₹${item.value}`}</td>
                            <td>
                              <span style={`display:inline-flex;align-items:center;border-radius:9999px;border:1px solid ${item.is_active ? '#FFD8C2' : '#D1D5DB'};background:${item.is_active ? '#FFF1EB' : '#F3F4F6'};color:${item.is_active ? '#FF5E13' : '#4B5563'};padding:2px 10px;font-size:12px;font-weight:500`}>
                                <span style={`display:inline-block;width:6px;height:6px;border-radius:50%;background:${item.is_active ? '#FF5E13' : '#9CA3AF'};margin-right:5px;flex-shrink:0`} />
                                {item.is_active ? '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={toggling() === item.id}
                                  onClick={() => handleToggle(item)}
                                >
                                  {toggling() === item.id ? '...' : (item.is_active ? 'Disable' : 'Enable')}
                                </button>
                              </div>
                            </td>
                          </tr>
                        )}
                      </For>
                    </Show>
                  </tbody>
                </table>
              </div>
            </div>
            </div>
          </Show>

          <Show when={activeTab() === 'create'}>
            <section class="rounded-xl border border-gray-200 bg-white shadow-sm" style="max-width:520px">
              <h2 style="margin:0 0 20px;font-size:16px;font-weight:700">{form().id ? 'Edit Discount' : 'Create Discount'}</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:14px">
                <div class="field">
                  <label>Title</label>
                  <input
                    type="text"
                    value={form().title}
                    onInput={(e) => setForm({ ...form(), title: e.currentTarget.value })}
                    required
                    placeholder="e.g. New user 10% off"
                  />
                </div>
                <div class="field">
                  <label>Scope</label>
                  <div style="display:flex;gap:24px;margin-top:4px">
                    <label style="display:flex;align-items:center;gap:6px;font-size:14px;font-weight:400;cursor:pointer">
                      <input
                        type="radio"
                        name="scope"
                        value="ROLE"
                        checked={form().scope === 'ROLE'}
                        onChange={() => setForm({ ...form(), scope: 'ROLE' })}
                      />
                      ROLE
                    </label>
                    <label style="display:flex;align-items:center;gap:6px;font-size:14px;font-weight:400;cursor:pointer">
                      <input
                        type="radio"
                        name="scope"
                        value="PACKAGE"
                        checked={form().scope === 'PACKAGE'}
                        onChange={() => setForm({ ...form(), scope: 'PACKAGE' })}
                      />
                      PACKAGE
                    </label>
                  </div>
                </div>
                <div class="field">
                  <label>Target</label>
                  <Show when={form().scope === 'ROLE'}>
                    <select
                      value={form().role_key}
                      onChange={(e) => setForm({ ...form(), role_key: e.currentTarget.value })}
                    >
                      <For each={ROLE_OPTIONS}>
                        {(role) => <option value={role}>{role}</option>}
                      </For>
                    </select>
                  </Show>
                  <Show when={form().scope === 'PACKAGE'}>
                    <select
                      value={form().package_id}
                      onChange={(e) => setForm({ ...form(), package_id: e.currentTarget.value })}
                    >
                      <Show when={packages.loading}>
                        <option value="">Loading packages...</option>
                      </Show>
                      <Show when={!packages.loading}>
                        <For each={packages()}>
                          {(pkg) => <option value={pkg.id}>{pkg.name}</option>}
                        </For>
                      </Show>
                    </select>
                  </Show>
                </div>
                <div class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
                  <div class="field">
                    <label>Type</label>
                    <select
                      value={form().type}
                      onChange={(e) => setForm({ ...form(), type: e.currentTarget.value as 'PERCENT' | 'FIXED' })}
                    >
                      <option value="PERCENT">Percent (%)</option>
                      <option value="FIXED">Fixed (₹)</option>
                    </select>
                  </div>
                  <div class="field">
                    <label>Value</label>
                    <input
                      type="number"
                      value={form().value}
                      onInput={(e) => setForm({ ...form(), value: Number(e.currentTarget.value) })}
                      required
                      min="1"
                    />
                  </div>
                </div>
                <div class="actions">
                  <button class="btn-primary" type="submit" disabled={saving()}>
                    {saving() ? 'Saving...' : (form().id ? 'Update Discount' : 'Save Discount')}
                  </button>
                  <Show when={form().id}>
                    <button type="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" onClick={resetForm}>Cancel Edit</button>
                  </Show>
                </div>
              </form>
            </section>
          </Show>
        </div>
      </div>
  );
}
