'use client';

import { PERMISSIONS } from '@/constants/permissions';
import { PermissionGuard } from '@/guards';
import type { TicketDetail } from '@/types';

import { AssignTicketAction } from './actions/AssignTicketAction';
import { ClosedTicketAction } from './actions/ClosedTicketAction';
import { NoTicketAction } from './actions/NoTicketAction';
import { ReviewExtensionRequestAction } from './actions/ReviewExtensionRequestAction';
import { ReviewRepairAction } from './actions/ReviewRepairAction';
import { SubmitRepairAction } from './actions/SubmitRepairAction';

interface TicketStatusActionsProps {
  ticket: TicketDetail;
}

function getTicketAction(ticket: TicketDetail) {
  if (ticket.assignment_status === 'unassigned') {
    return (
      <PermissionGuard
        permissions={PERMISSIONS.TICKET.ASSIGN}
        fallback={<NoTicketAction />}
      >
        <AssignTicketAction ticket={ticket} />
      </PermissionGuard>
    );
  }

  if (ticket.assignment_status === 'assigned') {
    return (
      <PermissionGuard
        permissions={PERMISSIONS.TICKET.ASSIGN}
        fallback={
          <PermissionGuard
            permissions={PERMISSIONS.TICKET.WORK}
            fallback={<NoTicketAction />}
          >
            <SubmitRepairAction ticket={ticket} />
          </PermissionGuard>
        }
      >
        <ReviewExtensionRequestAction ticket={ticket} />
      </PermissionGuard>
    );
  }

  if (ticket.assignment_status === 'under_review') {
    return (
      <PermissionGuard
        permissions={PERMISSIONS.TICKET.REVIEW}
        fallback={<NoTicketAction />}
      >
        <ReviewRepairAction ticket={ticket} />
      </PermissionGuard>
    );
  }

  if (
    ticket.assignment_status === 'approved' ||
    ticket.assignment_status === 'rejected'
  ) {
    return <ClosedTicketAction ticket={ticket} />;
  }

  return <NoTicketAction />;
}

export function TicketStatusActions({ ticket }: TicketStatusActionsProps) {
  return getTicketAction(ticket);
}
