'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Plus, Search, MoreHorizontal, UserCheck, UserX } from 'lucide-react';
import { api } from '@/lib/api';
import { EmployeeDialog } from '@/components/staff/employee-dialog';
import { DeleteEmployeeDialog } from '@/components/staff/delete-employee-dialog';

type Employee = {
  id: string;
  number: number | null;
  name: string;
  role: string;
  department: string;
  phone: string;
  status: 'active' | 'inactive';
  hiredAt: string;
};

type UsersResponse = {
  data: Employee[];
  hasMore: boolean;
  nextCursor: string | null;
};

const roleColors: Record<string, string> = {
  Тренер: 'bg-blue-100 text-blue-800',
  Координатор: 'bg-purple-100 text-purple-800',
  'Фитнес-менеджер': 'bg-orange-100 text-orange-800',
  Администратор: 'bg-green-100 text-green-800',
};

export default function StaffPage(): React.JSX.Element {
  const router = useRouter();
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState('');

  // Dialog state
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [editEmployee, setEditEmployee] = useState<Employee | null>(null);
  const [deleteEmployee, setDeleteEmployee] = useState<Employee | null>(null);

  // Dropdown state
  const [openMenuId, setOpenMenuId] = useState<string | null>(null);
  const menuRef = useRef<HTMLDivElement>(null);

  const loadEmployees = useCallback(() => {
    setLoading(true);
    api
      .get<UsersResponse>('/users')
      .then((res) => {
        setEmployees(res.data ?? []);
        setError(null);
      })
      .catch((err) => {
        setEmployees([]);
        setError(err instanceof Error ? err.message : 'Не удалось загрузить сотрудников');
      })
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    loadEmployees();
  }, [loadEmployees]);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
        setOpenMenuId(null);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <p className="text-error text-sm mb-2">{error}</p>
          <button onClick={loadEmployees} className="text-sm text-primary hover:underline">
            Попробовать снова
          </button>
        </div>
      </div>
    );
  }

  const filtered = employees.filter(
    (e) =>
      e.name.toLowerCase().includes(search.toLowerCase()) ||
      e.role.toLowerCase().includes(search.toLowerCase()) ||
      e.department.toLowerCase().includes(search.toLowerCase()),
  );

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Сотрудники</h1>
        <button
          onClick={() => setShowAddDialog(true)}
          className="flex items-center gap-2 bg-primary text-white px-4 py-2.5 rounded-xl text-sm font-medium hover:bg-primary/90 transition-colors"
        >
          <Plus className="h-4 w-4" />
          Добавить сотрудника
        </button>
      </div>

      <div className="bg-card rounded-xl shadow-sm border border-border">
        <div className="p-4 border-b border-border">
          <div className="relative max-w-md">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted" />
            <input
              type="text"
              placeholder="Поиск по имени, роли, департаменту..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
            />
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-border">
                <th className="text-left px-6 py-3 text-xs font-semibold text-muted uppercase tracking-wider w-16">
                  #
                </th>
                <th className="text-left px-6 py-3 text-xs font-semibold text-muted uppercase tracking-wider">
                  Имя
                </th>
                <th className="text-left px-6 py-3 text-xs font-semibold text-muted uppercase tracking-wider">
                  Роль
                </th>
                <th className="text-left px-6 py-3 text-xs font-semibold text-muted uppercase tracking-wider">
                  Департамент
                </th>
                <th className="text-left px-6 py-3 text-xs font-semibold text-muted uppercase tracking-wider">
                  Телефон
                </th>
                <th className="text-left px-6 py-3 text-xs font-semibold text-muted uppercase tracking-wider">
                  Статус
                </th>
                <th className="text-left px-6 py-3 text-xs font-semibold text-muted uppercase tracking-wider">
                  Дата найма
                </th>
                <th className="px-6 py-3"></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((employee) => (
                <tr
                  key={employee.id}
                  onClick={() =>
                    employee.number != null && router.push(`/staff/${employee.number}`)
                  }
                  className="border-b border-border last:border-0 hover:bg-gray-50 transition-colors cursor-pointer"
                >
                  <td className="px-6 py-4">
                    <span className="text-sm font-mono text-muted">{employee.number ?? '—'}</span>
                  </td>
                  <td className="px-6 py-4">
                    <span className="text-sm font-medium text-gray-900">{employee.name}</span>
                  </td>
                  <td className="px-6 py-4">
                    <span
                      className={`inline-flex px-2.5 py-0.5 rounded-full text-xs font-medium ${roleColors[employee.role] ?? 'bg-gray-100 text-gray-800'}`}
                    >
                      {employee.role}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-600">{employee.department}</td>
                  <td className="px-6 py-4 text-sm text-gray-600 font-mono">{employee.phone}</td>
                  <td className="px-6 py-4">
                    {employee.status === 'active' ? (
                      <span className="inline-flex items-center gap-1 text-xs font-medium text-success">
                        <UserCheck className="h-3.5 w-3.5" /> Активен
                      </span>
                    ) : (
                      <span className="inline-flex items-center gap-1 text-xs font-medium text-error">
                        <UserX className="h-3.5 w-3.5" /> Неактивен
                      </span>
                    )}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-600">{employee.hiredAt}</td>
                  <td className="px-6 py-4 text-right">
                    <div
                      className="relative inline-block"
                      ref={openMenuId === employee.id ? menuRef : undefined}
                    >
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          setOpenMenuId(openMenuId === employee.id ? null : employee.id);
                        }}
                        className="p-1 rounded hover:bg-gray-100"
                      >
                        <MoreHorizontal className="h-4 w-4 text-muted" />
                      </button>
                      {openMenuId === employee.id && (
                        <div className="absolute right-0 top-full mt-1 w-44 bg-white border border-border rounded-xl shadow-lg z-20">
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              setOpenMenuId(null);
                              setEditEmployee(employee);
                            }}
                            className="w-full text-left px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 rounded-t-xl transition-colors"
                          >
                            Редактировать
                          </button>
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              setOpenMenuId(null);
                              setDeleteEmployee(employee);
                            }}
                            className="w-full text-left px-4 py-2.5 text-sm text-error hover:bg-red-50 rounded-b-xl transition-colors"
                          >
                            Удалить
                          </button>
                        </div>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="px-6 py-3 border-t border-border text-sm text-muted">
          Показано {filtered.length} из {employees.length} сотрудников
        </div>
      </div>

      {/* Add / Edit Employee Dialog */}
      <EmployeeDialog
        open={showAddDialog || !!editEmployee}
        onClose={() => {
          setShowAddDialog(false);
          setEditEmployee(null);
        }}
        onSaved={loadEmployees}
        employee={editEmployee}
      />

      {/* Delete Employee Dialog */}
      <DeleteEmployeeDialog
        open={!!deleteEmployee}
        onClose={() => setDeleteEmployee(null)}
        onDeleted={loadEmployees}
        employee={deleteEmployee}
      />
    </div>
  );
}
