import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { Track } from '@/types/api';
import { recordPlay } from '@/features/tracks/services/trackService';

interface PlayerState {
  currentTrack: Track | null;
  isPlaying: boolean;
  currentTime: number;
  duration: number;
  volume: number;
  muted: boolean;
  queue: Track[];
  currentIndex: number;
  repeat: 'off' | 'track' | 'playlist';
  shuffle: boolean;
  
  // Actions
  play: (track: Track) => void;
  pause: () => void;
  resume: () => void;
  stop: () => void;
  next: () => void;
  previous: () => void;
  setCurrentTime: (time: number) => void;
  setDuration: (duration: number) => void;
  setVolume: (volume: number) => void;
  toggleMute: () => void;
  addToQueue: (track: Track) => void;
  removeFromQueue: (index: number) => void;
  reorderQueue: (from: number, to: number) => void;
  toggleShuffle: () => void;
  setRepeat: (mode: 'off' | 'track' | 'playlist') => void;
  clearQueue: () => void;
}

export const usePlayerStore = create<PlayerState>()(
  persist(
    (set, get) => ({
  currentTrack: null,
  isPlaying: false,
  currentTime: 0,
  duration: 0,
  volume: 100,
  muted: false,
  queue: [],
  currentIndex: -1,
  repeat: 'off',
  shuffle: false,

  play: (track) => {
    set({ currentTrack: track, isPlaying: true, currentTime: 0 });
    
    // T0295: Enregistrer le début de la lecture pour analytics
    if (track && track.id) {
      recordPlay(track.id, 0).catch((err) => {
        console.error('Failed to record play start:', err);
      });
    }
  },

  pause: () => {
    set({ isPlaying: false });
  },

  resume: () => {
    set({ isPlaying: true });
  },

  stop: () => {
    const state = get();
    const finalTime = state.currentTime;
    
    // T0295: Enregistrer la durée totale de lecture avant d'arrêter
    if (state.currentTrack && state.currentTrack.id && finalTime > 0) {
      recordPlay(state.currentTrack.id, Math.floor(finalTime)).catch((err) => {
        console.error('Failed to record play stop:', err);
      });
    }
    
    set({ isPlaying: false, currentTime: 0 });
  },

  next: () => {
    const { queue, currentIndex, repeat, shuffle } = get();
    
    if (queue.length === 0) return;
    
    let nextIndex = currentIndex;
    
    if (shuffle) {
      nextIndex = Math.floor(Math.random() * queue.length);
    } else if (currentIndex < queue.length - 1) {
      nextIndex = currentIndex + 1;
    } else if (repeat === 'playlist') {
      nextIndex = 0;
    }
    
    if (nextIndex !== currentIndex && nextIndex < queue.length) {
      set({ currentIndex: nextIndex, currentTrack: queue[nextIndex], currentTime: 0 });
    }
  },

  previous: () => {
    const { queue, currentIndex } = get();
    
    if (queue.length === 0 || currentIndex <= 0) return;
    
    const prevIndex = currentIndex - 1;
    set({ currentIndex: prevIndex, currentTrack: queue[prevIndex], currentTime: 0 });
  },

  setCurrentTime: (time) => {
    const state = get();
    set({ currentTime: time });
    
    // T0295: Enregistrer la lecture pour analytics
    // Enregistrer toutes les 30 secondes ou à la fin de la lecture
    if (state.currentTrack && state.isPlaying && state.duration > 0) {
      const trackId = state.currentTrack.id;
      const shouldRecord = 
        (time > 0 && Math.floor(time) % 30 === 0) || // Toutes les 30 secondes
        (time >= state.duration * 0.9); // À 90% de la durée
      
      if (shouldRecord) {
        // Enregistrer de manière asynchrone sans bloquer
        recordPlay(trackId, Math.floor(time)).catch((err) => {
          console.error('Failed to record play:', err);
        });
      }
    }
  },

  setDuration: (duration) => {
    set({ duration });
  },

  setVolume: (volume) => {
    set({ volume: Math.max(0, Math.min(100, volume)) });
  },

  toggleMute: () => {
    set({ muted: !get().muted });
  },

  addToQueue: (track) => {
    const { queue } = get();
    set({ queue: [...queue, track] });
  },

  removeFromQueue: (index) => {
    const { queue, currentIndex } = get();
    const newQueue = queue.filter((_, i) => i !== index);
    
    // Adjust current index if needed
    let newIndex = currentIndex;
    if (index <= currentIndex) {
      newIndex = Math.max(0, currentIndex - 1);
    }
    
    set({ queue: newQueue, currentIndex: newIndex });
  },

  reorderQueue: (from, to) => {
    const { queue } = get();
    const newQueue = [...queue];
    const [removed] = newQueue.splice(from, 1);
    newQueue.splice(to, 0, removed);
    set({ queue: newQueue });
  },

  toggleShuffle: () => {
    set({ shuffle: !get().shuffle });
  },

  setRepeat: (mode) => {
    set({ repeat: mode });
  },

  clearQueue: () => {
    set({ queue: [], currentIndex: -1, currentTrack: null });
  },
}),
    {
      name: 'player-storage',
      partialize: state => ({
        volume: state.volume,
        muted: state.muted,
        repeat: state.repeat,
        shuffle: state.shuffle,
        queue: state.queue,
      }),
    }
  )
);

