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

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

  const stats = () => {
    const items = data() || [];
    if (props.roleKey === 'COMPANY') {
      const shortlisted = items.filter(
        (a: any) => String(a.status || '').toUpperCase() === 'SHORTLISTED'
      ).length;
      const interview = items.filter(
        (a: any) => String(a.status || '').toUpperCase() === 'INTERVIEW_SCHEDULED'
      ).length;
      const offer = items.filter(
        (a: any) => String(a.status || '').toUpperCase() === 'OFFER_EXTENDED'
      ).length;
      return { shortlisted, interview, offer };
    }
    if (props.roleKey === 'CUSTOMER') {
      const shortlisted = items.reduce(
        (sum: number, r: any) => sum + (Number(r.shortlisted_count) || 0),
        0
      );
      const newResponses = items.reduce(
        (sum: number, r: any) => sum + (Number(r.new_responses_count) || 0),
        0
      );
      return { shortlisted, newResponses };
    }
    return null;
  };

  return (
    <DashboardWidget
      title={props.roleKey === 'COMPANY' ? 'Shortlisted Candidates' : 'Shortlisted Responses'}
      loading={data.loading}
      error={data.error ? 'Failed to load' : undefined}
      icon={<Star size={16} />}
    >
      <Show when={stats() && props.roleKey === 'COMPANY'}>
        <For each={[
          ['Shortlisted', stats()!.shortlisted, '#059669'],
          ['Interview Scheduled', stats()!.interview, '#7C3AED'],
          ['Offer Extended', stats()!.offer, '#D97706'],
        ]}>
          {([label, value, color]) => <ShortlistStatRow label={label} value={value} color={color} />}
        </For>
      </Show>
      <Show when={stats() && props.roleKey === 'CUSTOMER'}>
        <For each={[
          ['Total Shortlisted', stats()!.shortlisted, '#059669'],
          ['New Responses', stats()!.newResponses, '#7C3AED'],
        ]}>
          {([label, value, color]) => <ShortlistStatRow label={label} value={value} color={color} />}
        </For>
      </Show>
    </DashboardWidget>
  );
}
