// =============================================================================
// 🧑‍💼 EMPLOYEE MANAGEMENT V2
// =============================================================================
// Главный модульный компонент управления сотрудниками V2
// Следует паттерну MODULAR_ARCHITECTURE_PATTERN.md

'use client'

import { FileText, Plus, Users } from 'lucide-react'
import { useCallback, useState } from 'react'

import { Sidebar } from '@/components/dashboard/sidebar'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'

import { EmployeeFiltersBlock } from './blocks/EmployeeFiltersBlock'
import { EmployeeListBlock } from './blocks/EmployeeListBlock'
import { EmployeeStatsBlock } from './blocks/EmployeeStatsBlock'
import { EmployeeForm } from './forms/EmployeeForm'
import { useEmployeeCRUD, useEmployeeData, useEmployeeFilters } from './hooks'
import type { CreateEmployeeInput, EmployeeV2, UpdateEmployeeInput } from './types'

// =============================================================================
// ГЛАВНЫЙ КОМПОНЕНТ
// =============================================================================

export const EmployeeManagement = () => {
  // Локальное состояние UI
  const [activeTab, setActiveTab] = useState<'employees' | 'reports'>('employees')
  const [showCreateForm, setShowCreateForm] = useState(false)
  const [editingEmployee, setEditingEmployee] = useState<EmployeeV2 | null>(null)

  // Хуки для бизнес-логики
  const filters = useEmployeeFilters()
  const employeeData = useEmployeeData(filters.filters)
  const employeeCRUD = useEmployeeCRUD()

  // =============================================================================
  // ОБРАБОТЧИКИ ДЕЙСТВИЙ
  // =============================================================================

  const handleCreateEmployee = useCallback(async (data: CreateEmployeeInput) => {
    const result = await employeeCRUD.createEmployee(data)
    if (result.success) {
      setShowCreateForm(false)
      employeeData.refetch()
    }
  }, [employeeCRUD, employeeData])

  const handleUpdateEmployee = useCallback(async (data: UpdateEmployeeInput) => {
    if (!editingEmployee) return

    const result = await employeeCRUD.updateEmployee(editingEmployee.id, data)
    if (result.success) {
      setEditingEmployee(null)
      employeeData.refetch()
    }
  }, [editingEmployee, employeeCRUD, employeeData])

  const handleDeleteEmployee = useCallback(async (id: string) => {
    const success = await employeeCRUD.deleteEmployee(id)
    if (success) {
      employeeData.refetch()
    }
  }, [employeeCRUD, employeeData])

  const handleEditEmployee = useCallback((employee: EmployeeV2) => {
    setEditingEmployee(employee)
    setShowCreateForm(false)
  }, [])

  const handleCloseForm = useCallback(() => {
    setShowCreateForm(false)
    setEditingEmployee(null)
  }, [])

  // =============================================================================
  // RENDER
  // =============================================================================

  if (employeeData.loading && !employeeData.employees.length) {
    return (
      <div className="min-h-screen flex">
        <Sidebar />
        <main className="flex-1 ml-56 p-6">
          <div className="max-w-7xl mx-auto">
            <div className="flex items-center justify-center h-64">
              <div className="text-white text-xl">Загрузка сотрудников...</div>
            </div>
          </div>
        </main>
      </div>
    )
  }

  return (
    <div className="min-h-screen flex">
      <Sidebar />
      <main className="flex-1 ml-56 p-6">
        <div className="max-w-7xl mx-auto">
          
          {/* Заголовок и управление */}
          <div className="flex items-center justify-between mb-6">
            <h1 className="text-2xl font-bold text-white">Управление сотрудниками</h1>
            
            <div className="flex items-center gap-4">
              <button
                onClick={() => setShowCreateForm(true)}
                className="bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white border-0 shadow-lg shadow-purple-500/25 transition-all duration-300 px-4 py-2 rounded-lg flex items-center gap-2"
              >
                <Plus className="h-4 w-4" />
                Добавить сотрудника
              </button>
            </div>
          </div>

          {/* Табы */}
          <Tabs value={activeTab} onValueChange={setActiveTab as any} className="w-full">
            <TabsList className="glass-card inline-flex h-10 items-center justify-center rounded-lg bg-white/5 p-1 mb-6">
              <TabsTrigger
                value="employees"
                className="text-white data-[state=active]:bg-white/20 cursor-pointer text-sm px-4 py-2 rounded-md transition-all"
              >
                <Users className="h-4 w-4 mr-2" />
                Сотрудники
              </TabsTrigger>
              <TabsTrigger
                value="reports"
                className="text-white data-[state=active]:bg-white/20 cursor-pointer text-sm px-4 py-2 rounded-md transition-all"
              >
                <FileText className="h-4 w-4 mr-2" />
                Отчеты
              </TabsTrigger>
            </TabsList>

            {/* Контент табов */}
            <TabsContent value="employees" className="space-y-6">
              
              {/* Статистика */}
              <EmployeeStatsBlock 
                stats={employeeData.stats}
                loading={employeeData.loading}
              />

              {/* Фильтры и поиск */}
              <EmployeeFiltersBlock 
                {...filters}
                loading={employeeData.loading}
              />

              {/* Список сотрудников */}
              <EmployeeListBlock
                employees={employeeData.employees}
                pagination={employeeData.pagination}
                loading={employeeData.loading}
                onEdit={handleEditEmployee}
                onDelete={handleDeleteEmployee}
                onPageChange={filters.setPage}
              />
            </TabsContent>

            <TabsContent value="reports">
              <div className="glass-card p-6">
                <h3 className="text-white font-medium text-lg mb-4">Отчеты и аналитика</h3>
                <p className="text-white/60">Модуль отчетов будет реализован в следующей итерации</p>
              </div>
            </TabsContent>
          </Tabs>

          {/* Формы создания/редактирования */}
          {(showCreateForm || editingEmployee) && (
            <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
              <div className="glass-card p-6 max-w-2xl w-full max-h-[90vh] overflow-y-auto">
                <EmployeeForm
                  employee={editingEmployee}
                  onSubmit={editingEmployee ? handleUpdateEmployee : handleCreateEmployee}
                  onCancel={handleCloseForm}
                  loading={employeeCRUD.loading}
                />
              </div>
            </div>
          )}
        </div>
      </main>
    </div>
  )
}

// =============================================================================
// DISPLAY NAME
// =============================================================================

EmployeeManagement.displayName = 'EmployeeManagement'