'use client';

import { AlertTriangle } from 'lucide-react';

import { PERMISSIONS } from '@/constants/permissions';
import { PermissionGuard } from '@/guards';
import type { TicketAssignmentSummary } from '@/types';
import { formatDate } from '@/utils/date';

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

interface TicketStatusActionsProps {
  ticketId: string;
  assignment?: TicketAssignmentSummary;
}

function OverdueLotAlert({
  lotId,
  dueAt,
}: {
  lotId: number;
  dueAt: string | null;
}) {
  return (
    <div
      role="alert"
      className="flex gap-3 rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-destructive"
    >
      <AlertTriangle className="mt-0.5 size-5 shrink-0" />
      <div className="min-w-0">
        <p className="text-sm font-semibold">Lot {lotId} is overdue</p>
        <p className="mt-0.5 text-xs text-destructive/80">
          The due date expired on {formatDate(dueAt)}.
        </p>
      </div>
    </div>
  );
}

function getTicketAction(
  ticketId: string,
  assignment?: TicketAssignmentSummary,
) {
  if (assignment) {
    return (
      <PermissionGuard
        permissions={PERMISSIONS.TICKET.ASSIGN}
        fallback={
          <PermissionGuard
            permissions={PERMISSIONS.TICKET.WORK}
            fallback={
              <PermissionGuard
                permissions={PERMISSIONS.TICKET.READ}
                fallback={<NoTicketAction />}
              >
                <RequestExtensionAction
                  ticketId={ticketId}
                  assignmentId={assignment.id}
                  dueAt={assignment.due_at}
                  canRequest={false}
                />
              </PermissionGuard>
            }
          >
            <RequestExtensionAction
              ticketId={ticketId}
              assignmentId={assignment.id}
              dueAt={assignment.due_at}
              canRequest={!assignment.is_complete}
            />
          </PermissionGuard>
        }
      >
        <ReviewExtensionRequestAction
          ticketId={ticketId}
          assignmentId={assignment.id}
          canReview={!assignment.is_complete}
        />
      </PermissionGuard>
    );
  }

  return null;
}

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

  return action ? (
    <div className="space-y-3">
      {assignment?.is_overdue ? (
        <OverdueLotAlert lotId={assignment.id} dueAt={assignment.due_at} />
      ) : null}
      {action}
    </div>
  ) : null;
}
