import { useState, useCallback, useEffect } from 'react';
import { partnersApi } from '../api';
import type { Partner, PartnerFilters, CreatePartnerDto, UpdatePartnerDto } from '../types';

interface UsePartnersState {
  partners: Partner[];
  total: number;
  page: number;
  totalPages: number;
  isLoading: boolean;
  error: string | null;
}

interface UsePartnersReturn extends UsePartnersState {
  filters: PartnerFilters;
  setFilters: (filters: PartnerFilters) => void;
  refresh: () => Promise<void>;
  createPartner: (data: CreatePartnerDto) => Promise<Partner>;
  updatePartner: (id: string, data: UpdatePartnerDto) => Promise<Partner>;
  deletePartner: (id: string) => Promise<void>;
  activatePartner: (id: string) => Promise<void>;
  deactivatePartner: (id: string) => Promise<void>;
}

export function usePartners(initialFilters?: PartnerFilters): UsePartnersReturn {
  const [state, setState] = useState<UsePartnersState>({
    partners: [],
    total: 0,
    page: 1,
    totalPages: 1,
    isLoading: true,
    error: null,
  });

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

  const fetchPartners = useCallback(async () => {
    setState((prev) => ({ ...prev, isLoading: true, error: null }));
    try {
      const response = await partnersApi.getAll(filters);
      setState({
        partners: 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 partners',
      }));
    }
  }, [filters]);

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

  const createPartner = async (data: CreatePartnerDto): Promise<Partner> => {
    const partner = await partnersApi.create(data);
    await fetchPartners();
    return partner;
  };

  const updatePartner = async (id: string, data: UpdatePartnerDto): Promise<Partner> => {
    const partner = await partnersApi.update(id, data);
    await fetchPartners();
    return partner;
  };

  const deletePartner = async (id: string): Promise<void> => {
    await partnersApi.delete(id);
    await fetchPartners();
  };

  const activatePartner = async (id: string): Promise<void> => {
    await partnersApi.activate(id);
    await fetchPartners();
  };

  const deactivatePartner = async (id: string): Promise<void> => {
    await partnersApi.deactivate(id);
    await fetchPartners();
  };

  return {
    ...state,
    filters,
    setFilters,
    refresh: fetchPartners,
    createPartner,
    updatePartner,
    deletePartner,
    activatePartner,
    deactivatePartner,
  };
}

// Hook for single partner
export function usePartner(id: string | undefined) {
  const [partner, setPartner] = useState<Partner | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

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

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

  return { partner, isLoading, error, refresh: fetchPartner };
}

// Hook for customers only
export function useCustomers(initialFilters?: PartnerFilters) {
  return usePartners({ ...initialFilters, isCustomer: true });
}

// Hook for suppliers only
export function useSuppliers(initialFilters?: PartnerFilters) {
  return usePartners({ ...initialFilters, isSupplier: true });
}
