import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { videoDetailService, VideoDetail } from "@/services/videoDetailService";
import { VideoItem } from "@/types/home";

interface VideoDetailState {
  video: VideoDetail | null;
  relatedVideos: VideoItem[];
  isLoading: boolean;
  isRelatedLoading: boolean;
  error: string | null;
  relatedError: string | null;
}

const initialState: VideoDetailState = {
  video: null,
  relatedVideos: [],
  isLoading: false,
  isRelatedLoading: false,
  error: null,
  relatedError: null,
};

export const fetchVideoDetail = createAsyncThunk(
  "videoDetail/fetch",
  async (videoId: string, { dispatch, rejectWithValue }) => {
    try {
      const res = await videoDetailService.getVideoDetail(videoId);
      if (res.status !== 200) return rejectWithValue(res.message);
      const raw = res.result[0];
      if (!raw) return rejectWithValue("Video not found");
      const mapped = videoDetailService.mapVideoDetail(raw);
      dispatch(fetchRelatedVideos(videoId));
      return mapped;
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Failed to load video";
      return rejectWithValue(msg);
    }
  },
);

export const fetchRelatedVideos = createAsyncThunk(
  "videoDetail/fetchRelated",
  async (contentId: string, { rejectWithValue }) => {
    try {
      const res = await videoDetailService.getRelatedVideos(contentId);
      if (res.status !== 200) return rejectWithValue(res.message);
      return res.result.map(videoDetailService.mapRelatedVideo);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Failed to load related videos";
      return rejectWithValue(msg);
    }
  },
);

const videoDetailSlice = createSlice({
  name: "videoDetail",
  initialState,
  reducers: {
    clearVideoDetail: (state) => {
      state.video = null;
      state.relatedVideos = [];
      state.error = null;
      state.relatedError = null;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchVideoDetail.pending, (state) => {
        state.isLoading = true;
        state.error = null;
        state.video = null;
        state.relatedVideos = [];
      })
      .addCase(fetchVideoDetail.fulfilled, (state, action) => {
        state.isLoading = false;
        state.video = action.payload;
      })
      .addCase(fetchVideoDetail.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload as string;
      })
      .addCase(fetchRelatedVideos.pending, (state) => {
        state.isRelatedLoading = true;
        state.relatedError = null;
      })
      .addCase(fetchRelatedVideos.fulfilled, (state, action) => {
        state.isRelatedLoading = false;
        state.relatedVideos = action.payload;
        state.relatedError = null;
      })
      .addCase(fetchRelatedVideos.rejected, (state, action) => {
        state.isRelatedLoading = false;
        state.relatedError = (action.payload as string) ?? "No related videos found.";
      });
  },
});

export const { clearVideoDetail } = videoDetailSlice.actions;
export default videoDetailSlice.reducer;
