import React from "react";

import InstagramPermissionsModal from "@/components/InstagramPermissionsModal";
import {
  type InstagramConnectionIssue,
  type InstagramMissingPermission,
} from "@/lib/instagramConnection";

type InstagramConnectionDialogsProps = {
  connectUrl: string;
  connectionIssue: InstagramConnectionIssue | null;
  isPermissionsOpen: boolean;
  onCloseIssue: () => void;
  onClosePermissions: () => void;
  onReconnect: () => void;
  permissionsSource: "cta" | "info" | null;
};

function formatMissingPermission(permission: InstagramMissingPermission): string {
  if (permission === "comments") {
    return "Access and manage comments";
  }

  return "Access and manage messages";
}

function getIssueCopy(issue: InstagramConnectionIssue) {
  if (issue.type === "already-connected") {
    return {
      title: "Instagram account is already connected",
      body: "The Instagram account you tried to connect is already linked to another Influential.com, LLC account. Try connecting a different one.",
      reconnectLabel: null,
    };
  }

  if (issue.type === "missing-permissions") {
    return {
      title: "Permissions needed to enable Instagram connection",
      body: "Required Instagram permissions were not granted. Reconnect Instagram and allow the requested access to continue.",
      reconnectLabel: "Reconnect Instagram",
    };
  }

  if (issue.type === "oauth-cancelled") {
    return {
      title: "Instagram connection was cancelled",
      body: "You closed the Instagram permission flow before finishing. Reconnect Instagram when you are ready to continue.",
      reconnectLabel: "Try Again",
    };
  }

  if (issue.type === "oauth-error") {
    return {
      title: "Unable to connect Instagram",
      body: issue.message,
      reconnectLabel: "Try Again",
    };
  }

  return {
    title: "Unable to connect Instagram",
    body: issue.message,
    reconnectLabel: "Try Again",
  };
}

export default function InstagramConnectionDialogs({
  connectUrl,
  connectionIssue,
  isPermissionsOpen,
  onCloseIssue,
  onClosePermissions,
  onReconnect,
  permissionsSource,
}: InstagramConnectionDialogsProps) {
  const issueCopy = connectionIssue ? getIssueCopy(connectionIssue) : null;

  return (
    <>
      <InstagramPermissionsModal
        isOpen={isPermissionsOpen}
        onClose={onClosePermissions}
        proceedUrl={connectUrl}
        source={permissionsSource}
      />

      {connectionIssue && issueCopy && (
        <div
          className="modal fade show d-block"
          tabIndex={-1}
          style={{ backgroundColor: "rgba(0,0,0,0.5)", zIndex: 1050 }}
          onClick={onCloseIssue}
        >
          <div
            className="modal-dialog modal-dialog-centered"
            onClick={(event) => event.stopPropagation()}
          >
            <div className="modal-content rounded-3 shadow position-relative p-4">
              <button
                type="button"
                className="btn-close position-absolute top-0 end-0 m-3"
                onClick={onCloseIssue}
              ></button>

              <div className="modal-body text-center">
                <h5 className="fw-semibold mb-3">{issueCopy.title}</h5>
                <p className="mb-3">{issueCopy.body}</p>

                {connectionIssue.type === "missing-permissions" &&
                  connectionIssue.missingPermissions.length > 0 && (
                    <div className="text-start mb-3">
                      {connectionIssue.missingPermissions.map((permission) => (
                        <p key={permission} className="text-danger mb-1">
                          Missing: {formatMissingPermission(permission)}
                        </p>
                      ))}
                    </div>
                  )}

                {issueCopy.reconnectLabel ? (
                  <button
                    className="button btn-first btn-first-pink w-100 mb-2"
                    onClick={() => {
                      onCloseIssue();
                      onReconnect();
                    }}
                  >
                    {issueCopy.reconnectLabel}
                  </button>
                ) : null}

                <small className="text-muted d-block">
                  If the issue persists, verify the Instagram account and permissions you are granting before reconnecting.
                </small>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}