'use client';

import Link from 'next/link';
import { useState } from 'react';
import { notFound } from 'next/navigation';
import { useMutation, useQuery } from '@tanstack/react-query';
import { Icons } from '@/components/icons';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { ContentApprovalStatusBadge } from '@/features/content-approval/components/content-approval-status-badge';
import { ContentReviewActionDialog } from '@/features/content-approval/components/content-review-action-dialog';
import { canEditContent, canTransitionContent } from '@/features/content-approval/lib/workflow';
import { formatDate } from '@/lib/format';
import { updateOnlineLessonStateMutation } from '../api/mutations';
import { onlineLessonByIdOptions } from '../api/queries';
import { getOnlineLessonCategoryLabel } from '../constants/categories';
import OnlineLessonForm from './online-lesson-form';

function OnlineLessonPlaceholderCover() {
  return (
    <div className='from-muted via-muted/80 to-muted/60 flex h-full w-full flex-col items-center justify-center bg-gradient-to-br'>
      <div className='bg-background/85 mb-4 flex h-20 w-20 items-center justify-center rounded-3xl border shadow-sm'>
        <Icons.video className='text-muted-foreground h-10 w-10' />
      </div>
      <div className='text-muted-foreground text-base font-medium'>บทเรียนออนไลน์</div>
    </div>
  );
}

const YOUTUBE_HOSTS = new Set([
  'youtube.com',
  'www.youtube.com',
  'm.youtube.com',
  'youtu.be',
  'www.youtu.be'
]);

function isValidYouTubeVideoId(value: string) {
  return /^[a-zA-Z0-9_-]{11}$/.test(value);
}

function getYouTubeVideoId(url: URL) {
  const hostname = url.hostname.toLowerCase();

  if (!YOUTUBE_HOSTS.has(hostname)) {
    return null;
  }

  if (hostname === 'youtu.be' || hostname === 'www.youtu.be') {
    const videoId = url.pathname.split('/').filter(Boolean)[0] ?? '';
    return isValidYouTubeVideoId(videoId) ? videoId : null;
  }

  if (url.pathname === '/watch') {
    const videoId = url.searchParams.get('v') ?? '';
    return isValidYouTubeVideoId(videoId) ? videoId : null;
  }

  const pathSegments = url.pathname.split('/').filter(Boolean);
  const videoId =
    pathSegments[0] === 'shorts' || pathSegments[0] === 'embed' ? (pathSegments[1] ?? '') : '';

  return isValidYouTubeVideoId(videoId) ? videoId : null;
}

function getEmbeddableVideoUrl(value: string) {
  try {
    const url = new URL(value);
    const videoId = getYouTubeVideoId(url);
    return videoId ? `https://www.youtube.com/embed/${videoId}` : null;
  } catch {
    return null;
  }
}

export default function OnlineLessonDetailPage({
  lessonId,
  currentUserId,
  permissions,
  canViewInternalReviewData
}: {
  lessonId: number;
  currentUserId: string;
  permissions: readonly string[];
  canViewInternalReviewData: boolean;
}) {
  const [reviewAction, setReviewAction] = useState<'approve' | 'return' | 'reject' | null>(null);
  const { data, error, isPending } = useQuery(onlineLessonByIdOptions(lessonId));
  const stateMutation = useMutation(updateOnlineLessonStateMutation);

  if (isPending) {
    return (
      <Card className='border-dashed'>
        <CardContent className='flex flex-col items-center justify-center gap-4 py-12 text-center'>
          <Icons.spinner className='text-muted-foreground h-6 w-6 animate-spin' />
          <p className='text-muted-foreground text-sm'>กำลังโหลดรายละเอียดบทเรียนออนไลน์</p>
        </CardContent>
      </Card>
    );
  }

  if (error) {
    if (error.message.includes('ไม่พบบทเรียนออนไลน์')) {
      notFound();
    }

    return (
      <Alert variant='destructive'>
        <Icons.warning className='h-4 w-4' />
        <AlertTitle>ไม่สามารถโหลดรายละเอียดบทเรียนได้</AlertTitle>
        <AlertDescription>{error.message}</AlertDescription>
      </Alert>
    );
  }

  if (!data?.online_lesson) {
    notFound();
  }

  const lesson = data.online_lesson;
  const isOwner = lesson.created_by === currentUserId;
  const canEdit = canEditContent({
    module: 'online_lesson',
    permissions,
    status: lesson.status,
    isOwner
  });

  if (canEdit) {
    return (
      <OnlineLessonForm
        initialData={lesson}
        currentUserId={currentUserId}
        permissions={permissions}
      />
    );
  }

  const canApprove = canTransitionContent({
    module: 'online_lesson',
    action: 'approve',
    currentStatus: lesson.status,
    permissions,
    isOwner
  });
  const canReturn = canTransitionContent({
    module: 'online_lesson',
    action: 'return',
    currentStatus: lesson.status,
    permissions,
    isOwner
  });
  const canReject = canTransitionContent({
    module: 'online_lesson',
    action: 'reject',
    currentStatus: lesson.status,
    permissions,
    isOwner
  });
  const canPublish = canTransitionContent({
    module: 'online_lesson',
    action: 'publish',
    currentStatus: lesson.status,
    permissions,
    isOwner
  });
  const canArchive = canTransitionContent({
    module: 'online_lesson',
    action: 'archive',
    currentStatus: lesson.status,
    permissions,
    isOwner
  });

  const embedUrl = lesson.video_url ? getEmbeddableVideoUrl(lesson.video_url) : null;
  const attachmentViewUrl = `/api/online-lessons/${lesson.id}/attachment/view`;
  const attachmentDownloadUrl = `/api/online-lessons/${lesson.id}/attachment/download`;

  return (
    <>
      <ContentReviewActionDialog
        open={reviewAction !== null}
        onOpenChange={(open) => {
          if (!open) {
            setReviewAction(null);
          }
        }}
        action={reviewAction}
        module='online_lesson'
        contentTitle={lesson.title}
        isSubmitting={stateMutation.isPending}
        onConfirm={(values) => {
          stateMutation.mutate({ id: lesson.id, values });
          setReviewAction(null);
        }}
      />

      <div className='space-y-6'>
        <Card className='overflow-hidden'>
          <div className='bg-muted flex aspect-[16/6] items-center justify-center overflow-hidden'>
            {lesson.thumbnail_url ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img src={lesson.thumbnail_url} alt={lesson.title} className='h-full w-full object-cover' />
            ) : (
              <OnlineLessonPlaceholderCover />
            )}
          </div>
          <CardHeader className='space-y-4'>
            <div className='flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between'>
              <div className='space-y-2'>
                <div className='flex flex-wrap items-center gap-2'>
                  <CardTitle className='text-2xl'>{lesson.title}</CardTitle>
                  <ContentApprovalStatusBadge status={lesson.status} />
                </div>
                <CardDescription className='flex flex-wrap items-center gap-x-4 gap-y-1'>
                  <span>หมวดหมู่ {getOnlineLessonCategoryLabel(lesson.category)}</span>
                  <span>เผยแพร่ {lesson.published_at ? formatDate(lesson.published_at) : 'ยังไม่เผยแพร่'}</span>
                  {canViewInternalReviewData ? (
                    <span>สร้างโดย {lesson.created_by_name || '-'}</span>
                  ) : null}
                </CardDescription>
              </div>

              {canApprove || canReturn || canReject || canPublish || canArchive ? (
                <div className='flex flex-wrap gap-2'>
                  {canApprove ? (
                    <Button onClick={() => setReviewAction('approve')} disabled={stateMutation.isPending}>
                      อนุมัติ
                    </Button>
                  ) : null}
                  {canReturn ? (
                    <Button
                      variant='outline'
                      onClick={() => setReviewAction('return')}
                      disabled={stateMutation.isPending}
                    >
                      ส่งกลับ
                    </Button>
                  ) : null}
                  {canReject ? (
                    <Button
                      variant='outline'
                      onClick={() => setReviewAction('reject')}
                      disabled={stateMutation.isPending}
                    >
                      ไม่อนุมัติ
                    </Button>
                  ) : null}
                  {canPublish ? (
                    <Button
                      onClick={() => stateMutation.mutate({ id: lesson.id, values: { action: 'publish' } })}
                      disabled={stateMutation.isPending}
                    >
                      เผยแพร่
                    </Button>
                  ) : null}
                  {canArchive ? (
                    <Button
                      variant='outline'
                      onClick={() => stateMutation.mutate({ id: lesson.id, values: { action: 'archive' } })}
                      disabled={stateMutation.isPending}
                    >
                      เก็บถาวร
                    </Button>
                  ) : null}
                </div>
              ) : null}
            </div>
          </CardHeader>
          <CardContent className='space-y-6'>
            <div className='space-y-2'>
              <h3 className='text-lg font-semibold'>รายละเอียดบทเรียน</h3>
              <p className='text-muted-foreground whitespace-pre-wrap text-sm'>
                {lesson.description || 'ไม่มีรายละเอียดเพิ่มเติม'}
              </p>
            </div>

            {canViewInternalReviewData && lesson.review_comment ? (
              <div className='rounded-lg border border-dashed p-4'>
                <div className='mb-2 text-sm font-medium'>หมายเหตุการตรวจสอบ</div>
                <div className='text-muted-foreground whitespace-pre-wrap text-sm'>
                  {lesson.review_comment}
                </div>
              </div>
            ) : null}

            <div className='mx-auto w-full max-w-4xl space-y-3'>
              <h3 className='text-lg font-semibold'>วิดีโอ</h3>
              {lesson.video_file_url ? (
                <video
                  controls
                  aria-label={`วิดีโอบทเรียน ${lesson.title}`}
                  className='w-full rounded-xl border'
                >
                  <source src={lesson.video_file_url} />
                  <track kind='captions' />
                </video>
              ) : embedUrl ? (
                <div className='aspect-video overflow-hidden rounded-xl border'>
                  {/* eslint-disable-next-line react/iframe-missing-sandbox */}
                  <iframe
                    src={embedUrl}
                    title={lesson.title}
                    className='h-full w-full'
                    allow='accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share'
                    allowFullScreen
                    referrerPolicy='strict-origin-when-cross-origin'
                  />
                </div>
              ) : lesson.video_url ? (
                <Card className='border-dashed'>
                  <CardContent className='flex flex-col items-center gap-3 py-8 text-center'>
                    <Icons.externalLink className='text-muted-foreground h-6 w-6' />
                    <p className='text-muted-foreground text-sm'>
                      วิดีโอนี้ไม่รองรับการ embed ในระบบ สามารถเปิดผ่านลิงก์ภายนอกได้
                    </p>
                    <Button asChild>
                      <Link href={lesson.video_url} target='_blank' rel='noreferrer'>
                        เปิดวิดีโอ
                      </Link>
                    </Button>
                  </CardContent>
                </Card>
              ) : (
                <div className='text-muted-foreground rounded-lg border border-dashed px-4 py-8 text-center text-sm'>
                  ไม่มีวิดีโอสำหรับบทเรียนนี้
                </div>
              )}
            </div>

            <div className='space-y-3'>
              <h3 className='text-lg font-semibold'>เอกสารประกอบ</h3>
              {lesson.attachment_url ? (
                <div className='rounded-lg border p-4'>
                  <div className='mb-3 flex min-w-0 items-center gap-2 text-sm'>
                    <Icons.paperclip className='text-muted-foreground h-4 w-4 shrink-0' />
                    <span className='truncate font-medium'>{lesson.attachment_name || 'ไฟล์แนบ'}</span>
                  </div>
                  <div className='flex flex-wrap gap-2'>
                    <Button asChild variant='outline'>
                      <a href={attachmentViewUrl} target='_blank' rel='noopener noreferrer'>
                        เปิดไฟล์
                      </a>
                    </Button>
                    <Button asChild>
                      <a href={attachmentDownloadUrl}>ดาวน์โหลด</a>
                    </Button>
                  </div>
                </div>
              ) : (
                <div className='text-muted-foreground rounded-lg border border-dashed px-4 py-8 text-center text-sm'>
                  ไม่มีไฟล์แนบ
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      </div>
    </>
  );
}
