import dayjs from 'dayjs';
import { createSlice, type PayloadAction } from '@reduxjs/toolkit';

import {
  ACCESS_LEVEL_HUB,
  ASPECT_RATIO_16_9,
  AUTH_METHOD_NOAUTH,
  CONTENT_TYPE_ALL,
  FILE_SELECTION_NONE,
  FIT_FILL,
  REDUX_FIELD_NAME,
  RESOLUTION_HEIGHT,
  SCHEDULE_TYPE_DAILY,
  SPEECH_TO_TEXT_ANYCLIP_S2T_VALUE,
  SPEECH_TO_TEXT_DISABLED_VALUE,
  SPEECH_TO_TEXT_OPTIONS,
  TAB_GENERAL,
  VIDEO_FILE_TYPE_MP4M3U8,
  YT_CONTENT_TYPE_CHANNEL,
} from '../../constants';
import { STATUS_ACTIVE, TYPE_RSS, TYPE_SITEMAP, TYPE_STORY_API } from '@/modules/feeds/constants';

import { FeedType, MetadataFeed } from '../../types';

import { validationScheme } from '../../helpers/validationScheme';
import createFormSlice from '@/modules/@common/Form/redux/slices';
import { applyPartial } from '@/modules/@common/store/helpers';

const formSlice = createFormSlice(REDUX_FIELD_NAME, validationScheme);

export type StateType = FeedType & {
  contentOwnerIsPublic: boolean;
  accountOptions: FeedType['account'][] | null;
  hubsOptions: FeedType['accessPublishers'] | null;
  ownersOptions: FeedType['accessVideoOwner'][] | null;
  activeTabId: string;
  metadata: MetadataFeed;
  oAuthClientId: string | null;
  isSelfServeUser: boolean;
};

/**
 * A lookup table of default values for different store state keys,
 * where each state key can have different defaults depending on the feed type.
 *
 * This is used inside the `@/modules/feeds/Editor/hooks/useSetStoreDefaultValues` hook to reassign
 * store state defaults dynamically based on the selected feed type.
 *
 * Structure:
 * - Top-level keys: properties from `StateType` (e.g., `minResolutionValue`)
 * - Second-level keys: specific `FeedType['type']` values or `'default'` for fallback
 * - Values: can be of any type (`unknown`), but usually numbers, strings, booleans, arrays, or objects
 *
 * Example:
 * defaultValuesByFeedType.minResolutionValue?.[TYPE_MRSS] // 720
 * defaultValuesByFeedType.minResolutionValue?.default     // 720 (fallback)
 */
export const defaultStoreValuesDependsOnFeedType: Partial<
  Record<keyof StateType, Partial<Record<FeedType['type'] | 'initialStateValue', unknown>>>
> = {
  minResolutionValue: {
    initialStateValue: 720,
    [TYPE_RSS]: 190,
    [TYPE_SITEMAP]: 190,
    [TYPE_STORY_API]: 190,
  },
  speechToTextProvider: {
    initialStateValue: SPEECH_TO_TEXT_ANYCLIP_S2T_VALUE,
    [TYPE_RSS]: SPEECH_TO_TEXT_DISABLED_VALUE,
    [TYPE_SITEMAP]: SPEECH_TO_TEXT_DISABLED_VALUE,
    [TYPE_STORY_API]: SPEECH_TO_TEXT_DISABLED_VALUE,
  },
};

const initialState: StateType = {
  type: '',
  id: null,
  name: '',
  description: '',
  status: STATUS_ACTIVE,
  source: {
    isConnected: false,
    importParticipantsNames: false,
  },
  account: null,
  lang: 'EN',
  accessLevel: ACCESS_LEVEL_HUB,
  accessAllPublishers: false,
  accessPublishers: [],
  accessVideoOwner: null,
  // auth
  url: '',
  user: '',
  password: '',
  isUseForDownload: false,
  authMethod: AUTH_METHOD_NOAUTH,

  scheduleStatus: false,
  scheduleType: SCHEDULE_TYPE_DAILY,
  scheduleValue: '00:00',
  scheduleFrequency: 60,

  feedPriority: 0.5,
  priorityVerification: false,

  iabCategories: '[]',

  defaultTimezone: 'UTC',
  defaultTimezoneEnabled: false,

  isEvergreenFeed: false,
  isRestricted: false,
  keywords: '',
  parseKeywordsToLabels: false,

  maxDuration: 300,
  importPlot: true,

  fileSelection: FILE_SELECTION_NONE,
  resolution: RESOLUTION_HEIGHT,
  resolutionValue: 720,
  minResolutionValue: defaultStoreValuesDependsOnFeedType.minResolutionValue!.initialStateValue as number,
  bitrate: 7000,
  minBitrate: 4500,

  videoFileType: VIDEO_FILE_TYPE_MP4M3U8,

  importCCFromMrssFile: false,
  createClip: true,
  skipTaggingForLongClips: true,
  maxDurationForTagging: 300,
  immediateAvailability: false,
  processVideoVersions: false,
  versionAttributeName: '',
  automationScript: '{}',
  platformModels: [],
  speechToTextProvider: defaultStoreValuesDependsOnFeedType.speechToTextProvider!
    .initialStateValue as (typeof SPEECH_TO_TEXT_OPTIONS)[number]['value'],
  loadFromLastDays: 1,
  discardLongClips: false,
  fillLandingPage: false,
  youtubeContentType: YT_CONTENT_TYPE_CHANNEL,
  youTubeChannelId: '',
  youTubeLoadFromDate: dayjs(new Date()).format('YYYY-MM-DD'),
  contentType: CONTENT_TYPE_ALL,
  importShortsThumbnail: false,
  // rss
  maxStories: 12,
  videoDuration: 6,
  aspectRatio: ASPECT_RATIO_16_9,
  fit: FIT_FILL,
  videoMaxZoom: 10,
  jsRendering: false,

  accountOptions: null,
  hubsOptions: null,
  ownersOptions: null,
  activeTabId: TAB_GENERAL,
  contentOwnerIsPublic: false,
  metadata: {
    languages: null,
    platformModels: null,
    speechToTextLanguages: null,
    timezones: null,
  },
  oAuthClientId: null,
  oAuthToken: null,
  isSelfServeUser: false,
  ...formSlice.state,
};

export const slice = createSlice({
  name: '@@FEEDS/EDITOR',
  initialState,
  reducers: {
    setAction: (state: StateType, action: PayloadAction<Partial<StateType>>) => {
      applyPartial<StateType>(state, action.payload);
    },
    getMetadataAction: (state: StateType, action: PayloadAction<{ id: number | undefined }>) => {
      if (action.payload) {
        return state;
      }

      return state;
    },
    getItemAction: (state: StateType, action: PayloadAction<{ id: number }>) => {
      if (action.payload) {
        return state;
      }

      return state;
    },
    getAccountOptionsAction: (state: StateType, action: PayloadAction<{ searchText: string }>) => {
      if (action.payload) {
        return state;
      }

      return state;
    },
    getHubsOptionsAction: (state: StateType, action: PayloadAction<{ searchText: string }>) => {
      if (action.payload) {
        return state;
      }

      return state;
    },
    getOwnersOptionsAction: (state: StateType, action: PayloadAction<{ searchText: string }>) => {
      if (action.payload) {
        return state;
      }

      return state;
    },
    updateItemAction: (state: StateType, action: PayloadAction<{ id: number }>) => {
      if (action.payload) {
        return state;
      }

      return state;
    },
    createItemAction: (state: StateType) => state,
    getOAuthClientIdAction: (state: StateType) => state,
    getOAuthTokenAction: (state: StateType, action: PayloadAction<{ code: string }>) => {
      if (action.payload) {
        return state;
      }

      return state;
    },
    setActiveTabIdAction: (state, action) => {
      state.activeTabId = action.payload;
    },
    setInitialAction: (state: StateType) => {
      applyPartial<StateType>(state, initialState, ['isSelfServeUser']);
    },
    setScrollToFieldNameAction: formSlice.actions.setScrollToFieldAction,
    setErrorByPropAction: formSlice.actions.updateValidationSchemeAction,
    removeErrorByPropAction: (state: StateType, action) =>
      formSlice.actions.removeErrorByFieldNameAction(state, action),
  },
});

export const {
  setAction,
  setScrollToFieldNameAction,
  setErrorByPropAction,
  removeErrorByPropAction,
  getMetadataAction,
  getItemAction,
  getAccountOptionsAction,
  getHubsOptionsAction,
  getOwnersOptionsAction,
  setActiveTabIdAction,
  setInitialAction,
  updateItemAction,
  createItemAction,
  getOAuthClientIdAction,
  getOAuthTokenAction,
} = slice.actions;

export const { validateFields, validateSingleField } = formSlice;
