import { useState, useCallback, useRef, useEffect } from 'react';
import { Models } from 'appwrite';
import { usuarioService, UsuarioData } from '@/services/usuarioService';

export interface UsuarioFormData extends UsuarioData {}

export interface UseUsuariosReturn {
  usuarios: Models.Document[];
  loading: boolean;
  isChangingPage: boolean;
  isCreating: boolean;
  error: string | null;
  totalUsuarios: number;
  currentPage: number;
  listarUsuarios: (page?: number, search?: string) => Promise<void>;
  buscarUsuarios: (nome: string, page?: number) => Promise<void>;
  cadastrarUsuario: (data: UsuarioFormData) => Promise<boolean>;
  atualizarUsuario: (id: string, data: UsuarioFormData) => Promise<boolean>;
  deletarUsuario: (id: string) => Promise<boolean>;
  setCurrentPage: (page: number) => void;
  searchTerm: string;
  setSearchTerm: (term: string) => void;
}

const PAGE_SIZE = 10;

export const useUsuarios = (): UseUsuariosReturn => {
  const [usuarios, setUsuarios] = useState<Models.Document[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [totalUsuarios, setTotalUsuarios] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [isChangingPage, setIsChangingPage] = useState(false);
  const [isCreating, setIsCreating] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const isInitialMount = useRef(true);

  const listarUsuarios = useCallback(
    async (page = currentPage, search = searchTerm) => {
    setIsChangingPage(true);
    setLoading(true);
    setError(null);

    try {
      const response = search.trim()
        ? await usuarioService.buscarPorNome(search, page, PAGE_SIZE)
        : await usuarioService.listar(page, PAGE_SIZE);

      if (response.success) {
        setUsuarios(response.documents || []);
        setTotalUsuarios(response.total || 0);
        setCurrentPage(page);
        setSearchTerm(search);
      } else {
        setError(response.error || 'Erro ao carregar usuários');
      }
    } catch (err) {
      setError('Erro de conexão ao carregar usuários');
    } finally {
      setLoading(false);
      setIsChangingPage(false);
    }
  }, [currentPage, searchTerm]);

  const buscarUsuarios = useCallback(async (nome: string, page = 1) => {
    setIsChangingPage(true);
    setLoading(true);
    setError(null);

    try {
      const response = await usuarioService.buscarPorNome(nome, page, PAGE_SIZE);

      if (response.success) {
        setUsuarios(response.documents || []);
        setTotalUsuarios(response.total || 0);
        setCurrentPage(page);
        setSearchTerm(nome);
      } else {
        setError(response.error || 'Erro ao buscar usuários');
      }
    } catch (err) {
      setError('Erro de conexão ao buscar usuários');
    } finally {
      setLoading(false);
      setIsChangingPage(false);
    }
  }, []);

  const cadastrarUsuario = useCallback(async (formData: UsuarioFormData): Promise<boolean> => {
    setIsCreating(true);
    setError(null);

    try {
      const response = await usuarioService.criar(formData);

      if (response.success) {
        await listarUsuarios(1, searchTerm);
        return true;
      } else {
        setError(response.error || 'Erro ao cadastrar usuário');
        return false;
      }
    } catch (err) {
      setError('Erro de conexão ao cadastrar usuário');
      return false;
    } finally {
      setIsCreating(false);
    }
  }, [listarUsuarios, searchTerm]);

  const atualizarUsuario = useCallback(async (id: string, formData: UsuarioFormData): Promise<boolean> => {
    setLoading(true);
    setError(null);

    try {
      const response = await usuarioService.atualizar(id, formData);

      if (response.success) {
        await listarUsuarios(currentPage, searchTerm);
        return true;
      } else {
        setError(response.error || 'Erro ao atualizar usuário');
        return false;
      }
    } catch (err) {
      setError('Erro de conexão ao atualizar usuário');
      return false;
    } finally {
      setLoading(false);
    }
  }, [currentPage, listarUsuarios]);

  const deletarUsuario = useCallback(async (id: string): Promise<boolean> => {
    setLoading(true);
    setError(null);

    try {
      const response = await usuarioService.deletar(id);

      if (response.success) {
        await listarUsuarios(currentPage, searchTerm);
        return true;
      } else {
        setError(response.error || 'Erro ao deletar usuário');
        return false;
      }
    } catch (err) {
      setError('Erro de conexão ao deletar usuário');
      return false;
    } finally {
      setLoading(false);
    }
  }, [currentPage, listarUsuarios]);

  useEffect(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false;
      return;
    }

    if (searchTerm.trim()) {
      buscarUsuarios(searchTerm, currentPage);
    } else {
      listarUsuarios(currentPage);
    }
  }, [currentPage, searchTerm, listarUsuarios, buscarUsuarios]);

  return {
    usuarios,
    loading,
    isChangingPage,
    isCreating,
    error,
    totalUsuarios,
    currentPage,
    listarUsuarios,
    buscarUsuarios,
    cadastrarUsuario,
    atualizarUsuario,
    deletarUsuario,
    setCurrentPage,
    searchTerm,
    setSearchTerm
  };
};
