import { For, Show, createSignal, onMount } from 'solid-js';
import { BTN_GHOST, CARD } from '~/components/DashboardShell';

const API = '';

type JobItem = { id: string; title: string };
type ApplicationItem = {
  id: string;
  job_id: string;
  applicant_user_id: string;
  status: string;
  applied_at?: string;
  cover_note?: string | null;
};

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 ?? {}),
    },
  });
}

export default function CompanyShortlistedCandidatesPage() {
  const [rows, setRows] = createSignal<Array<ApplicationItem & { job_title?: string }>>([]);
  const [loading, setLoading] = createSignal(true);
  const [err, setErr] = createSignal('');

  const loadAllShortlisted = async () => {
    setLoading(true);
    setErr('');
    try {
      const jobsRes = await apiFetch('/api/companies/jobs?page=1&limit=100');
      const jobsPayload = await jobsRes.json().catch(() => ({}));
      const jobs = (Array.isArray(jobsPayload?.data) ? jobsPayload.data : []) as JobItem[];
      const titleById = new Map(jobs.map((j) => [j.id, j.title]));

      const allRows: Array<ApplicationItem & { job_title?: string }> = [];
      for (const job of jobs) {
        const res = await apiFetch(`/api/companies/jobs/${job.id}/applications?page=1&limit=100&status=SHORTLISTED`);
        if (!res.ok) continue;
        const payload = await res.json().catch(() => ({}));
        const list = Array.isArray(payload?.data) ? payload.data : [];
        for (const app of list) {
          allRows.push({ ...app, job_title: titleById.get(app.job_id) || job.title });
        }
      }
      setRows(allRows);
    } catch {
      setErr('Failed to load shortlisted candidates.');
      setRows([]);
    } finally {
      setLoading(false);
    }
  };

  onMount(loadAllShortlisted);

  return (
    <div style={{ display: 'grid', gap: '14px', 'max-width': '980px' }}>
      <div style={CARD}>
        <p style={{ margin: '0', 'font-size': '18px', 'font-weight': '800', color: '#111827' }}>Shortlisted Candidates</p>
        <p style={{ margin: '4px 0 0', 'font-size': '13px', color: '#6B7280' }}>Candidates shortlisted across all approved job posts.</p>
      </div>

      <Show when={err()}>
        <div style={{ ...CARD, border: '1px solid #FECACA', background: '#FEF2F2', padding: '12px 14px', color: '#B91C1C', 'font-size': '13px', 'font-weight': '600' }}>{err()}</div>
      </Show>

      <div style={CARD}>
        <div style={{ display: 'flex', 'justify-content': 'space-between', 'align-items': 'center', 'margin-bottom': '10px' }}>
          <p style={{ margin: '0', 'font-size': '16px', 'font-weight': '700', color: '#111827' }}>Candidate List</p>
          <button type="button" onClick={loadAllShortlisted} style={BTN_GHOST}>Refresh</button>
        </div>
        <Show when={loading()}>
          <p style={{ margin: '0', color: '#9CA3AF', 'font-size': '13px' }}>Loading shortlisted candidates...</p>
        </Show>
        <Show when={!loading() && rows().length === 0}>
          <p style={{ margin: '0', color: '#6B7280', 'font-size': '13px' }}>No shortlisted candidates yet.</p>
        </Show>
        <Show when={!loading() && rows().length > 0}>
          <div style={{ display: 'grid', gap: '10px' }}>
            <For each={rows()}>
              {(row) => (
                <div style={{ border: '1px solid #E5E7EB', 'border-radius': '12px', padding: '12px', background: '#FCFCFD' }}>
                  <div style={{ display: 'flex', 'justify-content': 'space-between', gap: '10px', 'flex-wrap': 'wrap' }}>
                    <div>
                      {/* This label identifies the candidate (job_seeker_id), not the application
                          record, so it is not a candidate for the new application reference_number
                          field. Leaving the truncated id as-is pending backend confirmation of
                          whether a human-readable candidate identifier should be shown instead. */}
                      <p style={{ margin: '0', 'font-size': '14px', 'font-weight': '800', color: '#111827' }}>
                        Candidate #{row.applicant_user_id?.slice(0, 8) || row.id.slice(0, 8)}
                      </p>
                      <p style={{ margin: '4px 0 0', 'font-size': '12px', color: '#6B7280' }}>
                        {row.job_title || '—'} {row.applied_at ? `• ${new Date(row.applied_at).toLocaleString('en-IN')}` : ''}
                      </p>
                    </div>
                    <span style={{ display: 'inline-flex', height: '24px', 'align-items': 'center', padding: '0 10px', 'border-radius': '999px', background: '#FFF1EB', color: '#C2410C', 'font-size': '11px', 'font-weight': '700' }}>
                      {String(row.status || 'SHORTLISTED').replace(/_/g, ' ')}
                    </span>
                  </div>
                  <p style={{ margin: '8px 0 0', 'font-size': '13px', color: '#374151' }}>{row.cover_note || 'No cover note available.'}</p>
                </div>
              )}
            </For>
          </div>
        </Show>
      </div>
    </div>
  );
}

