'use client';

import { useCallback, useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { api } from '@/lib/api';
import { useAuth } from '@/components/auth-context';
import { toast } from 'react-toastify';
import { showConfirmDelete } from '@/lib/confirm';
import BackToDashboard from '@/components/BackToDashboard';
import { PageLoader } from '@/components/DotLoader';

interface Param {
  id: number; key: string; label: string; description: string;
  weight: number; is_active: boolean; sort_order: number;
}

const EMPTY = { key: '', label: '', description: '', weight: 10, is_active: true, sort_order: 0 };

export default function RankParametersPage() {
  const router = useRouter();
  const { user: me } = useAuth();
  const [loading, setLoading] = useState(true);
  const [rows, setRows] = useState<Param[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [editId, setEditId] = useState<number | null>(null);
  const [form, setForm] = useState<any>(EMPTY);
  const [saving, setSaving] = useState(false);

  const load = useCallback(async () => {
    const res = (await api.get('/pipeline/rank-parameters/')) as any;
    setRows(res?.data ?? []);
  }, []);

  useEffect(() => {
    if (!me) return;
    (async () => {
      try {
        if (me.role !== 'ADMIN') { router.push('/dashboard'); return; }
        await load();
      } finally { setLoading(false); }
    })();
  }, [me, router, load]);

  const openCreate = () => { setEditId(null); setForm({ ...EMPTY, sort_order: rows.length + 1 }); setShowModal(true); };
  const openEdit = (p: Param) => { setEditId(p.id); setForm({ ...p }); setShowModal(true); };

  const slugify = (s: string) => s.toLowerCase().trim().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '');

  const save = async () => {
    const payload = { ...form, key: form.key || slugify(form.label) };
    if (!payload.label.trim() || !payload.key) { toast.warning('Label is required.'); return; }
    setSaving(true);
    try {
      if (editId) await api.put(`/pipeline/rank-parameters/${editId}/`, payload);
      else await api.post('/pipeline/rank-parameters/', payload);
      toast.success(editId ? 'Parameter updated' : 'Parameter added');
      setShowModal(false); load();
    } catch (e: any) { toast.error(e?.message || 'Save failed'); }
    finally { setSaving(false); }
  };

  const remove = async (p: Param) => {
    const r = await showConfirmDelete(`Delete parameter "${p.label}"?`);
    if (!r.isConfirmed) return;
    await api.delete(`/pipeline/rank-parameters/${p.id}/`);
    toast.success('Deleted'); load();
  };

  const total = rows.filter((r) => r.is_active).reduce((a, b) => a + Number(b.weight || 0), 0);
  const inputCls = 'w-full bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 px-3 py-2 text-xs focus:outline-none focus:border-[#405189] text-slate-800 dark:text-white';

  if (loading) return <PageLoader />;

  return (
    <>
        <main className="flex-1 p-6 overflow-x-auto">
          <BackToDashboard />
          <div className="flex items-center justify-between mb-4 gap-3 flex-wrap">
            <p className="text-xs text-slate-500 dark:text-slate-400">
              Define the scoring parameters the AI uses to rank candidates. Add/remove without any code change.
              <span className={`ml-2 font-bold ${total === 100 ? 'text-emerald-600' : 'text-amber-600'}`}>Active weights total: {total}{total !== 100 ? ' (aim for 100)' : ' ✓'}</span>
            </p>
            <button onClick={openCreate} className="bg-[#405189] hover:bg-[#364574] text-white px-4 py-2 text-xs font-bold cursor-pointer"><i className="fa-solid fa-plus mr-1.5"></i>Add Parameter</button>
          </div>

          <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 shadow-sm overflow-x-auto">
            <table className="w-full text-xs">
              <thead className="bg-slate-50 dark:bg-slate-950/40 text-slate-400 text-left text-[10px] uppercase">
                <tr>{['Order', 'Label', 'Key', 'Description', 'Weight', 'Active', 'Actions'].map((h) => <th key={h} className="px-4 py-2.5 font-semibold">{h}</th>)}</tr>
              </thead>
              <tbody>
                {rows.length === 0 ? (
                  <tr><td colSpan={7} className="px-4 py-10 text-center text-slate-400">No parameters. Add one to define how candidates are scored.</td></tr>
                ) : rows.map((p) => (
                  <tr key={p.id} className="border-t border-slate-100 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/40 align-top">
                    <td className="px-4 py-2.5 text-slate-400">{p.sort_order}</td>
                    <td className="px-4 py-2.5 font-bold text-slate-700 dark:text-slate-200">{p.label}</td>
                    <td className="px-4 py-2.5 font-mono text-slate-500">{p.key}</td>
                    <td className="px-4 py-2.5 text-slate-500 dark:text-slate-400 max-w-[320px]">{p.description || '—'}</td>
                    <td className="px-4 py-2.5 font-bold text-[#405189]">{p.weight}</td>
                    <td className="px-4 py-2.5"><span className={`text-[10px] font-bold px-2 py-0.5 ${p.is_active ? 'bg-emerald-50 text-emerald-700' : 'bg-slate-100 text-slate-400'}`}>{p.is_active ? 'Active' : 'Off'}</span></td>
                    <td className="px-4 py-2.5">
                      <div className="flex items-center gap-1.5">
                        <button onClick={() => openEdit(p)} className="w-7 h-7 flex items-center justify-center border border-[#405189]/30 bg-[#405189]/10 text-[#405189] hover:bg-[#405189] hover:text-white transition cursor-pointer"><i className="fa-solid fa-pen text-[11px]"></i></button>
                        <button onClick={() => remove(p)} className="w-7 h-7 flex items-center justify-center border border-rose-300/40 bg-rose-50 text-rose-500 hover:bg-rose-500 hover:text-white transition cursor-pointer"><i className="fa-solid fa-trash text-[11px]"></i></button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </main>

      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="absolute inset-0 bg-slate-950/60 backdrop-blur-sm" onClick={() => !saving && setShowModal(false)} />
          <div className="relative z-10 w-full max-w-lg bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 shadow-2xl p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-slate-900 dark:text-white">{editId ? 'Edit Parameter' : 'Add Parameter'}</h3>
              <button onClick={() => !saving && setShowModal(false)} className="w-8 h-8 flex items-center justify-center text-slate-400 hover:text-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800 cursor-pointer"><i className="fa-solid fa-xmark"></i></button>
            </div>
            <div className="space-y-3">
              <div>
                <label className="block text-[10px] uppercase font-bold text-slate-400 mb-1">Label</label>
                <input value={form.label} onChange={(e) => setForm({ ...form, label: e.target.value, key: editId ? form.key : slugify(e.target.value) })} placeholder="e.g. Communication Skills" className={inputCls} />
              </div>
              <div>
                <label className="block text-[10px] uppercase font-bold text-slate-400 mb-1">Key <span className="normal-case font-semibold text-slate-400">— machine name (auto from label)</span></label>
                <input value={form.key} onChange={(e) => setForm({ ...form, key: slugify(e.target.value) })} disabled={!!editId} placeholder="communication" className={`${inputCls} ${editId ? 'opacity-60' : ''} font-mono`} />
              </div>
              <div>
                <label className="block text-[10px] uppercase font-bold text-slate-400 mb-1">Description <span className="normal-case font-semibold text-slate-400">— guidance sent to the AI</span></label>
                <textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} rows={2} placeholder="How should the AI judge this parameter?" className={inputCls} />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-[10px] uppercase font-bold text-slate-400 mb-1">Weight (share of 100)</label>
                  <input type="number" min="0" max="100" value={form.weight} onChange={(e) => setForm({ ...form, weight: Number(e.target.value) })} className={inputCls} />
                </div>
                <div>
                  <label className="block text-[10px] uppercase font-bold text-slate-400 mb-1">Sort Order</label>
                  <input type="number" value={form.sort_order} onChange={(e) => setForm({ ...form, sort_order: Number(e.target.value) })} className={inputCls} />
                </div>
              </div>
              <label className="flex items-center gap-2 text-xs font-semibold text-slate-600 dark:text-slate-300 cursor-pointer">
                <input type="checkbox" checked={form.is_active} onChange={(e) => setForm({ ...form, is_active: e.target.checked })} className="accent-[#405189]" /> Active
              </label>
              <div className="flex justify-end gap-3 pt-2">
                <button onClick={() => setShowModal(false)} className="border border-slate-200 dark:border-slate-800 px-5 py-2 text-xs font-semibold cursor-pointer">Cancel</button>
                <button onClick={save} disabled={saving} className="bg-[#405189] hover:bg-[#364574] disabled:opacity-50 text-white px-6 py-2 text-xs font-extrabold cursor-pointer">{saving ? 'Saving…' : 'Save'}</button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
