'use client';

import { AlertModal } from '@/components/modal/alert-modal';
import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger
} from '@/components/ui/dropdown-menu';
import { deleteTrainingRecordMutation } from '../../api/mutations';
import type { TrainingRecord } from '../../api/types';
import { Icons } from '@/components/icons';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { toast } from 'sonner';
import { getBusinessRole } from '@/lib/auth/roles';

interface CellActionProps {
  data: TrainingRecord;
}

function isEditableStatus(status: TrainingRecord['approval_status']) {
  return status === 'draft' || status === 'needs_revision';
}

export function CellAction({ data }: CellActionProps) {
  const [open, setOpen] = useState(false);
  const router = useRouter();
  const { data: session } = useSession();
  const canReview =
    getBusinessRole({
      businessRole: session?.user.businessRole ?? null,
      systemRole: session?.user.systemRole ?? null,
      membershipRole: session?.user.membershipRole ?? null,
      role: session?.user.role ?? null
    }) === 'HRD';
  const canEmployeeManage = isEditableStatus(data.approval_status);
  const canManageRecord = canReview || canEmployeeManage;

  const deleteMutation = useMutation({
    ...deleteTrainingRecordMutation,
    onSuccess: () => {
      toast.success('Training record deleted successfully');
      setOpen(false);
    },
    onError: () => {
      toast.error('Failed to delete training record');
    }
  });

  return (
    <>
      <AlertModal
        isOpen={open}
        onClose={() => setOpen(false)}
        onConfirm={() => deleteMutation.mutate(data.id)}
        loading={deleteMutation.isPending}
      />
      <DropdownMenu modal={false}>
        <DropdownMenuTrigger asChild>
          <Button variant='ghost' className='h-8 w-8 p-0'>
            <span className='sr-only'>Open menu</span>
            <Icons.ellipsis className='h-4 w-4' />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align='end'>
          <DropdownMenuLabel>การจัดการ</DropdownMenuLabel>
          <DropdownMenuItem
            onClick={() => router.push(`/dashboard/training-records/${data.id}`)}
          >
            <Icons.info className='mr-2 h-4 w-4' /> รายละเอียด
          </DropdownMenuItem>
          {canReview && data.approval_status === 'pending' ? (
            <DropdownMenuItem
              onClick={() => router.push(`/dashboard/training-records/${data.id}/review`)}
            >
              <Icons.check className='mr-2 h-4 w-4' /> ตรวจสอบ
            </DropdownMenuItem>
          ) : null}
          {canManageRecord ? (
            <DropdownMenuItem
              onClick={() => router.push(`/dashboard/training-records/${data.id}`)}
            >
              <Icons.edit className='mr-2 h-4 w-4' /> แก้ไข
            </DropdownMenuItem>
          ) : null}
          {canManageRecord ? (
            <DropdownMenuItem onClick={() => setOpen(true)}>
              <Icons.trash className='mr-2 h-4 w-4' /> ลบ
            </DropdownMenuItem>
          ) : null}
        </DropdownMenuContent>
      </DropdownMenu>
    </>
  );
}
