import { createResource, Show } from 'solid-js';
import { User } from 'lucide-solid';
import DashboardWidget from './DashboardWidget';
import type { RoleKey } from '../RoleDashboardShared';
import { apiFetch } from '~/lib/api';
import { fetchOnboardingSchemaForRole } from '~/lib/runtime/storage';

type Props = {
  roleKey: RoleKey;
};

// Same source of truth the wizard itself uses (fetchOnboardingSchemaForRole)
// and the same storage the wizard writes to (/api/profile?roleKey=...) — so
// this can never drift from what fields actually exist / get saved for a role,
// unlike a hardcoded per-role field list.
async function fetchCompletionInputs(roleKey: RoleKey) {
  const [schema, profileRes] = await Promise.all([
    fetchOnboardingSchemaForRole(roleKey),
    apiFetch(`/api/profile?roleKey=${roleKey}`).catch(() => null),
  ]);
  const requiredFieldIds = (schema?.steps ?? [])
    .filter((step) => step.type !== 'review')
    .flatMap((step) => step.fields)
    .filter((field) => field.required)
    .map((field) => field.id);
  const profileData = profileRes?.profile_data ?? {};
  return { requiredFieldIds, profileData };
}

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

  const completion = () => {
    const d = data();
    if (!d || d.requiredFieldIds.length === 0) return { filled: 0, total: 0, pct: 0 };
    let filled = 0;
    for (const id of d.requiredFieldIds) {
      const val = (d.profileData as any)[id];
      if (val !== null && val !== undefined && String(val).trim() !== '') filled++;
    }
    const total = d.requiredFieldIds.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={data.loading}
      error={data.error ? 'Failed to load' : undefined}
      icon={<User size={16} />}
    >
      <Show when={!data.loading && !data.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>
  );
}
