'use client';

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

import { AssignedContractorAction } from './actions/AssignedContractorAction';
import { ClosedTicketAction } from './actions/ClosedTicketAction';
import { NoTicketAction } from './actions/NoTicketAction';
import { RequestExtensionAction } from './actions/RequestExtensionAction';
import { ReviewExtensionRequestAction } from './actions/ReviewExtensionRequestAction';

interface TicketStatusActionsProps {
  ticket: TicketDetail;
  assignment?: TicketAssignmentSummary;
}

function getTicketAction(
  ticket: TicketDetail,
  assignment?: TicketAssignmentSummary,
) {
  if (assignment && !assignment.is_complete) {
    return (
      <PermissionGuard
        permissions={PERMISSIONS.TICKET.ASSIGN}
        fallback={
          <PermissionGuard
            permissions={PERMISSIONS.TICKET.WORK}
            fallback={<NoTicketAction />}
          >
            <RequestExtensionAction
              ticket={ticket}
              assignmentId={assignment.id}
              dueAt={assignment.due_at}
            />
          </PermissionGuard>
        }
      >
        <>
          {ticket.assignment_status === 'assigned' ? (
            <AssignedContractorAction ticket={ticket} />
          ) : null}
          <ReviewExtensionRequestAction
            ticket={ticket}
            assignmentId={assignment.id}
          />
        </>
      </PermissionGuard>
    );
  }

  if (ticket.assignment_status === 'unassigned') {
    return null;
  }

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

  if (ticket.assignment_status === 'under_review') {
    return null;
  }

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

  return <NoTicketAction />;
}

export function TicketStatusActions({
  ticket,
  assignment,
}: TicketStatusActionsProps) {
  const action = getTicketAction(ticket, assignment);

  return action ? <div className="space-y-3">{action}</div> : null;
}
