'use client';

import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import StatusBadge from '@/components/ats/status-badge';
import DecisionActions from '@/components/ats/decision-actions';
import DecisionHistoryDrawer from '@/components/ats/decision-history-drawer';
import Loading from '@/components/ui/loading';
import Empty from '@/components/ui/empty';

export default function JobMatchesPage() {
  const params = useParams();
  const jobid = params.jobid as string;

  const [items, set_items] = useState<any[] | null>(null);
  const [history_open, set_history_open] = useState(false);
  const [history_mcid, set_history_mcid] = useState<number | null>(null);

  useEffect(() => {
    fetch(`/api/recruiter/jobs/${jobid}/matches`)
      .then(r => r.json())
      .then(d => set_items(d.candidates || []));
  }, [jobid]);

  function decide(id: number, decision: 'accept' | 'reject') {
    fetch(`/api/recruiter/matches/${id}/decision`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ decision })
    }).then(() => location.reload());
  }

  function open_history(match_candidate_id: number) {
    set_history_mcid(match_candidate_id);
    set_history_open(true);
  }

  if (items === null) {
    return <Loading />;
  }

  if (items.length === 0) {
    return <Empty label="aucun candidat pour cette offre" />;
  }

  return (
    <div className="page">
      <h1>candidats pour l’offre</h1>

      <table>
        <thead>
          <tr>
            <th>candidat</th>
            <th>score</th>
            <th>statut</th>
            <th>actions</th>
          </tr>
        </thead>

        <tbody>
          {items.map((i: any) => (
            <tr key={i.matchCandidateId}>
              <td>{i.first_name} {i.last_name}</td>
              <td>{i.score}</td>
              <td>
                <StatusBadge status={i.status} />
              </td>
              <td>
                <DecisionActions
                  status={i.status}
                  onAccept={() => decide(i.matchCandidateId, 'accept')}
                  onReject={() => decide(i.matchCandidateId, 'reject')}
                />
                <button
                  style={{ marginLeft: 6 }}
                  onClick={() => open_history(i.matchCandidateId)}
                >
                  historique
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>

      <DecisionHistoryDrawer
        matchCandidateId={history_mcid}
        open={history_open}
        onClose={() => set_history_open(false)}
      />
    </div>
  );
}
