"use client";

import { useState, type ReactNode } from "react";

import CheckRoundedIcon from "@mui/icons-material/CheckRounded";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import type { SxProps, Theme } from "@mui/material/styles";

import { AlertDialog } from "@/components/ui/alert-dialog";
import { AppButton } from "@/components/ui/button";
import {
  arrowReloadIcon as ArrowReloadIcon,
  sharedWithPSWGIcon as SharedWithPSWGIcon,
} from "@/components/ui/icon";

const actionButtonSx: SxProps<Theme> = {
  height: 44,
  minHeight: 44,
  px: 1.5,
  bgcolor: "#1a64a8",
  color: "#ffffff",
  "& .MuiButton-startIcon": { m: 0, mr: 1 },
  "&:hover": { bgcolor: "#155489", boxShadow: "none" },
  "&.Mui-disabled": {
    bgcolor: "#bdbdbd",
    color: "#ffffff",
  },
};

export type WorkflowActionButtonsProps = {
  showShare?: boolean;
  showSubmit?: boolean;
  showSaveDraft?: boolean;
  canShare?: boolean;
  canSubmit?: boolean;
  canSaveDraft?: boolean;
  isUpdating?: boolean;
  shareLabel?: string;
  submitLabel?: string;
  saveDraftLabel?: string;
  confirmLabel?: string;
  cancelLabel?: string;
  actionErrorMessage?: string;
  shareDialogTitle?: string;
  shareDialogDescription?: ReactNode;
  submitDialogTitle?: string;
  submitDialogDescription?: ReactNode;
  onShare?: () => void | Promise<void>;
  onSubmit?: () => void | Promise<void>;
  onSaveDraft?: () => void | Promise<void>;
};

function getActionErrorMessage(error: unknown, fallbackMessage: string) {
  return error instanceof Error ? error.message : fallbackMessage;
}

export function WorkflowActionButtons({
  showShare = true,
  showSubmit = true,
  showSaveDraft = true,
  canShare = false,
  canSubmit = false,
  canSaveDraft = false,
  isUpdating = false,
  shareLabel = "Share With PSWG",
  submitLabel = "Submit to CDC",
  saveDraftLabel = "Save Draft",
  confirmLabel = "Confirm",
  cancelLabel = "Cancel",
  actionErrorMessage = "Unable to complete this action.",
  shareDialogTitle = "Share with PSWG",
  shareDialogDescription = "Do you want to share this progress report with PSWG?",
  submitDialogTitle = "Submit to CDC",
  submitDialogDescription = "Are you sure you want to submit to CDC?",
  onShare,
  onSubmit,
  onSaveDraft,
}: WorkflowActionButtonsProps) {
  const [shareDialogOpen, setShareDialogOpen] = useState(false);
  const [submitDialogOpen, setSubmitDialogOpen] = useState(false);
  const [shareError, setShareError] = useState<string | null>(null);
  const [submitError, setSubmitError] = useState<string | null>(null);
  const [saveError, setSaveError] = useState<string | null>(null);

  async function handleShareConfirm() {
    if (!onShare) return;
    setShareError(null);

    try {
      await onShare();
      setShareDialogOpen(false);
    } catch (error) {
      setShareError(getActionErrorMessage(error, actionErrorMessage));
    }
  }

  async function handleSubmitConfirm() {
    if (!onSubmit) return;
    setSubmitError(null);

    try {
      await onSubmit();
      setSubmitDialogOpen(false);
    } catch (error) {
      setSubmitError(getActionErrorMessage(error, actionErrorMessage));
    }
  }

  async function handleSaveDraft() {
    if (!onSaveDraft) return;
    setSaveError(null);

    try {
      await onSaveDraft();
    } catch (error) {
      setSaveError(getActionErrorMessage(error, actionErrorMessage));
    }
  }

  if (!showShare && !showSubmit && !showSaveDraft) {
    return null;
  }

  return (
    <>
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          gap: 1.125,
          flexWrap: "wrap",
        }}
      >
        {showShare ? (
          <AppButton
            startIcon={<SharedWithPSWGIcon sx={{ fontSize: 24 }} />}
            disabled={!canShare || isUpdating}
            onClick={() => {
              setShareError(null);
              setShareDialogOpen(true);
            }}
            sx={actionButtonSx}
          >
            {shareLabel}
          </AppButton>
        ) : null}

        {showSubmit ? (
          <AppButton
            startIcon={<CheckRoundedIcon sx={{ fontSize: 24 }} />}
            disabled={!canSubmit || isUpdating}
            onClick={() => {
              setSubmitError(null);
              setSubmitDialogOpen(true);
            }}
            sx={actionButtonSx}
          >
            {submitLabel}
          </AppButton>
        ) : null}

        {showSaveDraft ? (
          <AppButton
            startIcon={<ArrowReloadIcon sx={{ fontSize: 24 }} />}
            disabled={!canSaveDraft || isUpdating}
            onClick={() => void handleSaveDraft()}
            aria-label={saveDraftLabel}
            sx={{
              ...actionButtonSx,
              minWidth: 124,
              bgcolor: "#bdbdbd",
              "&:hover": {
                bgcolor: "#a9a9a9",
                boxShadow: "none",
              },
            }}
          >
            {saveDraftLabel}
          </AppButton>
        ) : null}

        {saveError ? (
          <Typography
            sx={{
              width: "100%",
              color: (theme) =>
                theme.palette.mode === "dark"
                  ? theme.palette.error.light
                  : "#d92d20",
              fontSize: 12,
            }}
          >
            {saveError}
          </Typography>
        ) : null}
      </Box>

      {showShare ? (
        <AlertDialog
          open={shareDialogOpen}
          title={shareDialogTitle}
          description={
            <Box>
              <Box>{shareDialogDescription}</Box>
              {shareError ? (
                <Box
                  sx={{
                    mt: 1,
                    color: (theme) =>
                      theme.palette.mode === "dark"
                        ? theme.palette.error.light
                        : "#d92d20",
                  }}
                >
                  {shareError}
                </Box>
              ) : null}
            </Box>
          }
          confirmLabel={confirmLabel}
          cancelLabel={cancelLabel}
          loading={isUpdating}
          onConfirm={() => void handleShareConfirm()}
          onCancel={() => setShareDialogOpen(false)}
        />
      ) : null}

      {showSubmit ? (
        <AlertDialog
          open={submitDialogOpen}
          title={submitDialogTitle}
          description={
            <Box>
              <Box>{submitDialogDescription}</Box>
              {submitError ? (
                <Box
                  sx={{
                    mt: 1,
                    color: (theme) =>
                      theme.palette.mode === "dark"
                        ? theme.palette.error.light
                        : "#d92d20",
                  }}
                >
                  {submitError}
                </Box>
              ) : null}
            </Box>
          }
          confirmLabel={confirmLabel}
          cancelLabel={cancelLabel}
          loading={isUpdating}
          onConfirm={() => void handleSubmitConfirm()}
          onCancel={() => setSubmitDialogOpen(false)}
        />
      ) : null}
    </>
  );
}
