import { useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useAuth } from "../../contexts/AuthContext";
import {
  createCheckoutSession,
  activateFreeTier,
} from "../../api/stripe";
import Input from "../../components/Input";
import Button from "../../components/Button";
import TierPicker from "../../components/TierPicker";
import "./Subscribe.css";

const STEPS = ["Create Account", "Verify Email", "Choose Plan"];

export default function Subscribe() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { currentUser, signup, sendEmailVerification, reloadUser, refreshAccount } = useAuth();

  const queryParameters = new URLSearchParams(window.location.search)
  const success = queryParameters?.get("payment")
  const session_id = queryParameters?.get("session_id")

  console.log('success, session_id ------>', success, session_id)

  function forward(success, session_id) {
    success && session_id ?
      navigate('/addresses') : console.log('ewps')
  }

  setTimeout(forward, 2000, success, session_id);

  const [step, setStep] = useState(
    currentUser ? (currentUser.emailVerified ? 3 : 2) : 1
  );
  const [verificationSent, setVerificationSent] = useState(false);
  const [data, setData] = useState({
    email: currentUser?.email || "",
    password: "",
    confirmPassword: "",
    selectedTier: null,
  });
  const [error, setError] = useState(
    searchParams.get("payment") === "cancelled"
      ? "Payment was cancelled. Please try again."
      : ""
  );
  const [loading, setLoading] = useState(false);

  function set(field, value) {
    setData((prev) => ({ ...prev, [field]: value }));
  }

  async function handleStep1() {
    setError("");
    if (!data.email || !data.password) {
      setError("Email and password are required");
      return;
    }
    if (data.password.length < 6) {
      setError("Password must be at least 6 characters");
      return;
    }
    if (data.password !== data.confirmPassword) {
      setError("Passwords do not match");
      return;
    }
    setLoading(true);
    try {
      await signup(data.email, data.password);
      await sendEmailVerification();
      setVerificationSent(true);
      setStep(2);
    } catch (err) {
      setError(err.message || "Failed to create account");
    } finally {
      setLoading(false);
    }
  }

  async function handleStep2() {
    setError("");
    setLoading(true);
    try {
      const user = await reloadUser();
      if (user?.emailVerified) {
        setStep(3);
      } else {
        setError("Email not yet verified. Please check your inbox and click the verification link.");
      }
    } catch (err) {
      setError(err.message || "Failed to check verification status");
    } finally {
      setLoading(false);
    }
  }

  async function handleResendVerification() {
    setError("");
    setLoading(true);
    try {
      await sendEmailVerification();
      setVerificationSent(true);
      setError("");
    } catch (err) {
      if (err.code === "auth/too-many-requests") {
        setError("Too many requests. Please wait a moment before trying again.");
      } else {
        setError(err.message || "Failed to resend verification email");
      }
    } finally {
      setLoading(false);
    }
  }

  async function handleStep3() {
    setError("");
    if (!data.selectedTier) {
      setError("Please select a plan");
      return;
    }
    setLoading(true);
    try {
      if (data.selectedTier === "free") {
        await activateFreeTier();
        await refreshAccount();
        navigate("/addresses", { replace: true });
      } else {
        const { url } = await createCheckoutSession(data.selectedTier);
        window.location.href = url;
      }
    } catch (err) {
      setError(err.message || "Something went wrong");
      setLoading(false);
    }
  }

  function ProgressBar() {
    return (
      <div className="progress-bar">
        {STEPS.map((label, i) => {
          const stepNum = i + 1;
          const done = step > stepNum;
          const active = step === stepNum;
          const dotClass = done
            ? "progress-bar__dot--done"
            : active
              ? "progress-bar__dot--active"
              : "progress-bar__dot--pending";

          return (
            <div key={label} className="progress-bar__step">
              {i > 0 && (
                <div
                  className={`progress-bar__connector ${done || active
                    ? "progress-bar__connector--active"
                    : "progress-bar__connector--inactive"
                    }`}
                />
              )}
              <div>
                <div className={`progress-bar__dot ${dotClass}`}>
                  {done ? "\u2713" : stepNum}
                </div>
                <div
                  className={`progress-bar__label ${active
                    ? "progress-bar__label--active"
                    : "progress-bar__label--inactive"
                    }`}
                >
                  {label}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    );
  }

  // ── Step content ──────────────────────────────────────────────────────────

  function StepCreateAccount() {
    return (
      <>
        <h2 className="mb-lg">Create your account</h2>
        <Input
          label="Email"
          type="email"
          value={data.email}
          onChange={(v) => set("email", v)}
          disabled={loading}
          placeholder="you@example.com"
        />
        <Input
          label="Password"
          type="password"
          value={data.password}
          onChange={(v) => set("password", v)}
          disabled={loading}
          placeholder="At least 6 characters"
        />
        <Input
          label="Confirm Password"
          type="password"
          value={data.confirmPassword}
          onChange={(v) => set("confirmPassword", v)}
          disabled={loading}
          placeholder="Repeat your password"
          className="form-field--last"
        />
      </>
    );
  }

  function StepVerifyEmail() {
    return (
      <>
        <h2 className="mb-sm">Verify your email</h2>
        <p className="subscribe__subtitle">
          We've sent a verification link to <strong>{currentUser?.email}</strong>.
          Please check your inbox and click the link to verify your email address.
        </p>
        {verificationSent && !error && (
          <p className="subscribe__verify-sent">Verification email sent!</p>
        )}
        <div className="subscribe__verify-actions">
          <Button
            onClick={handleResendVerification}
            disabled={loading}
            variant="ghost"
          >
            {loading ? "Sending..." : "Resend verification email"}
          </Button>
        </div>
      </>
    );
  }

  function StepChoosePlan() {
    return (
      <>
        <h2 className="mb-sm">Choose your monitoring plan</h2>
        <p className="subscribe__subtitle">
          Select the plan that works best for you. You can upgrade anytime.
        </p>
        <TierPicker
          onSelect={(tier) => set("selectedTier", tier)}
          selectedTier={data.selectedTier}
        />
      </>
    );
  }

  // ── Footer nav  ──────────────────────────────────────────────────────────

  function Footer() {
    async function handleNext() {
      if (step === 1) handleStep1();
      else if (step === 2) await handleStep2();
      else if (step === 3) await handleStep3();
    }

    function handleBack() {
      setError("");
      setStep((s) => s - 1);
    }

    const nextLabel =
      step === 1
        ? "Create Account"
        : step === 2
          ? "I've verified my email"
          : !data.selectedTier
            ? "Continue"
            : data.selectedTier === "free"
              ? "Start Free Trial"
              : "Subscribe & Continue";

    return (
      <div className="subscribe__footer">
        <div>
          {step > 1 && (
            <Button onClick={handleBack} disabled={loading} variant="ghost">
              ← Back
            </Button>
          )}
        </div>

        <Button
          onClick={handleNext}
          disabled={loading || (step === 3 && !data.selectedTier)}
          className="text-bold"
        >
          {loading ? "Please wait..." : nextLabel}
        </Button>
      </div>
    );
  }

  // ── Render ────────────────────────────────────────────────────────────────

  const stepContent = {
    1: StepCreateAccount(),
    2: StepVerifyEmail(),
    3: StepChoosePlan(),
  };

  return (
    <div className="subscribe">
      <div
        className={`subscribe__container${step === 3 ? " subscribe__container--wide" : ""}`}
      >
        <h1 className="subscribe__title">Koin Ping</h1>

        {ProgressBar()}

        {error && <div className="alert alert--error">{error}</div>}

        <div className="subscribe__card">
          {stepContent[step]}
          {Footer()}
        </div>

        {step === 1 && (
          <p className="subscribe__login-link">
            Already have an account? <a href="/login">Log in here</a>
          </p>
        )}
      </div>
    </div>
  );
}
