/* eslint-disable spellcheck/spell-checker */
import { useEffect, useState } from 'react';
import { getTrainingVideos } from './service';
import { getCurrentUserProfile } from '@/app/auth/service';
import { clampPercent } from './utils';
import { type TrainingVideoDefinition } from './constants';

interface TrainingVideoRow {
  id: number
  title: string
  video_url: string
}

interface UseTrainingVideoDataResult {
  videos: TrainingVideoDefinition[]
  videoDetail: number[]
  updateVideoDetailLocal: (index: number, percent: number) => void
  loading: boolean
}

// Shared by TrainingVideoGate and the /onboarding page: fetches the training video catalog
// (now DB-backed) alongside the current user's per-video progress, and exposes local
// progress-array updates so callers stay in sync as TrainingVideoPlayer reports playback.
export function useTrainingVideoData(): UseTrainingVideoDataResult {
  const [videos, setVideos] = useState<TrainingVideoDefinition[]>([]);
  const [videoDetail, setVideoDetail] = useState<number[]>([]);
  const [loading, setLoading] = useState<boolean>(true);

  useEffect(() => {
    let cancelled = false;

    Promise.all([getTrainingVideos(), getCurrentUserProfile()])
      .then(([videosResponse, profileResponse]) => {
        if (cancelled) return;

        const rows: TrainingVideoRow[] = Array.isArray(videosResponse.data?.data) ? videosResponse.data.data : [];
        const fetchedVideos: TrainingVideoDefinition[] = rows.map((row) => ({
          id: row.id,
          title: row.title,
          url: row.video_url,
        }));
        setVideos(fetchedVideos);

        const rawDetail = profileResponse.data?.training_video_progress_detail;
        const detail = Array.isArray(rawDetail) && rawDetail.length === fetchedVideos.length
          ? rawDetail.map(clampPercent)
          : new Array(fetchedVideos.length).fill(0);
        setVideoDetail(detail);
      })
      .catch(() => {
        // Leave videos/videoDetail empty - callers should show a friendly empty/error state.
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });

    return () => {
      cancelled = true;
    };
  }, []);

  const updateVideoDetailLocal = (index: number, percent: number): void => {
    setVideoDetail((prev) => {
      const next = [...prev];
      next[index] = Math.max(next[index] ?? 0, percent);
      return next;
    });
  };

  return { videos, videoDetail, updateVideoDetailLocal, loading };
}
