'use client';

import { useEffect, useState } from 'react';
import { api } from '@/lib/api';
import type { FilterOption, ReportFiltersState } from './types';
import { EMPTY_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 ReportFiltersProps {
  filters: ReportFiltersState;
  onChange: (filters: ReportFiltersState) => void;
}

export default function ReportFilters({ filters, onChange }: ReportFiltersProps) {
  const [clients, setClients] = useState<FilterOption[]>([]);
  const [jobs, setJobs] = useState<FilterOption[]>([]);
  const [recruiters, setRecruiters] = useState<FilterOption[]>([]);

  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(() => {});
  }, []);

  const set = (key: keyof ReportFiltersState) => (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={() => onChange({ ...EMPTY_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-3 xl:grid-cols-6 gap-3">
        <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>
    </div>
  );
}
