import { For, Show, createSignal, onMount } from 'solid-js';
import { BTN_GHOST, CARD } from '~/components/DashboardShell';
import { PROFESSIONAL_ROLE_SET, ROLE_PREFIXES, type RoleKey } from './RoleDashboardShared';

const API = '/api/gateway';

type Props = { roleKey: RoleKey };

async function apiFetch(path: string, opts?: RequestInit) {
  return fetch(`${API}${path}`, {
    ...opts,
    credentials: 'include',
    headers: { 'Content-Type': 'application/json', ...(opts?.headers ?? {}) },
  });
}

export default function CreditsPage(props: Props) {
  const [wallet, setWallet] = createSignal<any>(null);
  const [ledger, setLedger] = createSignal<any[]>([]);
  const [loading, setLoading] = createSignal(true);
  const [err, setErr] = createSignal('');

  const isProfessional = () => PROFESSIONAL_ROLE_SET.has(props.roleKey);
  const prefix = () => ROLE_PREFIXES[props.roleKey];

  const loadData = async () => {
    setLoading(true);
    setErr('');
    try {
      if (!isProfessional()) {
        setWallet(null);
        setLedger([]);
        return;
      }
      const [walletRes, ledgerRes] = await Promise.all([
        apiFetch(`/api/${prefix()}/wallet/me`),
        apiFetch(`/api/${prefix()}/wallet/me/ledger?page=1&limit=20`),
      ]);
      const walletJson = await walletRes.json().catch(() => ({}));
      const ledgerJson = await ledgerRes.json().catch(() => ({}));
      if (walletRes.ok) setWallet(walletJson);
      else setErr(walletJson.error || walletJson.message || 'Failed to load wallet.');
      if (ledgerRes.ok) setLedger(Array.isArray(ledgerJson?.data) ? ledgerJson.data : []);
      else if (!err()) setErr(ledgerJson.error || ledgerJson.message || 'Failed to load ledger.');
    } catch {
      setErr('Network error while loading credits.');
    } finally {
      setLoading(false);
    }
  };

  onMount(loadData);

  return (
    <div style={{ display: 'grid', gap: '14px', 'max-width': '980px' }}>
      <div style={CARD}>
        <p style={{ margin: '0', 'font-size': '22px', 'font-weight': '800', color: '#0D0D2A' }}>Credits</p>
        <p style={{ margin: '4px 0 0', 'font-size': '13px', color: '#6B7280' }}>
          {isProfessional() ? 'Track Tracecoin balance and usage history.' : 'Credits and billing summary for your account.'}
        </p>
      </div>

      <Show when={err()}>
        <div style={{ ...CARD, border: '1px solid #FECACA', background: '#FEF2F2', padding: '12px 14px', color: '#B91C1C', 'font-size': '13px', 'font-weight': '600' }}>{err()}</div>
      </Show>

      <Show when={loading()}>
        <div style={{ ...CARD, 'text-align': 'center', color: '#9CA3AF' }}>Loading credits...</div>
      </Show>

      <Show when={!loading() && !isProfessional()}>
        <div style={CARD}>
          <p style={{ margin: '0', 'font-size': '15px', 'font-weight': '700', color: '#111827' }}>Billing Overview</p>
          <p style={{ margin: '8px 0 0', 'font-size': '13px', color: '#6B7280' }}>
            Your role does not use professional wallet endpoints. Billing and payments are managed through role-specific transactions.
          </p>
        </div>
      </Show>

      <Show when={!loading() && isProfessional()}>
        <div style={{ ...CARD, display: 'grid', 'grid-template-columns': '1fr auto', gap: '10px', 'align-items': 'center' }}>
          <div>
            <p style={{ margin: '0', 'font-size': '12px', 'letter-spacing': '0.06em', 'text-transform': 'uppercase', color: '#6B7280' }}>Current Balance</p>
            <p style={{ margin: '6px 0 0', 'font-size': '28px', 'font-weight': '800', color: '#111827' }}>
              {wallet()?.balance ?? 0} <span style={{ 'font-size': '14px', color: '#6B7280', 'font-weight': '600' }}>Tracecoins</span>
            </p>
          </div>
          <button type="button" onClick={loadData} style={BTN_GHOST}>Refresh</button>
        </div>

        <div style={CARD}>
          <p style={{ margin: '0 0 10px', 'font-size': '16px', 'font-weight': '700', color: '#111827' }}>Recent Ledger</p>
          <Show when={ledger().length === 0}>
            <p style={{ margin: '0', 'font-size': '13px', color: '#6B7280' }}>No ledger entries yet.</p>
          </Show>
          <Show when={ledger().length > 0}>
            <div style={{ display: 'grid', gap: '8px' }}>
              <For each={ledger()}>
                {(item: any) => (
                  <div style={{ border: '1px solid #E5E7EB', 'border-radius': '10px', padding: '10px', background: '#FCFCFD', display: 'flex', 'justify-content': 'space-between', gap: '10px', 'flex-wrap': 'wrap' }}>
                    <div>
                      <p style={{ margin: '0', 'font-size': '13px', 'font-weight': '700', color: '#111827' }}>{item.reason || item.type || 'Transaction'}</p>
                      <p style={{ margin: '4px 0 0', 'font-size': '12px', color: '#6B7280' }}>{item.created_at ? new Date(item.created_at).toLocaleString('en-IN') : '—'}</p>
                    </div>
                    <p style={{ margin: '0', 'font-size': '13px', 'font-weight': '800', color: Number(item.amount || 0) >= 0 ? '#15803D' : '#B91C1C' }}>
                      {Number(item.amount || 0) >= 0 ? '+' : ''}{item.amount || 0}
                    </p>
                  </div>
                )}
              </For>
            </div>
          </Show>
        </div>
      </Show>
    </div>
  );
}

