'use client';

import React, { useCallback, useRef, useState } from 'react';
import { CheckCircle2, FileText, PlayCircle } from 'lucide-react';
import { cn } from '@/utils/cn';
import { Button } from '@/components/ui/button';
import { useMarkTrainingModuleComplete, useRecordTrainingVideoProgress, useTrainingOverview } from '@/services/training/queries';
import { TrainingModuleItem } from '@/services/training/types';


export default function TrainingPage() {
  const { data, isLoading } = useTrainingOverview();
  const recordVideoProgress = useRecordTrainingVideoProgress();
  const markComplete = useMarkTrainingModuleComplete();
  const [active, setActive] = useState<TrainingModuleItem | null>(null);
  const videoRef = useRef<HTMLVideoElement>(null);
  const lastSentAt = useRef(0);

  React.useEffect(() => {
    if (data && !active) {
      setActive(data.modules.find((m: TrainingModuleItem) => !m.isCompleted) ?? data.modules[0] ?? null);
    }
  }, [data, active]);

  const pushProgress = useCallback(
    (force = false) => {
      const el = videoRef.current;
      if (!el || !active?.video) return;
      const now = Date.now();
      if (!force && now - lastSentAt.current < 8000) return;
      lastSentAt.current = now;

      recordVideoProgress.mutate({
        moduleId: active.id,
        payload: {
          watchTimeSec: Math.round(el.currentTime),
          lastPositionSec: Math.round(el.currentTime),
          durationSec: Math.round(el.duration || active.video.durationSec),
        },
      });
    },
    [active, recordVideoProgress]
  );

  if (isLoading) {
    return <div className="p-6 text-xs font-medium text-muted-foreground">Loading training…</div>;
  }
  if (!data || data.modules.length === 0) {
    return (
      <div className="p-6 text-xs font-medium text-muted-foreground">
        No training modules have been published yet.
      </div>
    );
  }

  const pct = data.progress
    ? Math.round((data.progress.completedMandatory / Math.max(data.progress.totalMandatory, 1)) * 100)
    : 0;

  return (
    <div className="max-w-6xl mx-auto p-6 space-y-5">
      <div className="space-y-2">
        <div className="flex items-center justify-between">
          <h1 className="text-sm font-black uppercase tracking-widest text-foreground">Training</h1>
          <span className="text-[11px] font-bold text-muted-foreground">
            {data.progress?.completedMandatory ?? 0} / {data.progress?.totalMandatory ?? 0} modules
          </span>
        </div>
        <div className="h-1.5 w-full rounded-full bg-muted/40 overflow-hidden">
          <div
            className="h-full rounded-full bg-primary transition-all duration-500"
            style={{ width: `${pct}%` }}
          />
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        <div className="lg:col-span-2 space-y-3">
          {active && (
            <>
              {active.video ? (
                <video
                  ref={videoRef}
                  key={active.id}
                  src={active.video.url}
                  controls
                  className="w-full rounded-xl border border-border/40 bg-black aspect-video"
                  onTimeUpdate={() => pushProgress(false)}
                  onPause={() => pushProgress(true)}
                  onSeeked={() => pushProgress(true)}
                  onEnded={() => pushProgress(true)}
                  onLoadedMetadata={(e) => {
                    const start = active.video?.progress?.lastPositionSec ?? 0;
                    if (start > 0 && start < (e.currentTarget.duration || Infinity)) {
                      e.currentTarget.currentTime = start;
                    }
                  }}
                />
              ) : active.pdfUrl ? (
                <div className="rounded-xl border border-border/40 overflow-hidden bg-muted/10">
                  <iframe src={active.pdfUrl} className="w-full h-[520px]" title={active.title} />
                </div>
              ) : null}

              <div className="flex items-start justify-between gap-3">
                <div>
                  <h2 className="text-sm font-bold text-foreground">{active.title}</h2>
                  {active.description && (
                    <p className="text-xs text-muted-foreground mt-1">{active.description}</p>
                  )}
                </div>
                {!active.video && !active.isCompleted && (
                  <Button
                    onClick={() => markComplete.mutate(active.id)}
                    disabled={markComplete.isPending}
                    className="h-8 shrink-0 rounded-md text-[11px] font-bold uppercase tracking-wider cursor-pointer"
                  >
                    Mark as read
                  </Button>
                )}
                {active.isCompleted && (
                  <span className="inline-flex items-center gap-1 px-2 py-1 text-[10px] font-bold rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/10 shrink-0">
                    <CheckCircle2 className="h-3 w-3" /> Completed
                  </span>
                )}
              </div>
            </>
          )}
        </div>

        <div className="space-y-1.5">
          {data.modules.map((m: any) => {
            const isActive = active?.id === m.id;
            return (
              <button
                key={m.id}
                onClick={() => setActive(m)}
                className={cn(
                  'w-full flex items-center gap-2.5 rounded-lg border p-2.5 text-left transition-colors',
                  isActive
                    ? 'border-primary/40 bg-primary/5'
                    : 'border-border/40 bg-surface hover:bg-muted/20'
                )}
              >
                {m.isCompleted ? (
                  <CheckCircle2 className="h-4 w-4 shrink-0 text-emerald-500" />
                ) : m.video ? (
                  <PlayCircle className="h-4 w-4 shrink-0 text-muted-foreground/50" />
                ) : (
                  <FileText className="h-4 w-4 shrink-0 text-muted-foreground/50" />
                )}
                <div className="min-w-0 flex-1">
                  <div className="text-xs font-semibold text-foreground truncate">{m.title}</div>
                  <div className="text-[10px] text-muted-foreground/70">
                    {m.isMandatory ? 'Mandatory' : 'Optional'}
                  </div>
                </div>
              </button>
            );
          })}

          {data.progress?.isCompleted && (
            <div className="mt-3 flex items-center gap-2 rounded-lg border border-emerald-500/20 bg-emerald-500/5 p-2.5 text-[11px] font-bold text-emerald-600">
              <CheckCircle2 className="h-3.5 w-3.5" /> Training complete — MCQ assessment unlocked
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
