'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 Stage {
  id: number;
  name: string;
  code: string;
  sort_order: number;
  outcome: 'IN_PROGRESS' | 'WON' | 'LOST';
  is_active: boolean;
}

const OUTCOMES = [
  { value: 'IN_PROGRESS', label: 'In Progress' },
  { value: 'WON', label: 'Won' },
  { value: 'LOST', label: 'Lost' },
];

const OUTCOME_BADGE: Record<string, string> = {
  IN_PROGRESS: 'text-[#405189] bg-[#405189]/10',
  WON: 'text-[#0ab39c] bg-[#0ab39c]/10',
  LOST: 'text-rose-600 bg-rose-500/10',
};

const EMPTY = { name: '', code: '', sort_order: 0, outcome: 'IN_PROGRESS' as const, is_active: true };

export default function PipelineStagesPage() {
  const router = useRouter();
  const { user: me } = useAuth();
  const [loading, setLoading] = useState(true);
  const [stages, setStages] = useState<Stage[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [editId, setEditId] = useState<number | null>(null);
  const [form, setForm] = useState<Omit<Stage, 'id'>>(EMPTY);
  const [saving, setSaving] = useState(false);

  const load = useCallback(async () => {
    const res = (await api.get('/pipeline/admin/stages/?page_size=200')) as any;
    const rows: Stage[] = res?.data?.results ?? res?.results ?? res?.data ?? res ?? [];
    setStages(Array.isArray(rows) ? rows : []);
  }, []);

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

  const openAdd = () => {
    setEditId(null);
    setForm({ ...EMPTY, sort_order: (stages.at(-1)?.sort_order ?? 0) + 1 });
    setShowModal(true);
  };
  const openEdit = (s: Stage) => { setEditId(s.id); const { id, ...rest } = s; setForm(rest); setShowModal(true); };

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

  const save = async () => {
    if (!form.name.trim()) { toast.error('Name is required'); return; }
    const payload = { ...form, code: form.code.trim() || slugify(form.name) };
    setSaving(true);
    try {
      if (editId) await api.put(`/pipeline/admin/stages/${editId}/`, payload);
      else await api.post('/pipeline/admin/stages/', payload);
      toast.success(editId ? 'Stage updated' : 'Stage created');
      setShowModal(false);
      await load();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Could not save stage');
    } finally { setSaving(false); }
  };

  const remove = async (s: Stage) => {
    const r = await showConfirmDelete(`Delete stage "${s.name}"?`);
    if (!r.isConfirmed) return;
    try { await api.delete(`/pipeline/admin/stages/${s.id}/`); toast.success('Stage deleted'); await load(); }
    catch (err) { toast.error(err instanceof Error ? err.message : 'Could not delete'); }
  };

  if (loading) return <PageLoader />;
  if (me?.role !== 'ADMIN') {
    return (
      <div className="flex-1 flex flex-col items-center justify-center gap-4">
        <p className="text-slate-500">Only an administrator can manage pipeline stages.</p>
        <button onClick={() => router.push('/dashboard')} className="bg-[#405189] hover:bg-[#364574] text-white text-sm font-semibold py-2.5 px-5 rounded-none">Go to Dashboard</button>
      </div>
    );
  }

  const inputCls = 'mt-1 w-full border border-vz-border dark:border-slate-700 dark:bg-slate-800 rounded-none px-3 py-2 text-sm focus:ring-2 focus:ring-[#405189]/25 focus:border-[#405189] focus:outline-none';

  return (
    <>
        <main className="flex-1 p-6 overflow-x-auto">
          <BackToDashboard />
          <div className="flex items-center justify-between mb-5">
            <div>
              <h1 className="text-xl font-semibold text-[#495057] dark:text-slate-100">Master Pipeline Stages</h1>
              <p className="text-sm text-vz-muted">Manage recruitment stages used across all JD pipelines.</p>
            </div>
            <button onClick={openAdd} className="bg-[#405189] hover:bg-[#364574] text-white text-sm font-medium py-2.5 px-4 rounded-none flex items-center gap-2">
              <i className="fa-solid fa-plus"></i> Add stage
            </button>
          </div>

          <div className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 rounded-none overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-slate-50 dark:bg-slate-900/60 text-slate-500 text-left">
                <tr>
                  <th className="px-4 py-2.5 font-semibold w-16">Order</th>
                  <th className="px-4 py-2.5 font-semibold">Stage</th>
                  <th className="px-4 py-2.5 font-semibold">Code</th>
                  <th className="px-4 py-2.5 font-semibold">Outcome</th>
                  <th className="px-4 py-2.5 font-semibold">Active</th>
                  <th className="px-4 py-2.5 font-semibold text-right">Actions</th>
                </tr>
              </thead>
              <tbody>
                {stages.map((s) => (
                  <tr key={s.id} className="border-t border-slate-100 dark:border-slate-800">
                    <td className="px-4 py-2.5 text-slate-500">{s.sort_order}</td>
                    <td className="px-4 py-2.5 font-medium text-slate-800 dark:text-slate-200">{s.name}</td>
                    <td className="px-4 py-2.5"><code className="text-xs bg-slate-100 dark:bg-slate-800 px-1.5 py-0.5 rounded-none">{s.code}</code></td>
                    <td className="px-4 py-2.5"><span className={`text-[11px] font-semibold px-2 py-0.5 rounded-none ${OUTCOME_BADGE[s.outcome]}`}>{OUTCOMES.find((o) => o.value === s.outcome)?.label}</span></td>
                    <td className="px-4 py-2.5">{s.is_active ? <span className="text-emerald-600 text-xs font-semibold">Active</span> : <span className="text-slate-400 text-xs">Hidden</span>}</td>
                    <td className="px-4 py-2.5 text-right whitespace-nowrap">
                      <button onClick={() => openEdit(s)} className="w-8 h-8 rounded-none text-slate-400 hover:text-[#405189] hover:bg-slate-100 dark:hover:bg-slate-800" title="Edit"><i className="fa-solid fa-pen text-[13px]"></i></button>
                      <button onClick={() => remove(s)} className="w-8 h-8 rounded-none text-slate-400 hover:text-rose-600 hover:bg-rose-50 dark:hover:bg-rose-950/30" title="Delete"><i className="fa-solid fa-trash-can text-[13px]"></i></button>
                    </td>
                  </tr>
                ))}
                {stages.length === 0 && <tr><td colSpan={6} className="px-4 py-8 text-center text-slate-400">No stages.</td></tr>}
              </tbody>
            </table>
          </div>
        </main>

      {showModal && (
        <div className="fixed inset-0 z-[100] bg-slate-950/50 flex items-center justify-center p-4" onClick={() => !saving && setShowModal(false)}>
          <div className="bg-white dark:bg-slate-900 rounded-none w-full max-w-md p-6 space-y-4" onClick={(e) => e.stopPropagation()}>
            <h2 className="text-lg font-semibold text-[#495057] dark:text-slate-100">{editId ? 'Edit stage' : 'Add stage'}</h2>
            <label className="block">
              <span className="text-xs font-medium text-slate-500">Name</span>
              <input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} className={inputCls} />
            </label>
            <div className="grid grid-cols-2 gap-3">
              <label className="block">
                <span className="text-xs font-medium text-slate-500">Code (auto if blank)</span>
                <input value={form.code} placeholder="e.g. contacted" onChange={(e) => setForm({ ...form, code: e.target.value })} className={inputCls} />
              </label>
              <label className="block">
                <span className="text-xs font-medium text-slate-500">Sort order</span>
                <input type="number" value={form.sort_order} onChange={(e) => setForm({ ...form, sort_order: Number(e.target.value) })} className={inputCls} />
              </label>
            </div>
            <label className="block">
              <span className="text-xs font-medium text-slate-500">Outcome</span>
              <select value={form.outcome} onChange={(e) => setForm({ ...form, outcome: e.target.value as any })} className={inputCls}>
                {OUTCOMES.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
              </select>
            </label>
            <label className="flex items-center gap-2">
              <input type="checkbox" checked={form.is_active} onChange={(e) => setForm({ ...form, is_active: e.target.checked })} className="accent-[#405189]" />
              <span className="text-sm text-slate-600 dark:text-slate-300">Active</span>
            </label>
            <div className="flex justify-end gap-2 pt-2">
              <button onClick={() => setShowModal(false)} disabled={saving} className="px-4 py-2 rounded-none text-sm border border-vz-border text-slate-600 dark:text-slate-300">Cancel</button>
              <button onClick={save} disabled={saving} className="px-4 py-2 rounded-none text-sm font-medium bg-[#405189] hover:bg-[#364574] text-white disabled:opacity-50">{saving ? 'Saving…' : 'Save'}</button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
