/* eslint-disable spellcheck/spell-checker */
'use client';

import React, { useEffect, useState } from 'react';
import { useSession } from 'next-auth/react';
import { type Session } from 'next-auth';
import { Alert, Button, Progress, Spin, Tag } from 'antd';
import { ClockCircleOutlined, LockOutlined, InfoCircleFilled, CheckOutlined } from '@ant-design/icons';
import TrainingVideoPlayer from './TrainingVideoPlayer';
import { useTrainingVideoData } from './useTrainingVideoData';

interface TrainingVideoGateProps {
  onComplete: (updatedSession: Session) => void
}

const firstIncompleteIndex = (detail: number[]): number => {
  const idx = detail.findIndex((percent) => percent < 100);
  return idx === -1 ? 0 : idx;
};

const TrainingVideoGate: React.FC<TrainingVideoGateProps> = ({ onComplete }) => {
  const { update } = useSession();
  const { videos, videoDetail, updateVideoDetailLocal, loading } = useTrainingVideoData();

  const [currentVideoIndex, setCurrentVideoIndex] = useState<number>(0);
  const [continuing, setContinuing] = useState<boolean>(false);

  // Once the catalog + the user's progress have loaded, jump straight to the first
  // not-yet-completed video instead of always starting at index 0.
  useEffect(() => {
    if (!loading) {
      setCurrentVideoIndex(firstIncompleteIndex(videoDetail));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [loading]);

  const totalVideos = videos.length;
  const overallProgress = totalVideos > 0 ? Math.round(videoDetail.reduce((sum, value) => sum + value, 0) / totalVideos) : 0;
  const completedCount = videoDetail.filter((value) => value >= 100).length;
  // Vacuously "complete" if no videos are configured, so a misconfigured/empty catalog
  // can't lock every new user out of the CRM.
  const allVideosCompleted = totalVideos === 0 || completedCount === totalVideos;

  const handleVideoCompleted = (index: number): void => {
    updateVideoDetailLocal(index, 100);
    if (index < totalVideos - 1) {
      setCurrentVideoIndex(index + 1);
    }
  };

  const handleContinue = async(): Promise<void> => {
    setContinuing(true);
    try {
      const updatedSession = await update({ training_video_watched: true, training_video_progress: 100 });
      if (updatedSession) {
        onComplete(updatedSession as Session);
      }
    } finally {
      setContinuing(false);
    }
  };

  return (
    <div className="min-h-screen bg-slate-50 p-6">
      <div className="mx-auto max-w-5xl">
        <div className="mb-4 flex items-start justify-between gap-4 rounded-xl border border-blue-100 bg-blue-50 px-5 py-3">
          <div className="flex items-start gap-3">
            <InfoCircleFilled className="mt-0.5 text-lg text-blue-500" />
            <div>
              <div className="font-semibold text-slate-800">Welcome to the CRM!</div>
              <div className="text-sm text-slate-500">To ensure a smooth start, please watch all the training videos below.</div>
            </div>
          </div>
          <div className="flex shrink-0 items-center gap-2">
            <Tag color="blue" className="!m-0 !rounded-full">Required</Tag>
            <span className="hidden items-center gap-1 text-xs font-medium text-blue-600 md:flex">
              <LockOutlined /> You must complete these videos before using the CRM.
            </span>
          </div>
        </div>

        <div className="rounded-2xl border border-slate-100 bg-white p-8 shadow-sm">
          {loading ? (
            <div className="flex min-h-[300px] items-center justify-center">
              <Spin size="large" />
            </div>
          ) : totalVideos === 0 ? (
            <Alert type="info" showIcon message="No training videos are configured right now - you can continue to the CRM." />
          ) : (
            <div className="grid grid-cols-1 gap-10 md:grid-cols-2">
              <div>
                <h2 className="mb-1 text-2xl font-bold text-slate-800">Learn How to Use the CRM</h2>
                <p className="mb-6 text-sm text-slate-500">
                  These training videos will help you understand all the features and workflows in the CRM.
                </p>

                <div className="space-y-3">
                  {videos.map((video, index) => {
                    const percent = videoDetail[index] ?? 0;
                    const isCompleted = percent >= 100;
                    const isCurrent = index === currentVideoIndex;
                    const isLocked = index > 0 && (videoDetail[index - 1] ?? 0) < 100 && !isCompleted;

                    return (
                      <button
                        key={video.id}
                        type="button"
                        disabled={isLocked}
                        onClick={() => {
                          if (!isLocked) setCurrentVideoIndex(index);
                        }}
                        className={`flex w-full items-center gap-3 rounded-lg border p-3 text-left ${
                          isCurrent ? 'border-blue-200 bg-blue-50' : 'border-slate-100 bg-white'
                        } ${isLocked ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'}`}
                      >
                        <div
                          className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-sm font-semibold ${
                            isCompleted
                              ? 'bg-emerald-100 text-emerald-600'
                              : isCurrent
                                ? 'bg-blue-600 text-white'
                                : 'bg-slate-100 text-slate-400'
                          }`}
                        >
                          {isCompleted ? <CheckOutlined /> : isLocked ? <LockOutlined /> : index + 1}
                        </div>
                        <div className="min-w-0 flex-1">
                          <div className="truncate text-sm font-semibold text-slate-800">{video.title}</div>
                          <div className="text-xs text-slate-500">{isCompleted ? 'Completed' : `${percent}% watched`}</div>
                        </div>
                      </button>
                    );
                  })}
                </div>

                <div className="mt-6 border-t border-slate-100 pt-5">
                  <div className="mb-1 flex items-center gap-1.5 text-sm text-slate-500">
                    <ClockCircleOutlined /> Overall Progress
                  </div>
                  <div className="mb-2 text-sm font-semibold text-blue-600">
                    {overallProgress}% Completed ({completedCount}/{totalVideos} videos)
                  </div>
                  <Progress percent={overallProgress} showInfo={false} strokeColor="#2563eb" trailColor="#e2e8f0" />
                </div>
              </div>

              <TrainingVideoPlayer
                key={currentVideoIndex}
                video={videos[currentVideoIndex]}
                videoIndex={currentVideoIndex}
                initialProgress={videoDetail[currentVideoIndex] ?? 0}
                onProgressChange={updateVideoDetailLocal}
                onCompleted={handleVideoCompleted}
              />
            </div>
          )}

          <Alert
            className="mt-6"
            type="warning"
            showIcon
            icon={<LockOutlined />}
            message="Access Restricted"
            description="You won't be able to access the CRM features until you complete all the training videos."
            action={
              <Button type="primary" disabled={!allVideosCompleted} loading={continuing} onClick={handleContinue}>
                Continue to CRM
              </Button>
            }
          />
        </div>
      </div>
    </div>
  );
};

export default TrainingVideoGate;
