'use client';

import Link from 'next/link';
import { useState } from 'react';
import { Icons } from '@/components/icons';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger
} from '@/components/ui/dropdown-menu';
import { ContentReviewActionDialog } from '@/features/content-approval/components/content-review-action-dialog';
import {
  canDeleteContent,
  canEditContent,
  canTransitionContent
} from '@/features/content-approval/lib/workflow';
import type { OnlineLesson, OnlineLessonWorkflowActionPayload } from '../api/types';

type OnlineLessonActionMenuProps = {
  lesson: OnlineLesson;
  currentUserId: string;
  permissions: readonly string[];
  isUpdating: boolean;
  isDeleting: boolean;
  onUpdateStatus: (values: { id: number; values: OnlineLessonWorkflowActionPayload }) => void;
  onDelete: (id: number) => void;
};

export function OnlineLessonActionMenu({
  lesson,
  currentUserId,
  permissions,
  isUpdating,
  isDeleting,
  onUpdateStatus,
  onDelete
}: OnlineLessonActionMenuProps) {
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [reviewAction, setReviewAction] = useState<'approve' | 'return' | 'reject' | null>(null);
  const isOwner = lesson.created_by === currentUserId;

  const canEdit = canEditContent({
    module: 'online_lesson',
    permissions,
    status: lesson.status,
    isOwner
  });
  const canDelete = canDeleteContent({
    module: 'online_lesson',
    permissions,
    status: lesson.status,
    isOwner
  });
  const canSubmit = canTransitionContent({
    module: 'online_lesson',
    action: 'submit',
    currentStatus: lesson.status,
    permissions,
    isOwner
  });
  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
  });

  return (
    <>
      <AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>ยืนยันการลบบทเรียน</AlertDialogTitle>
            <AlertDialogDescription>
              บทเรียนนี้จะถูกลบถาวร รวมถึงไฟล์วิดีโอ ไฟล์แนบ และรูปปกที่อัปโหลดไว้
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isDeleting}>ยกเลิก</AlertDialogCancel>
            <AlertDialogAction
              disabled={isDeleting}
              onClick={() => {
                onDelete(lesson.id);
                setDeleteOpen(false);
              }}
            >
              {isDeleting ? 'กำลังลบ...' : 'ยืนยันการลบ'}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

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

      <DropdownMenu modal={false}>
        <DropdownMenuTrigger asChild>
          <Button
            type='button'
            variant='ghost'
            size='icon'
            className='h-8 w-8 shrink-0'
            aria-label='เมนูจัดการบทเรียนออนไลน์'
          >
            <Icons.ellipsis className='h-4 w-4' />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align='end' sideOffset={8} className='w-56 max-w-[calc(100vw-1rem)]'>
          <DropdownMenuLabel>จัดการ</DropdownMenuLabel>
          <DropdownMenuItem asChild>
            <Link href={`/dashboard/online-lessons/${lesson.id}`}>
              <Icons.info className='mr-2 h-4 w-4' />
              ดูข้อมูลบทเรียน
            </Link>
          </DropdownMenuItem>
          {canEdit ? (
            <DropdownMenuItem asChild>
              <Link href={`/dashboard/online-lessons/manage/${lesson.id}`}>
                <Icons.edit className='mr-2 h-4 w-4' />
                แก้ไขบทเรียน
              </Link>
            </DropdownMenuItem>
          ) : null}
          {canSubmit || canApprove || canReturn || canReject || canPublish || canArchive || canDelete ? (
            <DropdownMenuSeparator />
          ) : null}
          {canSubmit ? (
            <DropdownMenuItem
              disabled={isUpdating}
              onClick={() => onUpdateStatus({ id: lesson.id, values: { action: 'submit' } })}
            >
              <Icons.send className='mr-2 h-4 w-4' />
              ส่งตรวจสอบ
            </DropdownMenuItem>
          ) : null}
          {canApprove ? (
            <DropdownMenuItem disabled={isUpdating} onClick={() => setReviewAction('approve')}>
              <Icons.check className='mr-2 h-4 w-4' />
              อนุมัติ
            </DropdownMenuItem>
          ) : null}
          {canReturn ? (
            <DropdownMenuItem disabled={isUpdating} onClick={() => setReviewAction('return')}>
              <Icons.chevronLeft className='mr-2 h-4 w-4' />
              ส่งกลับแก้ไข
            </DropdownMenuItem>
          ) : null}
          {canReject ? (
            <DropdownMenuItem disabled={isUpdating} onClick={() => setReviewAction('reject')}>
              <Icons.close className='mr-2 h-4 w-4' />
              ไม่อนุมัติ
            </DropdownMenuItem>
          ) : null}
          {canPublish ? (
            <DropdownMenuItem
              disabled={isUpdating}
              onClick={() => onUpdateStatus({ id: lesson.id, values: { action: 'publish' } })}
            >
              <Icons.upload className='mr-2 h-4 w-4' />
              เผยแพร่
            </DropdownMenuItem>
          ) : null}
          {canArchive ? (
            <DropdownMenuItem
              disabled={isUpdating}
              onClick={() => onUpdateStatus({ id: lesson.id, values: { action: 'archive' } })}
            >
              <Icons.upload className='mr-2 h-4 w-4 rotate-180' />
              เก็บถาวร
            </DropdownMenuItem>
          ) : null}
          {canDelete ? (
            <DropdownMenuItem
              className='text-destructive focus:text-destructive'
              disabled={isDeleting}
              onClick={() => setDeleteOpen(true)}
            >
              <Icons.trash className='mr-2 h-4 w-4' />
              ลบบทเรียน
            </DropdownMenuItem>
          ) : null}
        </DropdownMenuContent>
      </DropdownMenu>
    </>
  );
}
