import React, { useState, useCallback } from "react";
import { loadConnectAndInitialize } from "@stripe/connect-js";
import {
  ConnectAccountOnboarding,
  ConnectComponentsProvider,
} from "@stripe/react-connect-js";
import { stripeAPI } from "../services/api";

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

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

  const fetchClientSecret = useCallback(async () => {
    const response = await stripeAPI.createAccountSession();
    return response.data.clientSecret;
  }, []);

  const initializeStripeConnect = useCallback(async () => {
    try {
      const publishableKey = process.env.REACT_APP_STRIPE_PUBLISHABLE_KEY;
      if (!publishableKey) {
        throw new Error("Stripe publishable key not configured");
      }

      const instance = loadConnectAndInitialize({
        publishableKey,
        fetchClientSecret,
        appearance: {
          overlays: "dialog",
          variables: {
            colorPrimary: "#0d6efd",
            colorBackground: "#ffffff",
            colorText: "#212529",
            colorDanger: "#dc3545",
            fontFamily:
              "system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif",
            fontSizeBase: "20px",
            borderRadius: "8px",
            spacingUnit: "4px",
          },
        },
      });

      setStripeConnectInstance(instance);
    } catch (err: any) {
      setError(err.message || "Failed to initialize Stripe");
      setStep("start");
      setLoading(false);
    }
  }, [fetchClientSecret]);

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

    try {
      // Create the Stripe Connected Account
      await stripeAPI.createConnectedAccount();

      // Initialize Stripe Connect for embedded onboarding
      await initializeStripeConnect();

      setStep("onboarding");
      setLoading(false);
    } catch (err: any) {
      setError(
        err.response?.data?.error || err.message || "Failed to set up earnings"
      );
      setStep("start");
      setLoading(false);
    }
  };

  const startOnboardingForExistingAccount = async () => {
    setLoading(true);
    setError(null);

    try {
      await initializeStripeConnect();
      setStep("onboarding");
      setLoading(false);
    } catch (err: any) {
      setError(err.message || "Failed to initialize onboarding");
      setLoading(false);
    }
  };

  // If user already has an account, initialize immediately
  React.useEffect(() => {
    if (hasExistingAccount && step === "onboarding" && !stripeConnectInstance) {
      startOnboardingForExistingAccount();
    }
  }, [hasExistingAccount]);

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

  const handleOnboardingExit = () => {
    onComplete();
  };

  return (
    <div
      className="modal fade show d-block"
      style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
      tabIndex={-1}
    >
      <div
        className={`modal-dialog ${
          step === "onboarding" ? "modal-xl" : "modal-lg"
        }`}
      >
        <div className="modal-content">
          <div className="modal-header">
            <h5 className="modal-title">
              {step === "onboarding"
                ? "Complete Your Earnings Setup"
                : "Start Receiving Earnings"}
            </h5>
            <button
              type="button"
              className="btn-close"
              onClick={onCancel}
              disabled={loading}
            ></button>
          </div>
          <div className="modal-body">
            {step === "start" && (
              <>
                <div className="row text-center mb-4">
                  <div className="col-md-4">
                    <div className="mb-3">
                      <i
                        className="bi bi-lightning text-primary"
                        style={{ fontSize: "2rem" }}
                      ></i>
                    </div>
                    <h6>Quick Setup</h6>
                    <small className="text-muted">Takes about 5 minutes</small>
                  </div>
                  <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 and trusted by millions
                    </small>
                  </div>
                  <div className="col-md-4">
                    <div className="mb-3">
                      <i
                        className="bi bi-bank text-info"
                        style={{ fontSize: "2rem" }}
                      ></i>
                    </div>
                    <h6>Fast Deposits</h6>
                    <small className="text-muted">
                      In your bank in 2-7 business days
                    </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>Verify your identity securely</li>
                    <li>Provide bank account details for deposits</li>
                  </ul>
                </div>

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

            {step === "creating" && (
              <div className="text-center py-5">
                <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 === "onboarding" && (
              <>
                {!stripeConnectInstance ? (
                  <div className="text-center py-5">
                    <div
                      className="spinner-border text-primary mb-3"
                      role="status"
                    >
                      <span className="visually-hidden">Loading...</span>
                    </div>
                    <h5>Loading onboarding form...</h5>
                  </div>
                ) : (
                  <div style={{ minHeight: "500px" }}>
                    <ConnectComponentsProvider
                      connectInstance={stripeConnectInstance}
                    >
                      <ConnectAccountOnboarding onExit={handleOnboardingExit} />
                    </ConnectComponentsProvider>
                  </div>
                )}
                {error && (
                  <div className="alert alert-danger mt-3">
                    <i className="bi bi-exclamation-triangle"></i> {error}
                  </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" && (
              <div className="w-100 text-center">
                <small className="text-muted">
                  Please don't close this window...
                </small>
              </div>
            )}
            {step === "onboarding" && stripeConnectInstance && (
              <div className="w-100">
                <small className="text-muted">
                  <i className="bi bi-lock"></i> Your information is securely
                  processed by Stripe
                </small>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default StripeConnectOnboarding;
