import { createResource, Show } from 'solid-js';
import { User } from 'lucide-solid';
import DashboardWidget from './DashboardWidget';
import type { RoleKey } from '../RoleDashboardShared';
import { PROFESSIONAL_ROLE_SET, ROLE_PREFIXES } from '../RoleDashboardShared';
import { fetchProfile } from '~/lib/api';

const API = '/api/gateway';

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

type Props = {
  roleKey: RoleKey;
};

async function fetchProfileData(roleKey: RoleKey) {
  if (PROFESSIONAL_ROLE_SET.has(roleKey) || roleKey === 'COMPANY' || roleKey === 'CUSTOMER') {
    const prefix = ROLE_PREFIXES[roleKey];
    if (!prefix) return null;
    try {
      return await fetchProfile(prefix);
    } catch {
      return null;
    }
  }
  if (roleKey === 'JOB_SEEKER') {
    const res = await apiFetch('/api/jobseeker/profile/me');
    if (!res.ok) return null;
    return await res.json();
  }
  return null;
}

const PROFILE_FIELDS: Record<string, string[]> = {
  COMPANY: ['company_name', 'industry', 'description', 'website', 'contact_email'],
  CUSTOMER: ['full_name', 'location', 'phone', 'email'],
  JOB_SEEKER: ['full_name', 'location', 'summary', 'skills', 'experience_years'],
  PROFESSIONAL: ['full_name', 'headline', 'bio', 'location', 'skills'],
};

export default function ProfileCompletionWidget(props: Props) {
  const [profile] = createResource(() => props.roleKey, fetchProfileData);

  const completion = () => {
    const p = profile();
    if (!p) return { filled: 0, total: 5, pct: 0 };
    const fields = PROFILE_FIELDS[props.roleKey] || PROFILE_FIELDS['PROFESSIONAL'];
    let filled = 0;
    for (const field of fields) {
      const val = (p as any)[field];
      if (val !== null && val !== undefined && String(val).trim() !== '') filled++;
    }
    const total = fields.length;
    const pct = total > 0 ? Math.round((filled / total) * 100) : 0;
    return { filled, total, pct };
  };

  const barColor = () => {
    const pct = completion().pct;
    if (pct >= 80) return '#059669';
    if (pct >= 50) return '#D97706';
    return '#DC2626';
  };

  return (
    <DashboardWidget
      title="Profile Completion"
      loading={profile.loading}
      error={profile.error ? 'Failed to load' : undefined}
      icon={<User size={16} />}
    >
      <Show when={!profile.loading && !profile.error}>
        <div style={{ 'margin-bottom': '8px' }}>
          <div
            style={{
              display: 'flex',
              'align-items': 'center',
              'justify-content': 'space-between',
              'margin-bottom': '6px',
            }}
          >
            <span style={{ 'font-size': '12px', color: '#6B7280' }}>
              {completion().filled} of {completion().total} fields
            </span>
            <span
              style={{
                'font-size': '15px',
                'font-weight': '800',
                color: barColor(),
              }}
            >
              {completion().pct}%
            </span>
          </div>
          <div
            style={{
              height: '8px',
              background: '#E5E7EB',
              'border-radius': '4px',
              overflow: 'hidden',
            }}
          >
            <div
              style={{
                height: '100%',
                width: `${completion().pct}%`,
                background: barColor(),
                'border-radius': '4px',
                transition: 'width 0.3s ease',
              }}
            />
          </div>
        </div>
        <p style={{ margin: '0', 'font-size': '11px', color: '#9CA3AF' }}>
          Complete your profile to build trust with {props.roleKey === 'JOB_SEEKER' ? 'employers' : 'clients'}
        </p>
      </Show>
    </DashboardWidget>
  );
}
