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

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 (
    <AdminShell>
      <div class="page-actions">
        <div>
          <h1 class="page-title">Pricing Management</h1>
          <p class="page-subtitle">Create and manage TraceCoin packages</p>
        </div>
      </div>

      {/* Tabs */}
      <div style="display:flex;border-bottom:2px solid #e2e8f0;margin-bottom:24px;gap:0;overflow-x:auto;">
        <button
          type="button"
          class={`admin-tab${view() === 'packages' ? ' active' : ''}`}
          onClick={() => setView('packages')}
        >
          Packages
        </button>
        <button
          type="button"
          class={`admin-tab${view() === 'create' ? ' active' : ''}`}
          onClick={() => setView('create')}
        >
          Create Package
        </button>
      </div>

      {/* Packages list tab */}
      <Show when={view() === 'packages'}>
        <section class="card" style="padding:0;overflow:hidden">
          <div class="table-wrap">
            <table class="list-table">
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Role</th>
                  <th>TraceCoins</th>
                  <th>Price (₹)</th>
                  <th>Bonus (%)</th>
                  <th>Status</th>
                  <th class="align-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>
                          <td style="font-weight:600;color:#0f172a">{pkg.name}</td>
                          <td style="color:#475569">{pkg.role}</td>
                          <td style="color:#475569">{pkg.tracecoin_amount}</td>
                          <td style="color:#475569">₹{(pkg.price_inr / 100).toFixed(2)}</td>
                          <td style="color:#475569">{pkg.bonus_percentage != null ? `${pkg.bonus_percentage}%` : '—'}</td>
                          <td>
                            <span class={`status-chip ${pkg.is_active ? 'active' : ''}`}>
                              {pkg.is_active ? 'Active' : 'Inactive'}
                            </span>
                          </td>
                          <td>
                            <div class="table-actions">
                              <button class="btn" onClick={() => startEdit(pkg)}>Edit</button>
                              <button
                                class={pkg.is_active ? 'btn danger' : 'btn navy'}
                                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="error-box" 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 navy" disabled={editSaving()} onClick={() => saveEdit(pkg.id)}>
                                    {editSaving() ? 'Saving...' : 'Save'}
                                  </button>
                                  <button class="btn" onClick={cancelEdit}>Cancel</button>
                                </div>
                              </div>
                            </td>
                          </tr>
                        </Show>
                      </>
                    )}
                  </For>
                </Show>
              </tbody>
            </table>
          </div>
        </section>
      </Show>

      {/* Create Package tab */}
      <Show when={view() === 'create'}>
        <section class="card" style="max-width:480px">
          <h2 style="margin:0 0 20px;font-size:16px;font-weight:700">New Package</h2>
          <Show when={cError()}>
            <div class="error-box" 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 navy" type="submit" disabled={cSaving()}>
                {cSaving() ? 'Creating...' : 'Create Package'}
              </button>
            </div>
          </form>
        </section>
      </Show>
    </AdminShell>
  );
}
