// =============================================================================
// 🧑‍💼 EMPLOYEE CRUD HOOK V2
// =============================================================================
// Хук для CRUD операций с сотрудниками

'use client'

import { useMutation } from '@apollo/client'
import { useCallback, useState } from 'react'
import { toast } from 'sonner'

import { 
  CREATE_EMPLOYEE_V2,
  UPDATE_EMPLOYEE_V2,
  DELETE_EMPLOYEE_V2,
} from '@/graphql/queries/employees-v2'
import { GET_EMPLOYEES_V2 } from '@/graphql/queries/employees-v2'

import type { 
  CreateEmployeeInput, 
  UpdateEmployeeInput, 
  UseEmployeeCRUDReturn,
  EmployeeMutationResponse,
} from '../types'

export function useEmployeeCRUD(): UseEmployeeCRUDReturn {
  const [loading, setLoading] = useState(false)

  // GraphQL мутации
  const [createEmployeeMutation] = useMutation(CREATE_EMPLOYEE_V2, {
    refetchQueries: [{ query: GET_EMPLOYEES_V2 }],
    onCompleted: () => {
      toast.success('Сотрудник успешно создан!')
    },
    onError: (error) => {
      console.error('Error creating employee:', error)
      toast.error('Ошибка при создании сотрудника')
    },
  })

  const [updateEmployeeMutation] = useMutation(UPDATE_EMPLOYEE_V2, {
    refetchQueries: [{ query: GET_EMPLOYEES_V2 }],
    onCompleted: () => {
      toast.success('Сотрудник успешно обновлен!')
    },
    onError: (error) => {
      console.error('Error updating employee:', error)
      toast.error('Ошибка при обновлении сотрудника')
    },
  })

  const [deleteEmployeeMutation] = useMutation(DELETE_EMPLOYEE_V2, {
    refetchQueries: [{ query: GET_EMPLOYEES_V2 }],
    onCompleted: () => {
      toast.success('Сотрудник успешно удален!')
    },
    onError: (error) => {
      console.error('Error deleting employee:', error)
      toast.error('Ошибка при удалении сотрудника')
    },
  })

  // =============================================================================
  // CRUD ОПЕРАЦИИ
  // =============================================================================

  const createEmployee = useCallback(async (data: CreateEmployeeInput): Promise<EmployeeMutationResponse> => {
    setLoading(true)
    try {
      const result = await createEmployeeMutation({
        variables: { input: data },
      })

      const response = result.data?.createEmployeeV2

      if (response?.errors?.length) {
        // Показываем ошибки валидации
        response.errors.forEach(error => {
          toast.error(`${error.field}: ${error.message}`)
        })
      }

      return {
        success: response?.success || false,
        message: response?.message,
        employee: response?.employee,
        errors: response?.errors,
      }
    } catch (error: any) {
      console.error('Create employee error:', error)
      return {
        success: false,
        message: 'Неизвестная ошибка при создании сотрудника',
        errors: [{ field: 'general', message: error.message }],
      }
    } finally {
      setLoading(false)
    }
  }, [createEmployeeMutation])

  const updateEmployee = useCallback(async (
    id: string, 
    data: UpdateEmployeeInput,
  ): Promise<EmployeeMutationResponse> => {
    setLoading(true)
    try {
      const result = await updateEmployeeMutation({
        variables: { id, input: data },
      })

      const response = result.data?.updateEmployeeV2

      if (response?.errors?.length) {
        response.errors.forEach(error => {
          toast.error(`${error.field}: ${error.message}`)
        })
      }

      return {
        success: response?.success || false,
        message: response?.message,
        employee: response?.employee,
        errors: response?.errors,
      }
    } catch (error: any) {
      console.error('Update employee error:', error)
      return {
        success: false,
        message: 'Неизвестная ошибка при обновлении сотрудника',
        errors: [{ field: 'general', message: error.message }],
      }
    } finally {
      setLoading(false)
    }
  }, [updateEmployeeMutation])

  const deleteEmployee = useCallback(async (id: string): Promise<boolean> => {
    setLoading(true)
    try {
      const result = await deleteEmployeeMutation({
        variables: { id },
      })

      return result.data?.deleteEmployeeV2 || false
    } catch (error: any) {
      console.error('Delete employee error:', error)
      return false
    } finally {
      setLoading(false)
    }
  }, [deleteEmployeeMutation])

  return {
    createEmployee,
    updateEmployee,
    deleteEmployee,
    loading,
  }
}