'use client';

import { useEffect, useState } from 'react';
import { api } from '@/lib/api';
import type { CandidateReportFiltersState, FilterOption } from './types';
import { CLASSIFICATIONS, EMPTY_CR_FILTERS } from './types';

// Candidate.StatusChoices on the backend
const CANDIDATE_STATUSES = ['Draft', 'Profile Completed', 'Verified', 'Blocked'];

/** Extract an array from any of the API envelope shapes used by the backend. */
function listOf(res: unknown): any[] {
  const body = res as { data?: unknown; results?: unknown[] };
  if (Array.isArray(body?.data)) return body.data;
  const d = body?.data as { results?: unknown[] } | undefined;
  if (d && Array.isArray(d.results)) return d.results;
  if (Array.isArray(body?.results)) return body.results;
  return [];
}

interface CandidateReportFiltersProps {
  filters: CandidateReportFiltersState;
  onChange: (filters: CandidateReportFiltersState) => void;
}

export default function CandidateReportFilters({ filters, onChange }: CandidateReportFiltersProps) {
  const [clients, setClients] = useState<FilterOption[]>([]);
  const [jobs, setJobs] = useState<FilterOption[]>([]);
  const [recruiters, setRecruiters] = useState<FilterOption[]>([]);
  const [search, setSearch] = useState(filters.search);

  useEffect(() => {
    // Dropdown sources — each degrades to an empty list if this role can't read it
    api.get('/clients/')
      .then((r) => setClients(listOf(r).map((c: any) => ({ value: String(c.id), label: c.name }))))
      .catch(() => {});
    api.get('/jobs/')
      .then((r) => setJobs(listOf(r).map((j: any) => ({ value: String(j.id), label: j.title }))))
      .catch(() => {});
    api.get('/users/dashboard/total-recruiters/')
      .then((r) => setRecruiters(listOf(r).map((u: any) => ({ value: String(u.id), label: u.full_name || u.email }))))
      .catch(() => {});
  }, []);

  // Debounce the free-text search so we don't refetch on every keystroke
  useEffect(() => {
    const t = setTimeout(() => {
      if (search !== filters.search) onChange({ ...filters, search });
    }, 400);
    return () => clearTimeout(t);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [search]);

  useEffect(() => setSearch(filters.search), [filters.search]);

  const set = (key: keyof CandidateReportFiltersState) =>
    (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) =>
      onChange({ ...filters, [key]: e.target.value });

  const hasActive = Object.values(filters).some(Boolean);

  const fieldCls =
    'w-full bg-slate-50 dark:bg-slate-950 border border-slate-200 dark:border-slate-800 focus:border-indigo-500 rounded-none px-3 py-2 text-sm text-slate-900 dark:text-white focus:outline-none transition';
  const labelCls = 'block text-[11px] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-1';

  return (
    <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none p-4 shadow-sm">
      <div className="flex items-center justify-between mb-3">
        <h3 className="text-sm font-semibold text-slate-700 dark:text-slate-200 flex items-center gap-2">
          <i className="fa-solid fa-filter text-indigo-500 text-xs" />
          Filters
        </h3>
        {hasActive && (
          <button
            onClick={() => { setSearch(''); onChange({ ...EMPTY_CR_FILTERS }); }}
            className="text-xs font-semibold text-indigo-600 dark:text-indigo-400 hover:underline cursor-pointer"
          >
            <i className="fa-solid fa-rotate-left mr-1 text-[10px]" />
            Reset
          </button>
        )}
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
        <div className="sm:col-span-2 lg:col-span-2">
          <label className={labelCls}>Candidate Search</label>
          <div className="relative">
            <i className="fa-solid fa-magnifying-glass absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-xs" />
            <input
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search by name or email..."
              className={`${fieldCls} pl-8`}
            />
          </div>
        </div>
        <div>
          <label className={labelCls}>From</label>
          <input type="date" value={filters.date_from} onChange={set('date_from')} className={fieldCls} />
        </div>
        <div>
          <label className={labelCls}>To</label>
          <input type="date" value={filters.date_to} onChange={set('date_to')} className={fieldCls} />
        </div>
        <div>
          <label className={labelCls}>Client</label>
          <select value={filters.client} onChange={set('client')} className={fieldCls}>
            <option value="">All Clients</option>
            {clients.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
          </select>
        </div>
        <div>
          <label className={labelCls}>Job Description</label>
          <select value={filters.job} onChange={set('job')} className={fieldCls}>
            <option value="">All JDs</option>
            {jobs.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
          </select>
        </div>
        <div>
          <label className={labelCls}>Recruiter</label>
          <select value={filters.recruiter} onChange={set('recruiter')} className={fieldCls}>
            <option value="">All Recruiters</option>
            {recruiters.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
          </select>
        </div>
        <div>
          <label className={labelCls}>Candidate Status</label>
          <select value={filters.status} onChange={set('status')} className={fieldCls}>
            <option value="">All Statuses</option>
            {CANDIDATE_STATUSES.map((s) => <option key={s} value={s}>{s}</option>)}
          </select>
        </div>
        <div>
          <label className={labelCls}>Classification</label>
          <select value={filters.classification} onChange={set('classification')} className={fieldCls}>
            <option value="">All Classifications</option>
            {CLASSIFICATIONS.map((c) => <option key={c} value={c}>{c}</option>)}
          </select>
        </div>
      </div>
    </div>
  );
}
