'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { useToast } from '@/lib/toast';
import { TableSkeleton } from '@/components/Skeletons';
import Modal from '@/components/Modal';

type Task = { id: number; title: string; description: string | null; status: string; priority: string; dueDate: string | null; assignedTo: { id: number; name: string } };
type EmployeeRow = {
  id: number; employeeNo: string; name: string; phone: string; roleTitle: string;
  isActive: boolean; attendanceToday: string | null; performanceTag: string | null; tasks: Task[];
};

const ATTENDANCE_OPTIONS = ['Present', 'Absent', 'Leave', 'Site Visit'];
const TASK_STATUSES = ['PENDING', 'IN_PROGRESS', 'COMPLETED'];
const TASK_STATUS_LABEL: Record<string, string> = { PENDING: 'Pending', IN_PROGRESS: 'In Progress', COMPLETED: 'Completed' };
const PRIORITY_COLOR: Record<string, string> = {
  LOW: 'bg-gray-100 text-gray-600', MEDIUM: 'bg-blue-100 text-blue-700',
  HIGH: 'bg-yellow-100 text-yellow-700', URGENT: 'bg-red-100 text-red-700',
};

export default function EmployeesPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [employees, setEmployees] = useState<EmployeeRow[]>([]);
  const [tasks, setTasks] = useState<Task[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState({ name: '', phone: '', roleTitle: '' });

  const [showTaskForm, setShowTaskForm] = useState(false);
  const [taskForm, setTaskForm] = useState({ title: '', description: '', assignedToId: '', priority: 'MEDIUM', dueDate: '' });
  const [savingTask, setSavingTask] = useState(false);

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const [e, t] = await Promise.all([
        adminApiFetch('/admin/employees', accessToken, appSecretProof),
        adminApiFetch('/admin/employees/tasks', accessToken, appSecretProof),
      ]);
      setEmployees(e.employees || []);
      setTasks(t.tasks || []);
    } catch { setError('You do not have permission to view this page.'); }
    finally { setLoading(false); }
  }
  useEffect(() => { load(); }, [accessToken, appSecretProof]); // eslint-disable-line react-hooks/exhaustive-deps

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof) return;
    setSaving(true);
    try {
      await adminApiFetch('/admin/employees', accessToken, appSecretProof, { method: 'POST', body: JSON.stringify(form) });
      show('success', `${form.name} added.`);
      setForm({ name: '', phone: '', roleTitle: '' });
      setShowForm(false);
      load();
    } catch { show('error', 'Could not save that employee.'); }
    finally { setSaving(false); }
  }

  async function setAttendance(id: number, name: string, attendanceToday: string) {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/employees/${id}/attendance`, accessToken, appSecretProof, { method: 'PATCH', body: JSON.stringify({ attendanceToday }) });
      setEmployees((e) => e.map((row) => row.id === id ? { ...row, attendanceToday } : row));
      show('success', `${name} marked ${attendanceToday}.`);
    } catch { show('error', 'Could not update attendance.'); }
  }

  async function submitTask(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !taskForm.assignedToId) return;
    setSavingTask(true);
    try {
      await adminApiFetch('/admin/employees/tasks', accessToken, appSecretProof, {
        method: 'POST',
        body: JSON.stringify({ ...taskForm, assignedToId: Number(taskForm.assignedToId), dueDate: taskForm.dueDate || undefined }),
      });
      show('success', `Task "${taskForm.title}" assigned.`);
      setTaskForm({ title: '', description: '', assignedToId: '', priority: 'MEDIUM', dueDate: '' });
      setShowTaskForm(false);
      load();
    } catch { show('error', 'Could not create that task.'); }
    finally { setSavingTask(false); }
  }

  async function moveTask(id: number, status: string) {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/employees/tasks/${id}/status`, accessToken, appSecretProof, { method: 'PATCH', body: JSON.stringify({ status }) });
      setTasks((t) => t.map((row) => row.id === id ? { ...row, status } : row));
      show('success', `Task moved to ${TASK_STATUS_LABEL[status]}.`);
    } catch { show('error', 'Could not move that task.'); }
  }

  if (error) return <p className="text-sm text-brand-red">{error}</p>;

  return (
    <div className="space-y-6">
      <div className="flex justify-between">
        <h1 className="text-xl font-bold">HR &bull; Employees &bull; admin.lussavara.co.tz</h1>
        <button onClick={() => setShowForm((s) => !s)} className="bg-brand-charcoal text-white px-4 py-2 rounded-full text-sm transition-transform hover:scale-[1.03]">{showForm ? 'Close' : '+ Add Employee'}</button>
      </div>

      {showForm && (
        <form onSubmit={submit} className="bg-white border border-brand-border rounded-xl p-4 grid grid-cols-2 md:grid-cols-3 gap-2 animate-scaleIn">
          <input required placeholder="Name" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
          <input required placeholder="Phone +255…" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
          <input required placeholder="Role title" value={form.roleTitle} onChange={(e) => setForm({ ...form, roleTitle: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
          <button disabled={saving} className="col-span-2 md:col-span-3 bg-brand-charcoal text-white text-xs py-2 rounded-lg disabled:opacity-60">{saving ? 'Saving…' : 'Save Employee'}</button>
        </form>
      )}

      {loading ? <TableSkeleton rows={5} cols={4} /> : (
        <div className="bg-white rounded-xl border border-brand-border overflow-hidden">
          <table className="w-full text-xs">
            <thead className="bg-brand-bg"><tr>
              <th className="p-3 text-left">Employee No &bull; Name &bull; Role</th><th className="p-3 text-left">Attendance Today</th>
              <th className="p-3 text-left">Open Tasks</th><th className="p-3 text-left">Performance</th>
            </tr></thead>
            <tbody>
              {employees.map((e) => (
                <tr key={e.id} className="border-t border-brand-border transition-colors hover:bg-brand-bg">
                  <td className="p-3">{e.employeeNo} &bull; {e.name} &bull; {e.phone}<br /><span className="text-gray-400">{e.roleTitle}</span></td>
                  <td className="p-3">
                    <select value={e.attendanceToday || ''} onChange={(ev) => setAttendance(e.id, e.name, ev.target.value)} className="text-[10px] rounded-full px-2 py-1 bg-green-100 text-green-700 border-0">
                      <option value="">—</option>
                      {ATTENDANCE_OPTIONS.map((a) => <option key={a} value={a}>{a}</option>)}
                    </select>
                  </td>
                  <td className="p-3">{e.tasks.length === 0 ? '—' : e.tasks.map((t) => t.title).join(', ')}</td>
                  <td className="p-3">{e.performanceTag || '—'}</td>
                </tr>
              ))}
              {employees.length === 0 && <tr><td colSpan={4} className="p-6 text-center text-gray-400">No employees yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      <div>
        <div className="flex justify-between items-center mb-3">
          <h2 className="text-sm font-bold">Task Board</h2>
          <button onClick={() => setShowTaskForm(true)} className="border px-3 py-1.5 rounded-full text-xs transition-colors hover:bg-brand-bg">+ Add Task</button>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          {TASK_STATUSES.map((status) => (
            <div key={status} className="bg-brand-bg rounded-xl p-3 min-h-[120px]">
              <p className="text-xs font-semibold text-gray-500 mb-2">{TASK_STATUS_LABEL[status]} &bull; {tasks.filter((t) => t.status === status).length}</p>
              <div className="space-y-2">
                {tasks.filter((t) => t.status === status).map((t) => (
                  <div key={t.id} className="bg-white border border-brand-border rounded-lg p-2.5 text-xs transition-all hover:shadow-sm animate-fadeInUp">
                    <div className="flex justify-between items-start gap-2">
                      <p className="font-semibold">{t.title}</p>
                      <span className={`text-[9px] px-1.5 py-0.5 rounded-full shrink-0 ${PRIORITY_COLOR[t.priority]}`}>{t.priority}</span>
                    </div>
                    <p className="text-gray-400 mt-0.5">{t.assignedTo.name}{t.dueDate && ` • due ${new Date(t.dueDate).toLocaleDateString()}`}</p>
                    <select value={t.status} onChange={(e) => moveTask(t.id, e.target.value)} className="mt-2 w-full text-[10px] border border-brand-border rounded px-1.5 py-1">
                      {TASK_STATUSES.map((s) => <option key={s} value={s}>{TASK_STATUS_LABEL[s]}</option>)}
                    </select>
                  </div>
                ))}
                {tasks.filter((t) => t.status === status).length === 0 && <p className="text-[11px] text-gray-400">Nothing here.</p>}
              </div>
            </div>
          ))}
        </div>
      </div>

      {showTaskForm && (
        <Modal title="Add Task" onClose={() => setShowTaskForm(false)}>
          <form onSubmit={submitTask} className="space-y-3">
            <input required autoFocus placeholder="Task title" value={taskForm.title} onChange={(e) => setTaskForm({ ...taskForm, title: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <textarea placeholder="Description (optional)" value={taskForm.description} onChange={(e) => setTaskForm({ ...taskForm, description: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" rows={2} />
            <select required value={taskForm.assignedToId} onChange={(e) => setTaskForm({ ...taskForm, assignedToId: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm">
              <option value="">Assign to…</option>
              {employees.map((e) => <option key={e.id} value={e.id}>{e.name}</option>)}
            </select>
            <div className="grid grid-cols-2 gap-2">
              <select value={taskForm.priority} onChange={(e) => setTaskForm({ ...taskForm, priority: e.target.value })}
                className="border border-brand-border rounded-lg px-3 py-2 text-sm">
                {['LOW', 'MEDIUM', 'HIGH', 'URGENT'].map((p) => <option key={p} value={p}>{p}</option>)}
              </select>
              <input type="date" value={taskForm.dueDate} onChange={(e) => setTaskForm({ ...taskForm, dueDate: e.target.value })}
                className="border border-brand-border rounded-lg px-3 py-2 text-sm" />
            </div>
            <button disabled={savingTask} className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-60">
              {savingTask ? 'Assigning…' : 'Assign Task'}
            </button>
          </form>
        </Modal>
      )}
    </div>
  );
}
