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

import React, { useEffect, useRef, useState } from 'react';
import { Alert, Button, Spin, Tag } from 'antd';
import { CheckOutlined, PlayCircleOutlined } from '@ant-design/icons';
import PageHeader from '@/components/pageHeader';
import TrainingVideoPlayer from '@/components/trainingVideo/TrainingVideoPlayer';
import { useTrainingVideoData } from '@/components/trainingVideo/useTrainingVideoData';

const OnboardingPage: React.FC = () => {
  const { videos, videoDetail, updateVideoDetailLocal, loading } = useTrainingVideoData();
  const [expandedIndex, setExpandedIndex] = useState<number | null>(null);
  const cardRefs = useRef<(HTMLDivElement | null)[]>([]);

  useEffect(() => {
    if (expandedIndex === null) return;
    const node = cardRefs.current[expandedIndex];
    if (!node) return;
    const timeout = setTimeout(() => {
      node.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }, 100);
    return () => clearTimeout(timeout);
  }, [expandedIndex]);

  return (
    <div>
      <PageHeader title="Onboarding" isBack={false} />

      {loading ? (
        <div className="flex min-h-[200px] items-center justify-center">
          <Spin size="large" />
        </div>
      ) : videos.length === 0 ? (
        <Alert type="info" showIcon message="No training videos are configured yet." />
      ) : (
        <div className="mx-auto max-w-4xl">
          <p className="mb-6 text-sm text-slate-500">
            Review any of the CRM training videos below at any time - completed videos stay available so you can revisit specific parts whenever you need to.
          </p>

          <div className="space-y-4">
            {videos.map((video, index) => {
              const percent = videoDetail[index] ?? 0;
              const isCompleted = percent >= 100;
              const isExpanded = expandedIndex === index;

              return (
                <div
                  key={video.id}
                  ref={(el) => {
                    cardRefs.current[index] = el;
                  }}
                  className={`overflow-hidden rounded-2xl border bg-white shadow-sm transition-shadow duration-300 ${
                    isExpanded ? 'border-blue-200 ring-2 ring-blue-100' : 'border-slate-100'
                  }`}
                >
                  <div className="flex flex-col gap-3 p-5 sm:flex-row sm:items-center sm:gap-4">
                    <div
                      className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-base font-semibold ${
                        isCompleted ? 'bg-emerald-100 text-emerald-600' : 'bg-blue-50 text-blue-600'
                      }`}
                    >
                      {isCompleted ? <CheckOutlined /> : <PlayCircleOutlined />}
                    </div>
                    <div className="min-w-0 flex-1">
                      <div className="truncate text-base font-semibold text-slate-800">{video.title}</div>
                      <div className="mt-1">
                        <Tag color={isCompleted ? 'success' : percent > 0 ? 'blue' : 'default'} className="!m-0">
                          {isCompleted ? 'Completed' : percent > 0 ? `${percent}% watched` : 'Not started'}
                        </Tag>
                      </div>
                    </div>
                    <Button
                      type={isExpanded ? 'default' : 'primary'}
                      className="w-full sm:w-auto"
                      onClick={() => setExpandedIndex(isExpanded ? null : index)}
                    >
                      {isExpanded ? 'Close' : isCompleted ? 'Adjust Playback' : percent > 0 ? 'Continue Watching' : 'Watch'}
                    </Button>
                  </div>

                  {isExpanded && (
                    <div className="animate-fadeIn border-t border-slate-100 p-5">
                      <TrainingVideoPlayer
                        key={index}
                        video={video}
                        videoIndex={index}
                        initialProgress={percent}
                        onProgressChange={updateVideoDetailLocal}
                      />
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
};

export default OnboardingPage;
