import { createResource } from 'solid-js';
import { Coins } from 'lucide-solid';
import DashboardWidget from './DashboardWidget';
import type { RoleKey } from '../RoleDashboardShared';
import { ROLE_PREFIXES } from '../RoleDashboardShared';

const API = '';

async function apiFetch(path: string, opts?: RequestInit) {
  const token =
    typeof window !== 'undefined'
      ? window.sessionStorage.getItem('nxtgauge_access_token') || ''
      : '';
  return fetch(`${API}${path}`, {
    ...opts,
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...(opts?.headers ?? {}),
    },
  });
}

type Props = {
  roleKey: RoleKey;
};

async function fetchWallet(roleKey: RoleKey): Promise<{ balance: number; reserved: number } | null> {
  const prefix = ROLE_PREFIXES[roleKey];
  if (!prefix) return null;
  try {
    const res = await apiFetch(`/api/${prefix}/wallet/me`);
    if (!res.ok) return null;
    return await res.json();
  } catch {
    return null;
  }
}

export default function WalletWidget(props: Props) {
  const [wallet] = createResource(() => props.roleKey, fetchWallet);
  const isCredits = () =>
    props.roleKey === 'COMPANY' || props.roleKey === 'CUSTOMER' || props.roleKey === 'JOB_SEEKER';

  return (
    <DashboardWidget
      title={isCredits() ? 'Credits' : 'Tracecoins'}
      loading={wallet.loading}
      error={wallet.error ? 'Failed to load' : undefined}
      icon={<Coins size={16} />}
    >
      <div style={{ display: 'grid', 'grid-template-columns': '1fr 1fr', gap: '10px' }}>
        <div>
          <p
            style={{
              margin: '0',
              'font-size': '10px',
              'text-transform': 'uppercase',
              'letter-spacing': '0.05em',
              color: '#6B7280',
            }}
          >
            Available
          </p>
          <p
            style={{
              margin: '4px 0 0',
              'font-size': '22px',
              'font-weight': '800',
              color: '#111827',
            }}
          >
            {wallet()?.balance ?? '—'}
          </p>
        </div>
        <div>
          <p
            style={{
              margin: '0',
              'font-size': '10px',
              'text-transform': 'uppercase',
              'letter-spacing': '0.05em',
              color: '#6B7280',
            }}
          >
            Reserved
          </p>
          <p
            style={{
              margin: '4px 0 0',
              'font-size': '22px',
              'font-weight': '800',
              color: '#111827',
            }}
          >
            {wallet()?.reserved ?? '—'}
          </p>
        </div>
      </div>
    </DashboardWidget>
  );
}
