'use client';

import { useCallback, useEffect, useState } from 'react';
import { Plus, Users, UserCheck, Edit, Trash2 } from 'lucide-react';
import { api } from '@/lib/api';
import { DepartmentDialog } from '@/components/departments/department-dialog';
import { DeleteDepartmentDialog } from '@/components/departments/delete-department-dialog';

type Department = {
  id: string;
  name: string;
  head: string;
  trainersCount: number;
  activeClients: number;
  description: string;
};

type DepartmentsResponse = {
  data: Department[];
  hasMore: boolean;
  nextCursor: string | null;
};

export default function DepartmentsPage(): React.JSX.Element {
  const [departments, setDepartments] = useState<Department[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Dialog state
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [editDepartment, setEditDepartment] = useState<Department | null>(null);
  const [deleteDepartment, setDeleteDepartment] = useState<Department | null>(null);

  const loadDepartments = useCallback(() => {
    setLoading(true);
    api.get<DepartmentsResponse>('/departments')
      .then((res) => {
        setDepartments(res.data ?? []);
        setError(null);
      })
      .catch((err) => {
        setDepartments([]);
        setError(err instanceof Error ? err.message : 'Не удалось загрузить департаменты');
      })
      .finally(() => setLoading(false));
  }, []);

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

  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={loadDepartments}
            className="text-sm text-primary hover:underline"
          >
            Попробовать снова
          </button>
        </div>
      </div>
    );
  }

  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>

      {departments.length === 0 && (
        <div className="text-center py-12 text-muted text-sm">
          Нет департаментов
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {departments.map((dept) => (
          <div
            key={dept.id}
            className="bg-card rounded-xl p-6 shadow-sm border border-border"
          >
            <div className="flex items-start justify-between mb-4">
              <h2 className="text-lg font-semibold text-gray-900">{dept.name}</h2>
              <div className="flex gap-1">
                <button
                  onClick={() => setEditDepartment(dept)}
                  className="p-1.5 rounded-lg hover:bg-gray-100 transition-colors"
                >
                  <Edit className="h-4 w-4 text-muted" />
                </button>
                <button
                  onClick={() => setDeleteDepartment(dept)}
                  className="p-1.5 rounded-lg hover:bg-red-50 transition-colors"
                >
                  <Trash2 className="h-4 w-4 text-error" />
                </button>
              </div>
            </div>

            <p className="text-sm text-gray-600 mb-4">{dept.description}</p>

            <div className="flex items-center gap-6">
              <div className="flex items-center gap-2">
                <UserCheck className="h-4 w-4 text-primary" />
                <span className="text-sm text-gray-600">
                  Руководитель: <span className="font-medium text-gray-900">{dept.head}</span>
                </span>
              </div>
            </div>

            <div className="flex gap-4 mt-4 pt-4 border-t border-border">
              <div className="flex items-center gap-1.5">
                <Users className="h-4 w-4 text-muted" />
                <span className="text-sm text-muted">
                  {dept.trainersCount} тренеров
                </span>
              </div>
              <div className="flex items-center gap-1.5">
                <Users className="h-4 w-4 text-muted" />
                <span className="text-sm text-muted">
                  {dept.activeClients} клиентов
                </span>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Add / Edit Department Dialog */}
      <DepartmentDialog
        open={showAddDialog || !!editDepartment}
        onClose={() => {
          setShowAddDialog(false);
          setEditDepartment(null);
        }}
        onSaved={loadDepartments}
        department={editDepartment}
      />

      {/* Delete Department Dialog */}
      <DeleteDepartmentDialog
        open={!!deleteDepartment}
        onClose={() => setDeleteDepartment(null)}
        onDeleted={loadDepartments}
        department={deleteDepartment}
      />
    </div>
  );
}
