'use client';

import { create } from 'zustand';
import { persist } from 'zustand/middleware';

export interface Profile {
  id: string;
  name: string;
  avatarColor: string; // Tailwind gradient class (e.g. from-pink-500 to-rose-500)
  avatarEmoji: string; // Emoji representing the profile character
  avatarUrl?: string;  // Illustrated avatar image URL
  isKids: boolean;
}

export interface WatchProgress {
  id: string; // Unique progress ID
  contentId: string; // IPTV stream id
  type: 'movie' | 'series';
  title: string;
  logoUrl: string;
  streamUrl: string;
  categoryId: string;
  categoryName?: string;
  currentTime: number; // in seconds
  duration: number; // in seconds
  updatedAt: string;
  // For series episodes
  seriesId?: string;
  seasonId?: string;
  episodeId?: string;
  episodeTitle?: string;
}

interface ProfileState {
  profiles: Profile[];
  activeProfile: Profile | null;
  favorites: Record<string, string[]>; // profileId -> contentIds (favorites)
  watchProgress: Record<string, WatchProgress[]>; // profileId -> WatchProgress[]
  _hasHydrated: boolean;

  // Actions
  selectProfile: (profile: Profile | null) => void;
  addProfile: (name: string, avatarColor: string, avatarEmoji: string, isKids: boolean, avatarUrl?: string) => void;
  deleteProfile: (id: string) => void;
  toggleFavorite: (contentId: string) => void;
  isFavorite: (contentId: string) => boolean;
  saveProgress: (
    contentId: string,
    type: 'movie' | 'series',
    title: string,
    logoUrl: string,
    streamUrl: string,
    categoryId: string,
    currentTime: number,
    duration: number,
    extra?: { seriesId?: string; categoryName?: string; seasonId?: string; episodeId?: string; episodeTitle?: string }
  ) => void;
  getProgress: (contentId: string) => WatchProgress | undefined;
  clearProgress: (contentId?: string) => void;
  setHasHydrated: (state: boolean) => void;
}

// Pre-defined modern gradients for Netflix-style profiles (CSS linear gradients)
export const PROFILE_AVATAR_GRADIENTS = [
  'linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%)', // Blue
  'linear-gradient(135deg, #7f1d1d 0%, #ef4444 100%)', // Red
  'linear-gradient(135deg, #064e3b 0%, #10b981 100%)', // Green
  'linear-gradient(135deg, #78350f 0%, #f59e0b 100%)', // Yellow
  'linear-gradient(135deg, #4c1d95 0%, #8b5cf6 100%)', // Purple
  'linear-gradient(135deg, #831843 0%, #ec4899 100%)', // Pink
];

export const PROFILE_AVATAR_EMOJIS = ['😎', '🤖', '👾', '🐱', '🦊', '🦄', '🍿', '👑', '👽', '🐼'];

export const useProfileStore = create<ProfileState>()(
  persist(
    (set, get) => ({
      profiles: [],
      activeProfile: null,
      favorites: {},
      watchProgress: {},
      _hasHydrated: false,

      selectProfile: (profile) => set({ activeProfile: profile }),

      addProfile: (name, avatarColor, avatarEmoji, isKids, avatarUrl) => {
        const newProfile: Profile = {
          id: Math.random().toString(36).substring(2, 9),
          name,
          avatarColor,
          avatarEmoji,
          avatarUrl,
          isKids
        };
        set((state) => ({
          profiles: [...state.profiles, newProfile]
        }));
      },

      deleteProfile: (id) => {
        set((state) => {
          const newProfiles = state.profiles.filter((p) => p.id !== id);
          const active = state.activeProfile?.id === id ? null : state.activeProfile;
          
          // Clean up progress and favorites
          const newFavorites = { ...state.favorites };
          delete newFavorites[id];
          const newProgress = { ...state.watchProgress };
          delete newProgress[id];

          return {
            profiles: newProfiles,
            activeProfile: active,
            favorites: newFavorites,
            watchProgress: newProgress
          };
        });
      },

      toggleFavorite: (contentId) => {
        const { activeProfile } = get();
        if (!activeProfile) return;

        set((state) => {
          const profileId = activeProfile.id;
          const currentFavorites = state.favorites[profileId] || [];
          const isFav = currentFavorites.includes(contentId);
          
          const updated = isFav 
            ? currentFavorites.filter(id => id !== contentId) 
            : [...currentFavorites, contentId];

          return {
            favorites: {
              ...state.favorites,
              [profileId]: updated
            }
          };
        });
      },

      isFavorite: (contentId) => {
        const { activeProfile, favorites } = get();
        if (!activeProfile) return false;
        return (favorites[activeProfile.id] || []).includes(contentId);
      },

      saveProgress: (contentId, type, title, logoUrl, streamUrl, categoryId, currentTime, duration, extra) => {
        const { activeProfile } = get();
        if (!activeProfile) return;

        // Don't save if progress is less than 5 seconds or near the end (97%)
        if (currentTime < 5 || (currentTime / duration) > 0.97) {
          get().clearProgress(contentId);
          return;
        }

        const profileId = activeProfile.id;
        set((state) => {
          const currentList = state.watchProgress[profileId] || [];
          const existingIndex = currentList.findIndex(p => p.contentId === contentId);

          const newProgressItem: WatchProgress = {
            id: existingIndex !== -1 ? currentList[existingIndex].id : Math.random().toString(36).substring(2, 9),
            contentId,
            type,
            title,
            logoUrl,
            streamUrl,
            categoryId,
            currentTime,
            duration,
            updatedAt: new Date().toISOString(),
            ...extra
          };

          let updatedList = [...currentList];
          if (existingIndex !== -1) {
            updatedList[existingIndex] = newProgressItem;
          } else {
            updatedList.push(newProgressItem);
          }

          // Sort by updatedAt descending
          updatedList.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());

          // Limit to maximum of 10 items per profile
          const limitedList = updatedList.slice(0, 10);

          return {
            watchProgress: {
              ...state.watchProgress,
              [profileId]: limitedList
            }
          };
        });
      },

      getProgress: (contentId) => {
        const { activeProfile, watchProgress } = get();
        if (!activeProfile) return undefined;
        return (watchProgress[activeProfile.id] || []).find(p => p.contentId === contentId);
      },

      clearProgress: (contentId) => {
        const { activeProfile } = get();
        if (!activeProfile) return;

        const profileId = activeProfile.id;
        set((state) => {
          const currentList = state.watchProgress[profileId] || [];
          const updated = contentId ? currentList.filter(p => p.contentId !== contentId) : [];
          return {
            watchProgress: {
              ...state.watchProgress,
              [profileId]: updated
            }
          };
        });
      },

      setHasHydrated: (state) => set({ _hasHydrated: state })
    }),
    {
      name: 'profiles-storage',
      partialize: (state) => ({
        profiles: state.profiles,
        activeProfile: state.activeProfile,
        favorites: state.favorites,
        watchProgress: state.watchProgress,
      }),
      onRehydrateStorage: () => (state) => {
        state?.setHasHydrated(true);
      }
    }
  )
);
