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

const API = '/api/gateway';

type Package = {
  id: string;
  name: string;
  role: string;
  tracecoin_amount: number;
  price_inr: number;
  bonus_percentage?: number;
  is_active: boolean;
};

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

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

export default function PricingPage() {
  const [packages, { refetch }] = createResource(loadPackages);
  const [view, setView] = createSignal<'packages' | 'create'>('packages');

  // Inline edit state
  const [editingId, setEditingId] = createSignal('');
  const [editName, setEditName] = createSignal('');
  const [editTracecoins, setEditTracecoins] = createSignal('');
  const [editPrice, setEditPrice] = createSignal('');
  const [editSaving, setEditSaving] = createSignal(false);
  const [editError, setEditError] = createSignal('');

  // Toggle active state
  const [togglingId, setTogglingId] = createSignal('');

  // Create form state
  const [cName, setCName] = createSignal('');
  const [cRole, setCRole] = createSignal(ROLES[0]);
  const [cTracecoins, setCTracecoins] = createSignal('');
  const [cPrice, setCPrice] = createSignal('');
  const [cBonus, setCBonus] = createSignal('');
  const [cSaving, setCsaving] = createSignal(false);
  const [cError, setCError] = createSignal('');

  const startEdit = (pkg: Package) => {
    setEditingId(pkg.id);
    setEditName(pkg.name);
    setEditTracecoins(String(pkg.tracecoin_amount));
    setEditPrice(String(pkg.price_inr));
    setEditError('');
  };

  const cancelEdit = () => {
    setEditingId('');
    setEditError('');
  };

  const saveEdit = async (id: string) => {
    try {
      setEditSaving(true);
      setEditError('');
      const res = await fetch(`${API}/api/admin/tracecoin-packages/${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: editName(),
          tracecoin_amount: Number(editTracecoins()),
          price_inr: Number(editPrice()),
        }),
      });
      if (!res.ok) throw new Error('Failed to save');
      setEditingId('');
      refetch();
    } catch (err: any) {
      setEditError(err.message || 'Failed to save');
    } finally {
      setEditSaving(false);
    }
  };

  const toggleActive = async (pkg: Package) => {
    try {
      setTogglingId(pkg.id);
      const res = await fetch(`${API}/api/admin/tracecoin-packages/${pkg.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ is_active: !pkg.is_active }),
      });
      if (!res.ok) throw new Error('Failed to update');
      refetch();
    } catch {
      // ignore
    } finally {
      setTogglingId('');
    }
  };

  const handleCreate = async (e: Event) => {
    e.preventDefault();
    try {
      setCsaving(true);
      setCError('');
      const body: Record<string, any> = {
        name: cName(),
        role: cRole(),
        tracecoin_amount: Number(cTracecoins()),
        price_inr: Number(cPrice()),
      };
      if (cBonus()) body.bonus_percentage = Number(cBonus());
      const res = await fetch(`${API}/api/admin/tracecoin-packages`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      if (!res.ok) throw new Error('Failed to create package');
      setCName('');
      setCRole(ROLES[0]);
      setCTracecoins('');
      setCPrice('');
      setCBonus('');
      setView('packages');
      refetch();
    } catch (err: any) {
      setCError(err.message || 'Failed to create');
    } finally {
      setCsaving(false);
    }
  };

  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">
          <h1 class="text-xl font-semibold text-gray-900">Pricing Management</h1>
          <p class="text-sm text-gray-500 mt-0.5">Create and manage TraceCoin packages</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={view() === 'packages' ? '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={() => setView('packages')}
          >
            Packages
          </button>
          <button
            type="button"
            class={view() === '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={() => setView('create')}
          >
            Create Package
          </button>
        </div>

        <div class="flex-1 p-6">
          {/* Packages list tab */}
          <Show when={view() === 'packages'}>
            <div class="table-card">
              <div class="overflow-x-auto">
                <table class="data-table w-full text-sm">
                  <thead>
                    <tr>
                      <th>Name</th>
                      <th>Role</th>
                      <th>TraceCoins</th>
                      <th>Price (₹)</th>
                      <th>Bonus (%)</th>
                      <th>Status</th>
                      <th class="text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    <Show when={packages.loading}>
                      <tr><td colspan="7" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr>
                    </Show>
                    <Show when={!packages.loading && packages.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={!packages.loading && !packages.error && (packages()?.length ?? 0) === 0}>
                      <tr><td colspan="7" style="text-align:center;padding:32px;color:#94a3b8">No packages found.</td></tr>
                    </Show>
                    <Show when={!packages.loading && !packages.error && (packages()?.length ?? 0) > 0}>
                      <For each={packages()}>
                        {(pkg) => (
                          <>
                            <tr class="hover:bg-slate-50">
                              <td class="font-semibold text-slate-900">{pkg.name}</td>
                              <td class="text-slate-500">{pkg.role}</td>
                              <td class="text-slate-500">{pkg.tracecoin_amount}</td>
                              <td class="text-slate-500">₹{(pkg.price_inr / 100).toFixed(2)}</td>
                              <td class="text-slate-500">{pkg.bonus_percentage != null ? `${pkg.bonus_percentage}%` : '—'}</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 ${pkg.is_active ? 'active' : ''}`}>
                                  {pkg.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" onClick={() => startEdit(pkg)}>Edit</button>
                                  <button
                                    class={pkg.is_active ? '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' : 'btn-primary'}
                                    disabled={togglingId() === pkg.id}
                                    onClick={() => toggleActive(pkg)}
                                  >
                                    {togglingId() === pkg.id ? '...' : pkg.is_active ? 'Disable' : 'Enable'}
                                  </button>
                                </div>
                              </td>
                            </tr>
                            <Show when={editingId() === pkg.id}>
                              <tr>
                                <td colspan="7" style="background:#f8fafc;padding:16px">
                                  <Show when={editError()}>
                                    <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:10px">{editError()}</div>
                                  </Show>
                                  <div style="display:flex;gap:12px;flex-wrap:wrap;align-items:flex-end">
                                    <div class="field">
                                      <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px">Name</label>
                                      <input
                                        type="text"
                                        value={editName()}
                                        onInput={(e) => setEditName(e.currentTarget.value)}
                                        style="padding:7px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:13px;width:180px"
                                      />
                                    </div>
                                    <div class="field">
                                      <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px">TraceCoins</label>
                                      <input
                                        type="number"
                                        value={editTracecoins()}
                                        onInput={(e) => setEditTracecoins(e.currentTarget.value)}
                                        style="padding:7px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:13px;width:110px"
                                      />
                                    </div>
                                    <div class="field">
                                      <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px">Price (paise)</label>
                                      <input
                                        type="number"
                                        value={editPrice()}
                                        onInput={(e) => setEditPrice(e.currentTarget.value)}
                                        style="padding:7px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:13px;width:110px"
                                      />
                                    </div>
                                    <div style="display:flex;gap:8px">
                                      <button class="btn-primary" disabled={editSaving()} onClick={() => saveEdit(pkg.id)}>
                                        {editSaving() ? 'Saving...' : 'Save'}
                                      </button>
                                      <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={cancelEdit}>Cancel</button>
                                    </div>
                                  </div>
                                </td>
                              </tr>
                            </Show>
                          </>
                        )}
                      </For>
                    </Show>
                  </tbody>
                </table>
              </div>
            </div>
          </Show>

          {/* Create Package tab */}
          <Show when={view() === 'create'}>
            <section class="rounded-xl border border-gray-200 bg-white shadow-sm" style="max-width:480px">
              <h2 style="margin:0 0 20px;font-size:16px;font-weight:700">New Package</h2>
              <Show when={cError()}>
                <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:14px">{cError()}</div>
              </Show>
              <form onSubmit={handleCreate} style="display:flex;flex-direction:column;gap:14px">
                <div class="field">
                  <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Name</label>
                  <input
                    type="text"
                    value={cName()}
                    onInput={(e) => setCName(e.currentTarget.value)}
                    required
                    placeholder="e.g. Starter Pack"
                    style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px"
                  />
                </div>
                <div class="field">
                  <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Role</label>
                  <select
                    value={cRole()}
                    onChange={(e) => setCRole(e.currentTarget.value)}
                    required
                    style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px"
                  >
                    <For each={ROLES}>{(r) => <option value={r}>{r}</option>}</For>
                  </select>
                </div>
                <div class="field">
                  <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">TraceCoins</label>
                  <input
                    type="number"
                    value={cTracecoins()}
                    onInput={(e) => setCTracecoins(e.currentTarget.value)}
                    required
                    min="1"
                    placeholder="e.g. 100"
                    style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px"
                  />
                </div>
                <div class="field">
                  <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Price INR (paise, e.g. 49900 = ₹499)</label>
                  <input
                    type="number"
                    value={cPrice()}
                    onInput={(e) => setCPrice(e.currentTarget.value)}
                    required
                    min="1"
                    placeholder="e.g. 49900"
                    style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px"
                  />
                </div>
                <div class="field">
                  <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Bonus Percentage (optional, e.g. 10 = 10% bonus coins)</label>
                  <input
                    type="number"
                    value={cBonus()}
                    onInput={(e) => setCBonus(e.currentTarget.value)}
                    min="0"
                    placeholder="e.g. 10"
                    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={cSaving()}>
                    {cSaving() ? 'Creating...' : 'Create Package'}
                  </button>
                </div>
              </form>
            </section>
          </Show>
        </div>
      </div>
  );
}
