import React from 'react';
import { notFound } from 'next/navigation';
import { repository } from '@/lib/db/repository';
import { hashTrackingToken } from '@/lib/crypto';
import { YouTubeTracker } from '@/components/YouTubeTracker';
import { ShieldCheck } from 'lucide-react';

interface WatchPageProps {
  params: {
    token: string;
  };
}

export const dynamic = 'force-dynamic';

export default async function WatchPage({ params }: WatchPageProps) {
  const { token } = params;

  if (!token || typeof token !== 'string') {
    notFound();
  }

  const tokenHash = hashTrackingToken(token);
  const assignment = await repository.getAssignmentByTokenHash(tokenHash);

  if (!assignment) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
        <div className="max-w-md w-full bg-white rounded-xl shadow-sm border border-gray-200 p-8 text-center">
          <div className="w-12 h-12 bg-red-100 text-red-600 rounded-full flex items-center justify-center mx-auto mb-4 text-xl font-bold">
            !
          </div>
          <h1 className="text-xl font-bold text-gray-900 mb-2">Invalid Tracking Link</h1>
          <p className="text-sm text-gray-600">
            This tracking link is invalid, does not exist, or has been removed. Please contact your administrator.
          </p>
        </div>
      </div>
    );
  }

  if (!assignment.is_active) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
        <div className="max-w-md w-full bg-white rounded-xl shadow-sm border border-gray-200 p-8 text-center">
          <div className="w-12 h-12 bg-amber-100 text-amber-600 rounded-full flex items-center justify-center mx-auto mb-4 text-xl font-bold">
            !
          </div>
          <h1 className="text-xl font-bold text-gray-900 mb-2">Link Revoked</h1>
          <p className="text-sm text-gray-600">
            This tracking link has been deactivated by the administrator and is no longer available for playback.
          </p>
        </div>
      </div>
    );
  }

  // Retrieve or create active session
  let session = await repository.getActiveSessionForAssignment(assignment.id);
  if (!session || session.status === 'Completed') {
    session = await repository.createWatchSession(assignment.id);
  }

  const video = assignment.video;
  const recipientName = assignment.recipient?.name || 'Viewer';

  return (
    <div className="min-h-screen bg-slate-50 text-slate-800 flex flex-col">
      {/* Top Header — full width */}
      <header className="bg-white border-b border-slate-200 py-3 px-4 sm:px-6">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-2">
            <span className="w-2.5 h-2.5 bg-blue-700 rounded-full" />
            <span className="font-black text-slate-900 text-sm tracking-tight">TRADING BITE</span>
          </div>
          <div className="text-xs text-slate-500">
            Viewer: <span className="font-semibold text-slate-700">{recipientName}</span>
          </div>
        </div>
      </header>

      {/* Main Content — full viewport width */}
      <main className="flex-1 w-full px-3 sm:px-5 py-4">
        <div className="mb-3">
          <h1 className="text-lg sm:text-xl font-bold text-slate-900 tracking-tight leading-snug">
            {video?.title || 'Assigned Video'}
          </h1>
          <p className="text-xs text-slate-500 mt-0.5">
            Assigned to <span className="font-semibold text-slate-700">{recipientName}</span>.
            Real-time playback metrics and watch duration are recorded securely.
          </p>
        </div>

        {/* Video Player & Side Information Panel — full width, no container max-width */}
        <YouTubeTracker
          token={token}
          sessionId={session.id}
          videoId={video?.youtube_video_id || ''}
          videoTitle={video?.title || ''}
          initialTotalWatchSeconds={session.total_watch_seconds}
          initialForegroundWatchSeconds={session.foreground_watch_seconds}
          initialPauseSeconds={session.pause_seconds}
          initialTabInactiveSeconds={session.tab_inactive_seconds}
          initialMutedSeconds={session.muted_seconds}
          initialContentWatchedSeconds={session.content_watched_seconds}
          initialContentIntervals={session.content_intervals || []}
        />

        {/* Privacy Notice */}
        <div className="mt-4 rounded-xl border border-blue-100 bg-blue-50/60 p-3 text-xs text-slate-600">
          <div className="flex items-start space-x-2">
            <ShieldCheck className="w-4 h-4 text-blue-600 mt-0.5 flex-shrink-0" />
            <div>
              <span className="font-semibold text-slate-800">Privacy Notice:</span> Playback activity,
              speed, and accumulated watch duration are recorded securely for verification. No personal
              device identifiers or web history are stored.
            </div>
          </div>
        </div>
      </main>

      {/* Footer */}
      <footer className="border-t border-slate-200 bg-white py-3 text-center text-xs text-slate-400">
        Trading Bite Watch-Time Portal &bull; Official YouTube IFrame Player
      </footer>
    </div>
  );
}
