'use client';

import { useEffect, useMemo, useState } from 'react';
import { motion } from 'framer-motion';
import { toast } from 'react-toastify';
import { api } from '@/lib/api';

interface CandidateOption {
  id: number;
  full_name: string;
  email: string | null;
  phone_number: string;
  total_experience: number | null;
  current_company: string | null;
}

interface AddCandidateModalProps {
  jobId: string | number;
  /** Candidates already in this JD's pipeline — hidden from the picker. */
  existingIds: Set<number>;
  onClose: () => void;
  /** Called with the newly added candidate ids so the page can refresh + preselect them. */
  onAdded: (candidateIds: number[]) => void;
}

export default function AddCandidateModal({ jobId, existingIds, onClose, onAdded }: AddCandidateModalProps) {
  const [candidates, setCandidates] = useState<CandidateOption[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [selected, setSelected] = useState<Set<number>>(new Set());
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    (api.get('/candidates/') as Promise<{ data: CandidateOption[] }>)
      .then((res) => setCandidates(Array.isArray(res.data) ? res.data : []))
      .catch((e) => {
        toast.error(e instanceof Error ? e.message : 'Failed to load candidates');
        onClose();
      })
      .finally(() => setLoading(false));
  }, [onClose]);

  const available = useMemo(() => {
    const q = search.trim().toLowerCase();
    return candidates
      .filter((c) => !existingIds.has(c.id))
      .filter((c) =>
        !q
        || c.full_name.toLowerCase().includes(q)
        || (c.email || '').toLowerCase().includes(q)
        || c.phone_number.includes(q)
      );
  }, [candidates, existingIds, search]);

  const toggle = (id: number) =>
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });

  const add = async () => {
    if (!selected.size) return;
    setSaving(true);
    const ids = Array.from(selected);
    const results = await Promise.allSettled(
      ids.map((cid) => api.post('/pipeline/applications/', { candidate: cid, job: Number(jobId) }))
    );
    const failed = results.filter((r) => r.status === 'rejected').length;
    const added = ids.length - failed;
    setSaving(false);
    if (added) toast.success(`${added} candidate${added === 1 ? '' : 's'} added to this JD`);
    if (failed) toast.warn(`${failed} could not be added`);
    onAdded(ids);
    onClose();
  };

  return (
    <div className="fixed inset-0 z-[100] flex items-start justify-center bg-slate-950/60 backdrop-blur-sm p-4 overflow-y-auto" onClick={onClose}>
      <motion.div
        initial={{ opacity: 0, y: 24 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.25 }}
        onClick={(e) => e.stopPropagation()}
        className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none shadow-2xl w-full max-w-6xl my-8"
      >
        <div className="flex items-center justify-between gap-3 px-5 py-4 bg-[#405189]">
          <div>
            <p className="text-[10px] font-extrabold uppercase tracking-widest text-indigo-200">AI Screening</p>
            <h2 className="text-base font-bold text-white">Add candidates to this JD</h2>
          </div>
          <button
            onClick={onClose}
            className="w-8 h-8 flex items-center justify-center text-white/80 hover:text-white hover:bg-white/10 transition cursor-pointer"
          >
            <i className="fa-solid fa-xmark" />
          </button>
        </div>

        <div className="p-5">
          <div className="relative mb-3">
            <i className="fa-solid fa-magnifying-glass absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-xs" />
            <input
              autoFocus
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search by name, email or phone..."
              className="w-full bg-slate-50 dark:bg-slate-950 border border-slate-200 dark:border-slate-800 focus:border-indigo-500 rounded-none pl-8 pr-3 py-2 text-sm text-slate-900 dark:text-white focus:outline-none transition"
            />
          </div>

          <div className="border border-slate-200 dark:border-slate-800 rounded-none max-h-[45vh] overflow-y-auto custom-scrollbar divide-y divide-slate-100 dark:divide-slate-800">
            {loading ? (
              [...Array(5)].map((_, i) => (
                <div key={i} className="h-14 bg-slate-100 dark:bg-slate-800 animate-pulse m-1" />
              ))
            ) : available.length === 0 ? (
              <p className="text-sm text-slate-400 dark:text-slate-500 text-center py-8">
                {candidates.length && !search
                  ? 'All candidates are already in this JD’s pipeline.'
                  : 'No candidates match your search.'}
              </p>
            ) : (
              available.map((c) => (
                <label
                  key={c.id}
                  className="flex items-center gap-3 px-3 py-2.5 hover:bg-slate-50 dark:hover:bg-slate-800/50 transition cursor-pointer"
                >
                  <input
                    type="checkbox"
                    checked={selected.has(c.id)}
                    onChange={() => toggle(c.id)}
                    className="w-3.5 h-3.5 accent-indigo-600 cursor-pointer shrink-0"
                  />
                  <span className="w-8 h-8 rounded-full bg-indigo-100 dark:bg-indigo-950/60 text-indigo-600 dark:text-indigo-300 flex items-center justify-center text-[10px] font-extrabold uppercase shrink-0">
                    {c.full_name.slice(0, 2)}
                  </span>
                  <span className="min-w-0 flex-1">
                    <span className="block text-xs font-bold text-slate-800 dark:text-white truncate">{c.full_name}</span>
                    <span className="block text-[10px] text-slate-400 dark:text-slate-500 font-medium truncate">
                      {[c.email, c.phone_number].filter(Boolean).join(' · ')}
                    </span>
                  </span>
                  <span className="text-[10px] font-semibold text-slate-400 dark:text-slate-500 shrink-0">
                    {c.total_experience ? `${c.total_experience} yrs` : 'Fresher'}
                    {c.current_company ? ` · ${c.current_company}` : ''}
                  </span>
                </label>
              ))
            )}
          </div>

          <div className="flex items-center justify-between mt-4">
            <p className="text-[11px] font-semibold text-slate-500 dark:text-slate-400">
              {selected.size} selected — they&apos;ll appear in the screening table, ready to call
            </p>
            <div className="flex gap-2">
              <button
                onClick={onClose}
                className="px-4 py-2 rounded-none text-sm font-semibold text-slate-500 hover:text-slate-900 dark:text-slate-400 dark:hover:text-white transition cursor-pointer"
              >
                Cancel
              </button>
              <button
                onClick={add}
                disabled={!selected.size || saving}
                className="bg-[#405189] hover:bg-[#364574] text-white px-4 py-2 rounded-none text-sm font-medium transition cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {saving ? (
                  <><i className="fa-solid fa-spinner fa-spin mr-2" />Adding...</>
                ) : (
                  <><i className="fa-solid fa-user-plus mr-2" />Add{selected.size ? ` (${selected.size})` : ''}</>
                )}
              </button>
            </div>
          </div>
        </div>
      </motion.div>
    </div>
  );
}
