import { useState, useEffect } from 'react';
import { apiClient } from '@/lib/api-client';
import { Portfolio } from '@/lib/types';

export function usePortfolios() {
  const [portfolios, setPortfolios] = useState<Portfolio[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchPortfolios = async () => {
    try {
      setIsLoading(true);
      setError(null);
      const response = await apiClient.get<Portfolio[]>('/portfolios');

      if (response.success && response.data) {
        setPortfolios(response.data);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to fetch portfolios');
    } finally {
      setIsLoading(false);
    }
  };

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

  const createPortfolio = async (name: string, domain: string) => {
    try {
      const response = await apiClient.post<Portfolio>('/portfolios', { name, domain });

      if (response.success && response.data) {
        setPortfolios([...portfolios, response.data]);
        return response.data;
      }
    } catch (err) {
      throw err;
    }
  };

  const uploadPortfolio = async (id: number, file: File) => {
    try {
      const formData = new FormData();
      formData.append('file', file);

      const response = await apiClient.upload<Portfolio>(`/portfolios/${id}/upload`, formData);

      if (response.success && response.data) {
        setPortfolios(portfolios.map(p => p.id === id ? response.data! : p));
        return response.data;
      }
    } catch (err) {
      throw err;
    }
  };

  const deployPortfolio = async (id: number) => {
    try {
      const response = await apiClient.post<Portfolio>(`/portfolios/${id}/deploy`);

      if (response.success && response.data) {
        setPortfolios(portfolios.map(p => p.id === id ? response.data! : p));
        return response.data;
      }
    } catch (err) {
      throw err;
    }
  };

  return {
    portfolios,
    isLoading,
    error,
    fetchPortfolios,
    createPortfolio,
    uploadPortfolio,
    deployPortfolio,
  };
}
