import { useState, useCallback, useEffect } from 'react';
import { companiesApi } from '../api';
import type { Company, CompanyFilters, CreateCompanyDto, UpdateCompanyDto } from '../types';

interface UseCompaniesState {
  companies: Company[];
  total: number;
  page: number;
  totalPages: number;
  isLoading: boolean;
  error: string | null;
}

interface UseCompaniesReturn extends UseCompaniesState {
  filters: CompanyFilters;
  setFilters: (filters: CompanyFilters) => void;
  refresh: () => Promise<void>;
  createCompany: (data: CreateCompanyDto) => Promise<Company>;
  updateCompany: (id: string, data: UpdateCompanyDto) => Promise<Company>;
  deleteCompany: (id: string) => Promise<void>;
}

export function useCompanies(initialFilters?: CompanyFilters): UseCompaniesReturn {
  const [state, setState] = useState<UseCompaniesState>({
    companies: [],
    total: 0,
    page: 1,
    totalPages: 1,
    isLoading: true,
    error: null,
  });

  const [filters, setFilters] = useState<CompanyFilters>(initialFilters || { page: 1, limit: 10 });

  const fetchCompanies = useCallback(async () => {
    setState((prev) => ({ ...prev, isLoading: true, error: null }));
    try {
      const response = await companiesApi.getAll(filters);
      setState({
        companies: response.data,
        total: response.meta.total,
        page: response.meta.page,
        totalPages: response.meta.totalPages,
        isLoading: false,
        error: null,
      });
    } catch (err) {
      setState((prev) => ({
        ...prev,
        isLoading: false,
        error: err instanceof Error ? err.message : 'Error al cargar empresas',
      }));
    }
  }, [filters]);

  useEffect(() => {
    fetchCompanies();
  }, [fetchCompanies]);

  const createCompany = async (data: CreateCompanyDto): Promise<Company> => {
    const company = await companiesApi.create(data);
    await fetchCompanies();
    return company;
  };

  const updateCompany = async (id: string, data: UpdateCompanyDto): Promise<Company> => {
    const company = await companiesApi.update(id, data);
    await fetchCompanies();
    return company;
  };

  const deleteCompany = async (id: string): Promise<void> => {
    await companiesApi.delete(id);
    await fetchCompanies();
  };

  return {
    ...state,
    filters,
    setFilters,
    refresh: fetchCompanies,
    createCompany,
    updateCompany,
    deleteCompany,
  };
}

// Hook for single company
export function useCompany(id: string | undefined) {
  const [company, setCompany] = useState<Company | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchCompany = useCallback(async () => {
    if (!id) {
      setIsLoading(false);
      return;
    }

    setIsLoading(true);
    setError(null);
    try {
      const data = await companiesApi.getById(id);
      setCompany(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error al cargar empresa');
    } finally {
      setIsLoading(false);
    }
  }, [id]);

  useEffect(() => {
    fetchCompany();
  }, [fetchCompany]);

  return { company, isLoading, error, refresh: fetchCompany };
}

// Hook for company children (subsidiaries)
export function useCompanyChildren(parentId: string | undefined) {
  const [children, setChildren] = useState<Company[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!parentId) {
      setIsLoading(false);
      return;
    }

    const fetchChildren = async () => {
      setIsLoading(true);
      setError(null);
      try {
        const data = await companiesApi.getChildren(parentId);
        setChildren(data);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Error al cargar subsidiarias');
      } finally {
        setIsLoading(false);
      }
    };

    fetchChildren();
  }, [parentId]);

  return { children, isLoading, error };
}
