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

function AppStatRow(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 ApplicationsWidget(props: Props) {
  const [data] = createResource(() => props.roleKey, fetchApplicationsData);

  const stats = () => {
    const items = data() || [];
    if (props.roleKey === 'COMPANY') {
      const total = items.length;
      const shortlisted = items.filter(
        (a: any) => String(a.status || '').toUpperCase() === 'SHORTLISTED'
      ).length;
      const underReview = items.filter(
        (a: any) =>
          !['SHORTLISTED', 'REJECTED', 'HIRED'].includes(String(a.status || '').toUpperCase())
      ).length;
      const rejected = items.filter(
        (a: any) => String(a.status || '').toUpperCase() === 'REJECTED'
      ).length;
      return { total, shortlisted, underReview, rejected };
    }
    if (props.roleKey === 'JOB_SEEKER') {
      const total = items.length;
      const shortlisted = items.filter(
        (a: any) => String(a.status || '').toUpperCase() === 'SHORTLISTED'
      ).length;
      const hired = items.filter(
        (a: any) => String(a.status || '').toUpperCase() === 'HIRED'
      ).length;
      const offered = items.filter(
        (a: any) => String(a.status || '').toUpperCase() === 'OFFERED'
      ).length;
      return { total, shortlisted, hired, offered };
    }
    return null;
  };

  return (
    <DashboardWidget
      title={props.roleKey === 'COMPANY' ? 'Applications Received' : 'My Applications'}
      loading={data.loading}
      error={data.error ? 'Failed to load' : undefined}
      icon={<FileText size={16} />}
    >
      <Show when={stats() && props.roleKey === 'COMPANY'}>
        <For each={[
          ['Total', stats()!.total, '#374151'],
          ['Shortlisted', stats()!.shortlisted, '#059669'],
          ['Under Review', stats()!.underReview, '#D97706'],
          ['Rejected', stats()!.rejected, '#6B7280'],
        ]}>
          {([label, value, color]) => <AppStatRow label={label} value={value} color={color} />}
        </For>
      </Show>
      <Show when={stats() && props.roleKey === 'JOB_SEEKER'}>
        <For each={[
          ['Total Applied', stats()!.total, '#374151'],
          ['Shortlisted', stats()!.shortlisted, '#059669'],
          ['Hired', stats()!.hired, '#059669'],
          ['Offered', stats()!.offered, '#7C3AED'],
        ]}>
          {([label, value, color]) => <AppStatRow label={label} value={value} color={color} />}
        </For>
      </Show>
    </DashboardWidget>
  );
}
