import { createResource, Show } from 'solid-js';
import { ShieldCheck } from 'lucide-solid';
import DashboardWidget from './DashboardWidget';
import type { RoleKey } 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 fetchVerificationStatus(roleKey: RoleKey) {
  try {
    const res = await apiFetch(`/api/me/verification-status?roleKey=${encodeURIComponent(roleKey)}`);
    if (!res.ok) return null;
    return await res.json();
  } catch {
    return null;
  }
}

const STATUS_COLORS: Record<string, string> = {
  VERIFIED: '#059669',
  PENDING: '#D97706',
  NOT_SUBMITTED: '#6B7280',
  REJECTED: '#DC2626',
  UNDER_REVIEW: '#7C3AED',
};

export default function VerificationWidget(props: Props) {
  const [status] = createResource(() => props.roleKey, fetchVerificationStatus);

  const statusLabel = () => {
    const s = status();
    if (!s) return 'Unknown';
    return String(s.status || s.verification_status || 'NOT_SUBMITTED').replace(/_/g, ' ');
  };

  const statusColor = () => {
    const s = status();
    const key = String(s?.status || s?.verification_status || 'NOT_SUBMITTED').toUpperCase();
    return STATUS_COLORS[key] || '#6B7280';
  };

  return (
    <DashboardWidget
      title="Verification Status"
      loading={status.loading}
      error={status.error ? 'Failed to load' : undefined}
      icon={<ShieldCheck size={16} />}
    >
      <Show when={!status.loading && !status.error}>
        <div
          style={{
            display: 'flex',
            'align-items': 'center',
            gap: '10px',
          }}
        >
          <div
            style={{
              width: '12px',
              height: '12px',
              'border-radius': '50%',
              background: statusColor(),
              'flex-shrink': 0,
            }}
          />
          <span
            style={{
              'font-size': '14px',
              'font-weight': '700',
              color: statusColor(),
            }}
          >
            {statusLabel()}
          </span>
        </div>
        <Show when={status()?.document_request}>
          <p style={{ margin: '8px 0 0', 'font-size': '11px', color: '#9CA3AF' }}>
            Documents requested: {status()?.document_request}
          </p>
        </Show>
      </Show>
    </DashboardWidget>
  );
}