import { useState, useEffect } from 'react';
import { CounterWithStats, AnonymousCounter, CreateCounterRequest, UpdateCounterRequest, CounterEntry } from '../types';
import { countersAPI } from '../services/api';
import { localStorageService } from '../services/localStorage';
import { useAuth } from './useAuth';

export const useCounters = () => {
  const { isAuthenticated } = useAuth();
  const [counters, setCounters] = useState<CounterWithStats[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [version, setVersion] = useState(0); // Force re-renders

  // Load counters based on authentication status
  useEffect(() => {
    loadCounters();
  }, [isAuthenticated]);

  useEffect(() => {
    console.log('Counters:', counters);
  }, [counters]);

  const loadCounters = async (search?: string) => {
    setIsLoading(true);
    setError(null);
    try {
      if (isAuthenticated) {
        // Load from API
        const response = await countersAPI.getCounters(search);
        console.log('Setting authenticated counters:', response.data);
        setCounters([...response.data]); // Ensure new array reference
        setVersion(prev => prev + 1); // Force re-render
      } else {
        // Load from localStorage and convert to CounterWithStats format
        const anonymousCounters = localStorageService.getAnonymousCounters();
        const convertedCounters = convertAnonymousToDisplay(anonymousCounters);
        console.log('Setting anonymous counters:', convertedCounters);
        setCounters([...convertedCounters]); // Ensure new array reference
        setVersion(prev => prev + 1); // Force re-render
      }
    } catch (err: any) {
      setError(err.response?.data?.error || 'Failed to load counters');
    } finally {
      setIsLoading(false);
    }
  };

  const convertAnonymousToDisplay = (anonymousCounters: AnonymousCounter[]): CounterWithStats[] => {
    console.log('Converting anonymous counters:', anonymousCounters);
    const converted = anonymousCounters.map(counter => {
      const today = localStorageService.getTodayString();
      const todayValue = counter.entries[today] || 0;
      
      const weekValue = Object.keys(counter.entries)
        .filter((date) => {
          const entryDate = new Date(date);
          const weekAgo = new Date();
          weekAgo.setDate(weekAgo.getDate() - 7);
          return entryDate >= weekAgo;
        })
        .reduce((sum, date) => sum + (counter.entries[date] as number), 0);
      
      const monthValue = Object.keys(counter.entries)
        .filter((date) => {
          const entryDate = new Date(date);
          const monthAgo = new Date();
          monthAgo.setMonth(monthAgo.getMonth() - 1);
          return entryDate >= monthAgo;
        })
        .reduce((sum, date) => sum + (counter.entries[date] as number), 0);
      
      const entryCount = Object.keys(counter.entries).reduce((sum: number, date: string) => sum + Math.abs(counter.entries[date] as number), 0);
      
      return {
        id: counter.id,
        name: counter.name,
        description: counter.description,
        created_at: counter.created_at,
        updated_at: counter.updated_at,
        total_value: counter.total_value,
        today_value: todayValue,
        week_value: weekValue,
        month_value: monthValue,
        entry_count: entryCount,
      };
    });
    
    console.log('Converted counters:', converted);
    return converted;
  };

  const createCounter = async (data: CreateCounterRequest) => {
    if (isAuthenticated) {
      try {
        const response = await countersAPI.createCounter(data);
        await loadCounters(); // Refresh the list
        return response.data;
      } catch (err: any) {
        throw new Error(err.response?.data?.error || 'Failed to create counter');
      }
    } else {
      // Create anonymous counter
      const newCounter: AnonymousCounter = {
        id: localStorageService.generateId(),
        name: data.name,
        description: data.description,
        total_value: 0,
        entries: {},
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
      };
      
      localStorageService.addAnonymousCounter(newCounter);
      await loadCounters(); // Refresh the list
      return newCounter;
    }
  };

  const updateCounter = async (id: number | string, data: UpdateCounterRequest) => {
    if (isAuthenticated) {
      try {
        const response = await countersAPI.updateCounter(id as number, data);
        await loadCounters(); // Refresh the list
        return response.data;
      } catch (err: any) {
        throw new Error(err.response?.data?.error || 'Failed to update counter');
      }
    } else {
      // Update anonymous counter
      const updated = { ...data, updated_at: new Date().toISOString() };
      localStorageService.updateAnonymousCounter(id as string, updated);
      await loadCounters(); // Refresh the list
      return { id, ...updated };
    }
  };

  const deleteCounter = async (id: number | string) => {
    if (isAuthenticated) {
      try {
        await countersAPI.deleteCounter(id as number);
        await loadCounters(); // Refresh the list
      } catch (err: any) {
        throw new Error(err.response?.data?.error || 'Failed to delete counter');
      }
    } else {
      // Delete anonymous counter
      localStorageService.deleteAnonymousCounter(id as string);
      await loadCounters(); // Refresh the list
    }
  };

  const incrementCounter = async (id: number | string, value: number) => {
    if (isAuthenticated) {
      try {
        const response = await countersAPI.incrementCounter(id as number, { value });
        await loadCounters(); // Refresh the list
        return response.data;
      } catch (err: any) {
        throw new Error(err.response?.data?.error || 'Failed to increment counter');
      }
    } else {
      // Increment anonymous counter
      const today = localStorageService.getTodayString();
      const counters = localStorageService.getAnonymousCounters();
      const counter = counters.find((c: AnonymousCounter) => c.id === id);
      
      if (!counter) {
        throw new Error('Counter not found');
      }

      const newTotal = counter.total_value + value;
      const newEntries = { ...counter.entries };
      newEntries[today] = (newEntries[today] || 0) + value;
      
      const updated = {
        total_value: newTotal,
        entries: newEntries,
        updated_at: new Date().toISOString(),
      };
      
      localStorageService.updateAnonymousCounter(id as string, updated);
      console.log('Increment completed, reloading counters...');
      await loadCounters(); // Refresh the list
      return { id, ...updated };
    }
  };

  const getCounterEntries = async (id: number | string): Promise<CounterEntry[]> => {
    if (isAuthenticated) {
      try {
        const response = await countersAPI.getCounterEntries(id as number);
        return response.data;
      } catch (err: any) {
        throw new Error(err.response?.data?.error || 'Failed to load counter entries');
      }
    } else {
      // Get entries from localStorage
      const counters = localStorageService.getAnonymousCounters();
      const counter = counters.find((c: AnonymousCounter) => c.id === id);
      
      if (!counter) {
        throw new Error('Counter not found');
      }

      return Object.entries(counter.entries || {}).map(([date, value], index) => ({
        id: index + 1,
        counter_id: parseInt(counter.id as string),
        value: value as number,
        date: date,
        created_at: counter.updated_at,
      }));
    }
  };

  const searchCounters = (search: string) => {
    loadCounters(search);
  };

  return {
    counters,
    isLoading,
    error,
    version, // Add version to force re-renders
    createCounter,
    updateCounter,
    deleteCounter,
    incrementCounter,
    getCounterEntries,
    searchCounters,
    refreshCounters: loadCounters,
  };
};