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

export interface CarrinhoFormData {
  usuarios: string;
  itens: string[];
  quantidade: number[];
}

export interface UseCarrinhosReturn {
  carrinhos: Models.Document[];
  loading: boolean;
  isChangingPage: boolean;
  isCreating: boolean;
  error: string | null;
  totalCarrinhos: number;
  currentPage: number;
  listarCarrinhos: (page?: number, search?: string) => Promise<void>;
  buscarCarrinhos: (usuario: string, page?: number) => Promise<void>;
  cadastrarCarrinho: (data: CarrinhoFormData) => Promise<boolean>;
  atualizarCarrinho: (id: string, data: CarrinhoFormData) => Promise<boolean>;
  deletarCarrinho: (id: string) => Promise<boolean>;
  setCurrentPage: (page: number) => void;
  searchTerm: string;
  setSearchTerm: (term: string) => void;
}

const PAGE_SIZE = 10;

export const useCarrinhos = (): UseCarrinhosReturn => {
  const [carrinhos, setCarrinhos] = useState<Models.Document[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [totalCarrinhos, setTotalCarrinhos] = 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 listarCarrinhos = useCallback(
    async (page = currentPage, search = searchTerm) => {
      setIsChangingPage(true);
      setLoading(true);
      setError(null);

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

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

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

      try {
        const response = await carrinhoService.buscarPorUsuario(
          usuario,
          page,
          PAGE_SIZE
        );

        if (response.success) {
          setCarrinhos(response.documents || []);
          setTotalCarrinhos(response.total || 0);
          setCurrentPage(page);
          setSearchTerm(usuario);
        } else {
          setError(response.error || 'Erro ao buscar carrinhos');
        }
      } catch (err) {
        setError('Erro de conexão ao buscar carrinhos');
      } finally {
        setLoading(false);
        setIsChangingPage(false);
      }
    },
    []
  );

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

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

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

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

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

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

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

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

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

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

    if (searchTerm.trim()) {
      buscarCarrinhos(searchTerm, currentPage);
    } else {
      listarCarrinhos(currentPage);
    }
  }, [currentPage, searchTerm, listarCarrinhos, buscarCarrinhos]);

  return {
    carrinhos,
    loading,
    isChangingPage,
    isCreating,
    error,
    totalCarrinhos,
    currentPage,
    listarCarrinhos,
    buscarCarrinhos,
    cadastrarCarrinho,
    atualizarCarrinho,
    deletarCarrinho,
    setCurrentPage,
    searchTerm,
    setSearchTerm
  };
};
