"use client";

import { useEffect, useState, useTransition } from "react";
import toast from "react-hot-toast";
import { FaCheck, FaXmark } from "react-icons/fa6";

import Button from "@/components/common/button";
import { useClientPortalAuth } from "@/components/pages/client/participant-list/common/client-portal-auth-context";
import RejectReasonModal from "@/components/pages/client/participant-list/participant-details/partials/reject-reason-modal";
import {
  setParticipantDecisionFromPortal,
  ParticipantDecision,
} from "@/services/client/participant-list/portal-actions";
import { ParticipantStatus } from "@/types/participant-list/provisional-types";

type ActionBarProps = {
  participantReference: string;
  canEdit: boolean;
  currentStatus: ParticipantStatus;
  currentRejectionReason: string | null;
  onDecisionSaved: () => void;
};

function ActionBar({
  participantReference,
  canEdit,
  currentStatus,
  currentRejectionReason,
  onDecisionSaved,
}: ActionBarProps) {
  const { auth, handlePortalStatus } = useClientPortalAuth();
  const [isPending, startTransition] = useTransition();
  const [pendingDecision, setPendingDecision] =
    useState<ParticipantDecision | null>(null);
  const [optimisticDecision, setOptimisticDecision] =
    useState<ParticipantDecision | null>(null);
  const [isRejectModalOpen, setIsRejectModalOpen] = useState(false);
  const activeDecision: ParticipantDecision | null =
    optimisticDecision ??
    (currentStatus === "accepted" || currentStatus === "rejected"
      ? currentStatus
      : null);

  useEffect(() => {
    if (!canEdit) setIsRejectModalOpen(false);
  }, [canEdit]);

  const submitDecision = (decision: ParticipantDecision, reason?: string) => {
    if (!auth || !canEdit || isPending) return;
    setPendingDecision(decision);
    startTransition(async () => {
      try {
        const result = await setParticipantDecisionFromPortal(
          auth,
          participantReference,
          decision,
          { reason },
        );
        if (result.ok) {
          toast.success(
            decision === "accepted"
              ? "Participant accepted."
              : "Participant rejected.",
          );
          setOptimisticDecision(decision);
          setIsRejectModalOpen(false);
          onDecisionSaved();
        } else if (!handlePortalStatus(result.status)) {
          toast.error("Could not update decision. Please try again.");
        }
      } catch {
        toast.error("Could not update decision. Please try again.");
      } finally {
        setPendingDecision(null);
      }
    });
  };

  const handleAccept = () => {
    if (!canEdit || isPending) return;
    submitDecision("accepted");
  };

  const handleRejectClick = () => {
    if (!canEdit || isPending) return;
    setIsRejectModalOpen(true);
  };

  const acceptSelected = activeDecision === "accepted";
  const rejectSelected = activeDecision === "rejected";

  return (
    <>
      <div className="sticky bottom-0 bg-white dark:bg-neutral-900 border-t border-gray-200 dark:border-neutral-700 px-4 py-3 z-50">
        <div className="mx-auto max-w-4xl space-y-2">
          <p className="text-[11px] font-semibold uppercase tracking-widest text-gray-400 dark:text-gray-300">
            {canEdit ? "Your decision" : "Your decision (view only)"}
          </p>
          <div className="grid grid-cols-2 gap-3">
            <Button
              fullWidth
              aria-pressed={acceptSelected}
              btnLabel="Accept"
              color={acceptSelected ? "success" : "default"}
              isDisabled={!canEdit || isPending}
              isLoading={pendingDecision === "accepted"}
              startContent={<FaCheck className="size-3" />}
              variant={acceptSelected ? "solid" : "bordered"}
              onClick={handleAccept}
            />
            <Button
              fullWidth
              aria-pressed={rejectSelected}
              btnLabel="Reject"
              color={rejectSelected ? "danger" : "default"}
              isDisabled={!canEdit || isPending}
              isLoading={pendingDecision === "rejected"}
              startContent={<FaXmark className="size-3" />}
              variant={rejectSelected ? "solid" : "bordered"}
              onClick={handleRejectClick}
            />
          </div>
        </div>
      </div>
      {canEdit && (
        <RejectReasonModal
          initialReason={currentRejectionReason}
          isOpen={isRejectModalOpen}
          isSubmitting={pendingDecision === "rejected"}
          onClose={() => {
            if (pendingDecision === "rejected") return;
            setIsRejectModalOpen(false);
          }}
          onConfirm={(reason) => submitDecision("rejected", reason)}
        />
      )}
    </>
  );
}

export default ActionBar;
