import React, { useState } from "react";
import { stripeAPI } from "../services/api";

interface StripeConnectOnboardingProps {
  onComplete: () => void;
  onCancel: () => void;
}

const StripeConnectOnboarding: React.FC<StripeConnectOnboardingProps> = ({
  onComplete,
  onCancel,
}) => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [step, setStep] = useState<"start" | "creating" | "redirecting">(
    "start"
  );

  const createStripeAccount = async () => {
    setLoading(true);
    setError(null);
    setStep("creating");

    try {
      // First, create the Stripe Connected Account
      const accountResponse = await stripeAPI.createConnectedAccount();

      setStep("redirecting");

      // Generate onboarding link
      const refreshUrl = `${window.location.origin}/earnings?refresh=true`;
      const returnUrl = `${window.location.origin}/earnings?setup=complete`;

      const linkResponse = await stripeAPI.createAccountLink({
        refreshUrl,
        returnUrl,
      });

      const { url } = linkResponse.data;

      // Redirect to Stripe onboarding
      window.location.href = url;
    } catch (err: any) {
      setError(
        err.response?.data?.error || err.message || "Failed to set up earnings"
      );
      setStep("start");
      setLoading(false);
    }
  };

  const handleStartSetup = () => {
    createStripeAccount();
  };

  return (
    <div
      className="modal fade show d-block"
      style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
      tabIndex={-1}
    >
      <div className="modal-dialog modal-lg">
        <div className="modal-content">
          <div className="modal-header">
            <h5 className="modal-title">Set Up Earnings</h5>
            <button
              type="button"
              className="btn-close"
              onClick={onCancel}
              disabled={loading}
            ></button>
          </div>
          <div className="modal-body">
            {step === "start" && (
              <>
                <div className="text-center mb-4">
                  <div className="text-primary mb-3">
                    <i
                      className="bi bi-cash-coin"
                      style={{ fontSize: "3rem" }}
                    ></i>
                  </div>
                  <h4>Start Receiving Earnings</h4>
                  <p className="text-muted">
                    Set up your earnings account to automatically receive
                    payments
                  </p>
                </div>

                <div className="row text-center mb-4">
                  <div className="col-md-4">
                    <div className="mb-3">
                      <i
                        className="bi bi-shield-check text-success"
                        style={{ fontSize: "2rem" }}
                      ></i>
                    </div>
                    <h6>Secure</h6>
                    <small className="text-muted">
                      Powered by Stripe, trusted by millions
                    </small>
                  </div>
                  <div className="col-md-4">
                    <div className="mb-3">
                      <i
                        className="bi bi-clock text-primary"
                        style={{ fontSize: "2rem" }}
                      ></i>
                    </div>
                    <h6>Automatic</h6>
                    <small className="text-muted">
                      Earnings are processed automatically
                    </small>
                  </div>
                  <div className="col-md-4">
                    <div className="mb-3">
                      <i
                        className="bi bi-bank text-info"
                        style={{ fontSize: "2rem" }}
                      ></i>
                    </div>
                    <h6>Direct Deposit</h6>
                    <small className="text-muted">
                      Funds go directly to your bank
                    </small>
                  </div>
                </div>

                <div className="alert alert-info">
                  <h6>
                    <i className="bi bi-info-circle"></i> What to expect:
                  </h6>
                  <ul className="mb-0">
                    <li>
                      You'll be redirected to Stripe to verify your identity
                    </li>
                    <li>Provide bank account details for deposits</li>
                    <li>The setup process takes about 5 minutes</li>
                    <li>Start earning immediately after setup</li>
                  </ul>
                </div>

                {error && (
                  <div className="alert alert-danger">
                    <i className="bi bi-exclamation-triangle"></i> {error}
                  </div>
                )}
              </>
            )}

            {step === "creating" && (
              <div className="text-center">
                <div className="spinner-border text-primary mb-3" role="status">
                  <span className="visually-hidden">Loading...</span>
                </div>
                <h5>Creating your earnings account...</h5>
                <p className="text-muted">
                  Please wait while we set up your account
                </p>
              </div>
            )}

            {step === "redirecting" && (
              <div className="text-center">
                <div className="spinner-border text-success mb-3" role="status">
                  <span className="visually-hidden">Loading...</span>
                </div>
                <h5>Redirecting to Stripe...</h5>
                <p className="text-muted">
                  You'll be redirected to complete the setup process. This may
                  take a moment.
                </p>
              </div>
            )}
          </div>
          <div className="modal-footer">
            {step === "start" && (
              <>
                <button
                  type="button"
                  className="btn btn-secondary"
                  onClick={onCancel}
                  disabled={loading}
                >
                  Cancel
                </button>
                <button
                  type="button"
                  className="btn btn-primary"
                  onClick={handleStartSetup}
                  disabled={loading}
                >
                  Set Up Earnings
                </button>
              </>
            )}
            {(step === "creating" || step === "redirecting") && (
              <div className="w-100 text-center">
                <small className="text-muted">
                  Please don't close this window...
                </small>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default StripeConnectOnboarding;
