import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import { searchService, SearchItem } from "@/services/searchService";

interface SearchState {
  query: string;
  videos: SearchItem[];
  music: SearchItem[];
  isLoading: boolean;
  error: string | null;
  hasSearched: boolean;
}

const initialState: SearchState = {
  query: "",
  videos: [],
  music: [],
  isLoading: false,
  error: null,
  hasSearched: false,
};

export const performSearch = createAsyncThunk(
  "search/perform",
  async (query: string, { rejectWithValue }) => {
    try {
      return await searchService.search(query);
    } catch {
      return rejectWithValue("Search failed. Please try again.");
    }
  },
);

const searchSlice = createSlice({
  name: "search",
  initialState,
  reducers: {
    setQuery: (state, action: PayloadAction<string>) => {
      state.query = action.payload;
    },
    clearSearch: (state) => {
      state.query = "";
      state.videos = [];
      state.music = [];
      state.error = null;
      state.hasSearched = false;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(performSearch.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(performSearch.fulfilled, (state, action) => {
        state.isLoading = false;
        state.videos = action.payload.videos;
        state.music = action.payload.music;
        state.hasSearched = true;
      })
      .addCase(performSearch.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload as string;
        state.hasSearched = true;
      });
  },
});

export const { setQuery, clearSearch } = searchSlice.actions;
export default searchSlice.reducer;
