import React from "react";
import AppModal from "@/components/AppModal";
import { Image } from "react-feather";

type RequestHigherPayoutModalProps = {
  isOpen: boolean;
  brandName: string;
  brandLogo?: string;
  currentRate: string | number | null | undefined;
  requestedRate: string;
  onRequestedRateChange: (value: string) => void;
  onClose: () => void;
  onSubmit: () => void;
  isSubmitting?: boolean;
  errorMessage?: string;
  title?: string;
  description?: string;
  currentRateLabel?: string;
  requestedRateLabel?: string;
};

const RequestHigherPayoutModal: React.FC<RequestHigherPayoutModalProps> = ({
  isOpen,
  brandName,
  brandLogo,
  currentRate,
  requestedRate,
  onRequestedRateChange,
  onClose,
  onSubmit,
  isSubmitting = false,
  errorMessage = "",
  title = "Request Higher Payout",
  description = "Looking for a better rate for this brand? Submit your request and our team will review it.",
  currentRateLabel = "Current rate",
  requestedRateLabel = "Requested rate",
}) => {
  const [isErrorDismissed, setIsErrorDismissed] = React.useState(false);
  const prevIsSubmitting = React.useRef(false);

  React.useEffect(() => {
    if (prevIsSubmitting.current && !isSubmitting) {
      // Submission just completed — show error (if any) regardless of message value
      setIsErrorDismissed(false);
    }
    prevIsSubmitting.current = isSubmitting;
  }, [isSubmitting]);

  const isValidNumericInput = (value: string): boolean => {
    if (!value.trim()) return false;

    // Max 3 digits before decimal, max 3 after
    const numericRegex = /^\d{1,3}(\.\d{0,3})?$/;

    return numericRegex.test(value);
  };

  // Display current rate or N/A
  const displayCurrentRate = (): string => {
    if (currentRate === null || currentRate === undefined) {
      return "N/A";
    }

    const rate = Number(currentRate);
    if (!isNaN(rate) && rate >= 0) {
      return rate.toString();
    }

    return "N/A";
  };

  // Handle requested rate change with validation
  const handleRequestedRateChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;

    setIsErrorDismissed(true);

    if (value === "") {
      onRequestedRateChange(value);
      return;
    }

    if (isValidNumericInput(value)) {
      onRequestedRateChange(value);
    }
  };

  // Check if requested rate is a valid number
  const isRequestedRateValid = () => {
    return requestedRate.trim() !== "" && isValidNumericInput(requestedRate);
  };

  return (
    <AppModal
      isOpen={isOpen}
      onClose={onClose}
      isCloseDisabled={isSubmitting}
      contentClassName="rounded-4"
      title={title}
    >
      <div className="mt-3">
        <p className="text-sm fw-400 mb-3">{description}</p>

        <form
          className="modal-form m-0"
          onSubmit={(e) => {
            e.preventDefault();
            onSubmit();
          }}
        >
          <div className="bg-color-light rounded-4 p-3 p-md-4 m-0">
            <div className="brands-card text-center mb-3">
              {brandLogo ? (
                <a className="logos-image">
                  <img
                    className="bg-color-white-same"
                    src={brandLogo}
                    alt={`${brandName} logo`}
                    loading="lazy"
                    onError={(e) => {
                      e.currentTarget.style.display = "none";
                    }}
                  />
                </a>
              ) : (
                <div
                  className="logos-image d-flex align-items-center justify-content-center"
                  style={{
                    minHeight: "80px",
                    backgroundColor: "#f0f0f0",
                    borderRadius: "50%",
                    width: "80px",
                    margin: "0 auto",
                  }}
                >
                  <Image size={40} color="#999" />
                </div>
              )}
              <p className="fw-semibold brands-name mt-2 mb-0">
                {brandName?.toUpperCase() || ""}
              </p>
            </div>

            <div className="row g-2">
              <div className="col-md-6 col-12">
                <label
                  htmlFor="current-rate"
                  className="form-label color-content fw-700"
                >
                  {currentRateLabel}
                </label>
                <input
                  type="text"
                  id="current-rate"
                  name="current-rate"
                  value={displayCurrentRate()}
                  className="form-control form-control-light"
                  readOnly
                  style={{
                    pointerEvents: "none",
                    opacity: 0.7,
                    cursor: "not-allowed",
                  }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.opacity = "0.3";
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.opacity = "0.7";
                  }}
                />
              </div>

              <div className="col-md-6 col-12">
                <label
                  htmlFor="requested-rate"
                  className="form-label color-content fw-700"
                >
                  {requestedRateLabel}
                </label>
                <input
                  type="text"
                  id="requested-rate"
                  name="requested-rate"
                  value={requestedRate}
                  onChange={handleRequestedRateChange}
                  className="form-control form-control-light"
                  placeholder=""
                  disabled={isSubmitting}
                  inputMode="decimal"
                />
              </div>
            </div>
          </div>

          {(!errorMessage || isErrorDismissed) && (
            <div className="d-flex justify-content-center align-items-center gap-2 border-top pt-3 mt-3">
              <button
                type="button"
                className="w-100 button-style btn-outline-second small-btn h-40 m-0"
                onClick={onClose}
                disabled={isSubmitting}
              >
                Cancel
              </button>
              <button
                type="submit"
                className="w-100 button-style btn-first small-btn h-40 m-0"
                disabled={isSubmitting || !isRequestedRateValid()}
              >
                {isSubmitting ? "Submitting..." : "Submit"}
              </button>
            </div>
          )}

          <br />

          {errorMessage && !isErrorDismissed && (
            <div className="alert alert-danger py-2 mb-3 text-center">
              {errorMessage}
            </div>
          )}
        </form>
      </div>
    </AppModal>
  );
};

export default RequestHigherPayoutModal;
