"use client";

import { useTranslation } from "react-i18next";
import { Lock, LockOpen, Mail, Pencil, RefreshCw, RotateCcw, Trash2 } from "lucide-react";
import ManageActionIcon from "@/components/ui/ManageActionIcon";
import DeletionReviewAction from "../DeletionReviewAction";
import CreatorActionDialogs from "./CreatorActionDialogs";
import { useCreatorActions } from "./useCreatorActions";
import type { VolunteerEventView } from "./volunteerEventView";
import { useAuthStore } from "@/store/authStore";

interface CreatorActionBarProps {
  opportunityId: string;
  view: Pick<
    VolunteerEventView,
    | "isCreator"
    | "canEdit"
    | "canMessage"
    | "isRepostState"
    | "isRejected"
    | "showActionButton"
    | "actionLabelKey"
    | "closedByCreator"
    | "canCloseRegistration"
    | "canReopenRegistration"
    | "canSendCertificates"
    | "certificatesNeedAttendee"
    | "certificatesUpToDate"
    | "certificatesOutdated"
    | "canRequestDeletion"
    | "canRequestDeletionReview"
  >;
  /** Re-read the opportunity after an action changes it. */
  onChanged: () => void;
}

/**
 * The creator's icon rail: Edit / Repost, the registration padlock, resubmit,
 * send certificates, and request deletion — stacked vertically beside the
 * opportunity's details.
 *
 * This file is the rail itself. What each glyph *does* is in
 * `useCreatorActions`, and every confirmation it opens is in
 * `CreatorActionDialogs`. They are unlabelled glyphs, and an unlabelled glyph
 * should never *change* anything on the first tap — Repost in particular reads
 * as "edit" at a glance but creates a second opportunity.
 *
 * Edit is the exception, and deliberately: it only opens a form, which the
 * back button undoes. It was the one control whose dialog asked the reader to
 * confirm a navigation (client, 2026-10-06).
 */
export default function CreatorActionBar({
  opportunityId,
  view,
  onChanged,
}: CreatorActionBarProps) {
  const { t } = useTranslation();
  const publishingPaused = useAuthStore(state => state.user?.is_publishing_paused === true);
  const actions = useCreatorActions(opportunityId, view.isRepostState, onChanged);
  const { setConfirm, messageMutation, openForm } = actions;
  const actionLabel = t(view.actionLabelKey);

  // Every glyph below is an organizer action and every modal belongs to one of
  // them, so a viewer renders none of it. `LearnServeDetails` gates its whole
  // rail the same way; here the check used to be repeated per control, which is
  // why the resubmit glyph leaked to anyone who could open a rejected page.
  if (!view.isCreator) return null;

  return (
    <>
      {/*
        A vertical rail beside the details rather than a row under the title —
        the shape the development page uses, so a creator meets the same layout
        on both. Stacking also keeps each glyph in a stable place as actions
        come and go; a wrapping row reshuffled itself every time registration
        closed or the opportunity completed.

      */}
      <div className="flex flex-col items-center justify-start gap-2 pt-1">
        {view.showActionButton && (
          <ManageActionIcon
            label={actionLabel}
            disabled={view.isRepostState ? publishingPaused : !view.canEdit}
            icon={
              view.isRepostState ? (
                <RotateCcw className="h-5 w-5" />
              ) : (
                <Pencil className="h-5 w-5" />
              )
            }
            /* Edit navigates and nothing else, so it goes straight to the
                form — a confirmation in front of a page change asks the reader
                to agree to something that has not happened yet and that the
                back button already undoes. Repost keeps its dialog: it creates
                a *second* opportunity while wearing almost the same glyph, and
                that is the one this rail genuinely has to guard. */
            onClick={view.isRepostState ? () => setConfirm("primary") : openForm}
          />
        )}

        {/* One padlock, two states: open → click to close; closed → accented,
            click to reopen. The accent replaces the «التسجيل مغلق» pill that
            other viewers see. */}
        {view.canCloseRegistration && (
          <ManageActionIcon
            label={t("COMMON.CLOSE_REGISTRATION")}
            icon={<LockOpen className="h-5 w-5" />}
            onClick={() => setConfirm("close")}
          />
        )}
        {view.canReopenRegistration && (
          <ManageActionIcon
            label={t("COMMON.REOPEN_REGISTRATION")}
            icon={<Lock className="h-5 w-5" />}
            onClick={() => setConfirm("reopen")}
            accent
          />
        )}
        {/* Closed, but past the toggle window — the state still has to be
            readable, so the lock stays as a disabled marker. */}
        {view.closedByCreator && !view.canReopenRegistration && (
          <ManageActionIcon
            label={t("COMMON.REGISTRATION_CLOSED")}
            icon={<Lock className="h-5 w-5" />}
            disabled
            accent
          />
        )}

        {view.isRejected && (
          <ManageActionIcon
            label={t("COMMON.RESUBMIT_WITHOUT_EDIT")}
            icon={<RefreshCw className="h-5 w-5" />}
            onClick={() => setConfirm("resubmit")}
          />
        )}

        {/* Registrant messaging closes at the actual final session end. */}
        <ManageActionIcon
          label={t("COMMON.MESSAGE_REGISTRANTS")}
          icon={<Mail className="h-5 w-5" />}
          onClick={() => setConfirm("message")}
          disabled={messageMutation.isPending || !view.canMessage}
        />
        {/* {view.isCreator && (
          <ManageActionIcon
            label={
              view.certificatesNeedAttendee
                ? t("COMMON.CERTIFICATES_NEED_ATTENDEE")
                : view.certificatesUpToDate
                  ? t("COMMON.CERTIFICATES_UP_TO_DATE")
                  : t("COMMON.SEND_CERTIFICATES")
            }
            icon={<Award className="h-5 w-5" />}
            onClick={() => setConfirm("certificates")}
            disabled={!view.canSendCertificates || certificatesMutation.isPending || view.certificatesNeedAttendee}
          />
        )} */}

        {view.canRequestDeletion && (
          <ManageActionIcon
            label={t("COMMON.DELETE_OPPORTUNITY")}
            disabled={!view.canEdit}
            icon={<Trash2 className="h-5 w-5" />}
            onClick={() => setConfirm("delete")}
            danger
          />
        )}
        {!view.canEdit && <DeletionReviewAction id={opportunityId} type="volunteer" started={view.isRepostState} requestable={view.canRequestDeletionReview} onChanged={onChanged} />}
      </div>

      <CreatorActionDialogs
        opportunityId={opportunityId}
        actions={actions}
        isRepostState={view.isRepostState}
        actionLabel={actionLabel}
        onChanged={onChanged}
      />
    </>
  );
}
