import { useState, useCallback, useRef, useEffect } from 'react';
import { Models } from 'appwrite';
import { enderecoService, EnderecoData } from '@/services/enderecoService';
export type { EnderecoData };

export interface UseEnderecosReturn {
  enderecos: Models.Document[];
  loading: boolean;
  isChangingPage: boolean;
  isCreating: boolean;
  error: string | null;
  totalEnderecos: number;
  currentPage: number;
  listarEnderecos: (page?: number, search?: string) => Promise<void>;
  buscarEnderecos: (termo: string, page?: number) => Promise<void>;
  cadastrarEndereco: (data: EnderecoData) => Promise<boolean>;
  atualizarEndereco: (id: string, data: EnderecoData) => Promise<boolean>;
  deletarEndereco: (id: string) => Promise<boolean>;
  setCurrentPage: (page: number) => void;
  searchTerm: string;
  setSearchTerm: (term: string) => void;
}

const PAGE_SIZE = 10;

export const useEnderecos = (): UseEnderecosReturn => {
  const [enderecos, setEnderecos] = useState<Models.Document[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [totalEnderecos, setTotalEnderecos] = 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 listarEnderecos = useCallback(
    async (page = currentPage, search = searchTerm) => {
    setIsChangingPage(true);
    setLoading(true);
    setError(null);

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

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

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

      try {
        const response = await enderecoService.buscar(
          termo,
          page,
          PAGE_SIZE
        );

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

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

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

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

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

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

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

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

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

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

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

    if (searchTerm.trim()) {
      buscarEnderecos(searchTerm, currentPage);
    } else {
      listarEnderecos(currentPage);
    }
  }, [currentPage, searchTerm, listarEnderecos, buscarEnderecos]);

  return {
    enderecos,
    loading,
    isChangingPage,
    isCreating,
    error,
    totalEnderecos,
    currentPage,
    listarEnderecos,
    buscarEnderecos,
    cadastrarEndereco,
    atualizarEndereco,
    deletarEndereco,
    setCurrentPage,
    searchTerm,
    setSearchTerm,
  };
};
