import { createResource, For, Show } from 'solid-js';
import { Briefcase } 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 fetchJobsData(roleKey: RoleKey) {
  if (roleKey === 'COMPANY') {
    const res = await apiFetch('/api/companies/jobs?page=1&limit=100');
    if (!res.ok) return null;
    const json = await res.json();
    return Array.isArray(json?.data) ? json.data : [];
  }
  if (roleKey === 'JOB_SEEKER') {
    const res = await apiFetch('/api/jobseeker/jobs?page=1&limit=100');
    if (!res.ok) return null;
    const json = await res.json();
    return Array.isArray(json?.data) ? json.data : [];
  }
  return null;
}

function JobStatRow(props: { label: string; value: number | string; color?: string }) {
  return (
    <div
      style={{
        display: 'flex',
        'align-items': 'center',
        'justify-content': 'space-between',
        padding: '6px 0',
        'border-bottom': '1px solid #F9FAFB',
      }}
    >
      <span style={{ 'font-size': '12px', color: '#6B7280' }}>{props.label}</span>
      <span
        style={{
          'font-size': '15px',
          'font-weight': '800',
          color: props.color || '#111827',
        }}
      >
        {props.value}
      </span>
    </div>
  );
}

export default function JobsWidget(props: Props) {
  const [data, { refetch }] = createResource(() => props.roleKey, fetchJobsData);

  const stats = () => {
    const items = data() || [];
    if (props.roleKey === 'COMPANY') {
      const total = items.length;
      const active = items.filter(
        (j: any) => String(j.status || '').toUpperCase() === 'OPEN'
      ).length;
      const pending = items.filter((j: any) =>
        String(j.status || '').toUpperCase().includes('PENDING')
      ).length;
      const closed = items.filter(
        (j: any) => String(j.status || '').toUpperCase() === 'CLOSED'
      ).length;
      return { total, active, pending, closed };
    }
    if (props.roleKey === 'JOB_SEEKER') {
      const total = items.length;
      const active = items.filter(
        (j: any) => String(j.status || '').toUpperCase() === 'LIVE'
      ).length;
      const expiring = items.filter((j: any) => {
        const exp = j?.expires_at || j?.expiry_date;
        if (!exp) return false;
        return new Date(exp).getTime() - Date.now() < 7 * 24 * 60 * 60 * 1000;
      }).length;
      return { total, active, expiring };
    }
    return null;
  };

  return (
    <DashboardWidget
      title={props.roleKey === 'COMPANY' ? 'My Job Posts' : 'Available Jobs'}
      loading={data.loading}
      error={data.error ? 'Failed to load' : undefined}
      icon={<Briefcase size={16} />}
    >
      <Show when={stats() && props.roleKey === 'COMPANY'}>
        <For each={[
          ['Total Jobs', stats()!.total, '#374151'],
          ['Active', stats()!.active, '#059669'],
          ['Pending Approval', stats()!.pending, '#D97706'],
          ['Closed', stats()!.closed, '#6B7280'],
        ]}>
          {([label, value, color]) => <JobStatRow label={label} value={value} color={color} />}
        </For>
      </Show>
      <Show when={stats() && props.roleKey === 'JOB_SEEKER'}>
        <For each={[
          ['Total Jobs', stats()!.total, '#374151'],
          ['Live Now', stats()!.active, '#059669'],
          ['Expiring Soon', stats()!.expiring, '#D97706'],
        ]}>
          {([label, value, color]) => <JobStatRow label={label} value={value} color={color} />}
        </For>
      </Show>
    </DashboardWidget>
  );
}
