"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { UI, type Lang } from "@/lib/config";
import { signupStorage } from "@/lib/storage";
import { logger } from "@/lib/logger";
import Link from "next/link";
import CheckoutErrorDisplay from "../components/CheckoutErrorDisplay";
import {
  validateCheckoutData,
  CheckoutException,
} from "@/lib/errors/checkout-errors";

interface OnboardingPageProps {
  params: { lang: Lang };
}

const GOALS = [
  {
    id: "reduce_no_shows",
    label: "Reduce No-Shows",
    description:
      "Automated reminders and confirmations to minimize missed appointments",
  },
  {
    id: "automate_reminders",
    label: "Automate Reminders",
    description: "Send automatic appointment reminders via WhatsApp",
  },
  {
    id: "enable_self_booking",
    label: "Enable Self Booking",
    description: "Let customers book appointments 24/7 through WhatsApp",
  },
  {
    id: "improve_communication",
    label: "Improve Communication",
    description: "Better customer engagement with instant WhatsApp responses",
  },
  {
    id: "manage_schedules",
    label: "Manage Schedules",
    description: "Centralized calendar and schedule management",
  },
  {
    id: "reduce_admin_work",
    label: "Reduce Admin Work",
    description: "Automate repetitive tasks and free up staff time",
  },
  {
    id: "collect_feedback",
    label: "Collect Feedback",
    description: "Gather customer reviews and satisfaction data",
  },
  {
    id: "marketing_campaigns",
    label: "Marketing Campaigns",
    description: "Run targeted WhatsApp marketing and promotions",
  },
];

export default function OnboardingPage({ params }: OnboardingPageProps) {
  const { lang } = params;
  const dict = UI[lang];
  const router = useRouter();

  const [selectedGoals, setSelectedGoals] = useState<string[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<any>(null);
  const [validationError, setValidationError] = useState<string | null>(null);

  // Get signup context
  const signup = signupStorage.get();
  const plan = signup?.plan;
  const userId = signup?.userId;
  const email = signup?.email;

  // Validate signup context on mount
  useEffect(() => {
    if (!plan || !userId || !email) {
      logger.warn("Missing signup context in onboarding page", {
        hasplan: !!plan,
        hasUserId: !!userId,
        hasEmail: !!email,
      });

      // Set validation error message before redirecting
      const missingItems = [];
      if (!plan) missingItems.push("plan selection");
      if (!userId) missingItems.push("user account");
      if (!email) missingItems.push("email");

      setValidationError(
        `Missing required information: ${missingItems.join(", ")}. Redirecting to signup...`,
      );

      // Redirect after showing error
      const timer = setTimeout(() => {
        router.push(`/${lang}/signup`);
      }, 3000); // Increased to 3 seconds for better visibility

      return () => clearTimeout(timer);
    }
  }, [plan, userId, email, lang, router]);

  // Show validation error if missing context
  if (validationError) {
    return (
      <div
        className={`min-h-screen flex items-center justify-center ${dict.dir === "rtl" ? "rtl" : "ltr"}`}
      >
        <div className="max-w-md mx-auto px-4">
          <div className="rounded-lg border-2 border-yellow-200 bg-yellow-50 p-6">
            <div className="flex items-start gap-3">
              <span className="text-2xl">⚠️</span>
              <div>
                <h3 className="text-lg font-semibold text-yellow-800 mb-2">
                  {dict.t.validationError || "Validation Error"}
                </h3>
                <p className="text-sm text-yellow-700">{validationError}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (!plan || !userId || !email) {
    return null;
  }

  const handleGoalToggle = (goalId: string) => {
    setSelectedGoals((prev) =>
      prev.includes(goalId)
        ? prev.filter((g) => g !== goalId)
        : [...prev, goalId],
    );
    setError(null);
  };

  // Extract submission logic for reusability (fixes retry event issue)
  const performCheckout = async () => {
    setError(null);
    setIsLoading(true);

    try {
      // Validate checkout data before proceeding
      try {
        validateCheckoutData({
          userId,
          email,
          plan: {
            tierId: plan?.tierId,
            billingPeriod: plan?.billingPeriod,
            currency: plan?.currency,
          },
        });
      } catch (validationError) {
        if (validationError instanceof CheckoutException) {
          logger.error("Checkout validation failed", validationError);
          setError({
            error: validationError.error.userMessage,
            errorAr: validationError.error.userMessageAr,
            code: validationError.error.code,
            retryable: validationError.error.retryable,
            recoverySteps: validationError.error.recoverySteps,
            recoveryStepsAr: validationError.error.recoveryStepsAr,
          });
          setIsLoading(false);
          return;
        }
        throw validationError;
      }

      // Track onboarding step and set payment status
      signupStorage.setOnboardingStep(5); // Goals selection is step 5
      signupStorage.setPaymentStatus("in_progress");

      // Save plan data and goals to storage
      if (plan) {
        signupStorage.savePlan({
          tierId: plan.tierId,
          stripePriceId: plan.stripePriceId,
          billingPeriod: plan.billingPeriod,
          currency: plan.currency,
        });
      }
      signupStorage.saveGoals(selectedGoals);

      logger.info("Fetching Stripe price", {
        tierId: plan.tierId,
        billingPeriod: plan.billingPeriod,
        currency: plan.currency,
      });

      // Fetch the real Stripe price ID from database (with currency for proper conversion)
      const priceResponse = await fetch(
        `/api/stripe-price?tier=${plan.tierId}&period=${plan.billingPeriod}&currency=${plan.currency}`,
      );

      if (!priceResponse.ok) {
        const priceError = await priceResponse.json();
        logger.error("Price lookup failed", { error: priceError });

        setError({
          error: priceError.error || "Could not find pricing information",
          errorAr: priceError.errorAr,
          code: priceError.code,
          retryable: priceError.retryable !== false,
          recoverySteps: priceError.recoverySteps,
          recoveryStepsAr: priceError.recoveryStepsAr,
          details: priceError.details,
        });
        setIsLoading(false);
        return;
      }

      const priceData = await priceResponse.json();

      if (!priceData.priceId) {
        throw new Error("Could not find Stripe price for selected plan");
      }

      logger.info("Stripe price found", { priceId: priceData.priceId });

      // Prepare checkout data
      const checkoutData = {
        userId: userId,
        tierId: plan.tierId,
        stripePriceId: priceData.priceId, // Real Stripe price ID from database
        billingPeriod: plan.billingPeriod,
        currency: plan.currency,
        email: email,
        companyName: signup.companyInfo?.companyName || email,
        goals: selectedGoals,
        language: lang, // Pass user's language for correct redirect URL
      };

      logger.info("Creating checkout session", {
        userId: userId,
        tierId: plan.tierId,
      });

      // Create checkout session
      const response = await fetch("/api/signup/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(checkoutData),
      });

      if (!response.ok) {
        const data = await response.json();
        logger.error("Checkout session creation failed", { error: data });

        setError({
          error: data.error || "Failed to create checkout session",
          errorAr: data.errorAr,
          code: data.code,
          retryable: data.retryable !== false,
          recoverySteps: data.recoverySteps,
          recoveryStepsAr: data.recoveryStepsAr,
          details: data.details,
        });

        // Track failed payment attempt
        signupStorage.setPaymentStatus(
          "failed",
          data.error || "Checkout creation failed",
        );

        setIsLoading(false);
        return;
      }

      const { sessionUrl } = await response.json();

      logger.info("Redirecting to Stripe checkout", { sessionUrl });

      // Redirect to Stripe checkout
      window.location.href = sessionUrl;
    } catch (err) {
      const message = err instanceof Error ? err.message : "An error occurred";
      logger.error("Unexpected checkout error", {
        error: message,
        stack: err instanceof Error ? err.stack : undefined,
      });

      // Track failed payment attempt
      signupStorage.setPaymentStatus("failed", message);

      // Set a generic error if we don't have structured error data
      setError({
        error: message,
        retryable: true,
        recoverySteps: [
          "Check your internet connection",
          "Refresh the page",
          "Try again",
          "Contact support if the problem persists",
        ],
        recoveryStepsAr: [
          "تحقق من اتصالك بالإنترنت",
          "قم بتحديث الصفحة",
          "حاول مرة أخرى",
          "اتصل بالدعم إذا استمرت المشكلة",
        ],
      });

      setIsLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    await performCheckout();
  };

  return (
    <div className={`min-h-screen ${dict.dir === "rtl" ? "rtl" : "ltr"}`}>
      <div className="mx-auto max-w-2xl px-4 py-16">
        {/* Progress Indicator */}
        <div className="mb-8">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <div className="flex h-8 w-8 items-center justify-center rounded-full bg-brand-green text-white text-sm font-bold">
                5
              </div>
              <span className="text-sm font-medium text-gray-700">
                {dict.t.selectGoals || "Select Your Goals"}
              </span>
            </div>
            <span className="text-xs text-gray-500">{dict.t.step} 5/7</span>
          </div>
        </div>

        <div className="space-y-8">
          {/* Header */}
          <div>
            <h1 className="mb-2 text-3xl font-bold text-brand-ink">
              {dict.t.selectGoalsTitle || "What would you like to achieve?"}
            </h1>
            <p className="text-gray-600">
              {dict.t.selectGoalsDescription ||
                "Choose the goals that matter most to your clinic. This helps us customize your experience."}
            </p>
          </div>

          {/* Subscription Summary Card */}
          <div className="rounded-lg border border-gray-200 bg-gray-50 p-6">
            <h2 className="mb-4 font-semibold text-brand-ink">
              {dict.t.subscriptionSummary || "Subscription Summary"}
            </h2>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <p className="text-xs text-gray-600 uppercase">
                  {dict.t.plan || "Plan"}
                </p>
                <p className="font-semibold text-brand-ink">{plan.tierId}</p>
              </div>
              <div>
                <p className="text-xs text-gray-600 uppercase">
                  {dict.t.billingCycle || "Billing Cycle"}
                </p>
                <p className="font-semibold text-brand-ink">
                  {plan.billingPeriod === "monthly"
                    ? dict.t.monthly || "Monthly"
                    : dict.t.yearly || "Yearly"}
                </p>
              </div>
              <div>
                <p className="text-xs text-gray-600 uppercase">
                  {dict.t.currency || "Currency"}
                </p>
                <p className="font-semibold text-brand-ink">
                  {plan.currency.toUpperCase()}
                </p>
              </div>
              <div>
                <p className="text-xs text-gray-600 uppercase">
                  {dict.t.setupFee || "Setup Fee"}
                </p>
                <p className="font-semibold text-brand-green">
                  {dict.t.includesSetup || "Included"}
                </p>
              </div>
            </div>
          </div>

          {/* Goals Selection Form */}
          <form onSubmit={handleSubmit} className="space-y-6">
            {/* Validation Error Message (before redirect) */}
            {validationError && (
              <div className="rounded-lg border border-yellow-200 bg-yellow-50 p-4">
                <p className="text-sm text-yellow-700">{validationError}</p>
              </div>
            )}

            {/* Checkout Error Display */}
            {error && (
              <CheckoutErrorDisplay
                error={error}
                lang={lang}
                onRetry={performCheckout}
                onBack={() => router.back()}
              />
            )}

            {/* Goals Checkboxes */}
            <div className="space-y-3">
              {GOALS.map((goal) => (
                <label
                  key={goal.id}
                  className="flex cursor-pointer items-start gap-4 rounded-lg border border-gray-200 p-4 transition-all hover:border-brand-green hover:bg-green-50"
                >
                  <input
                    type="checkbox"
                    checked={selectedGoals.includes(goal.id)}
                    onChange={() => handleGoalToggle(goal.id)}
                    className="mt-1 h-5 w-5 rounded border-gray-300 text-brand-green accent-brand-green flex-shrink-0"
                  />
                  <div className="flex-1">
                    <p className="font-semibold text-brand-ink mb-1">
                      {goal.label}
                    </p>
                    <p className="text-sm text-gray-600">{goal.description}</p>
                  </div>
                </label>
              ))}
            </div>

            {/* Action Buttons */}
            <div className="flex gap-4 pt-4">
              <button
                type="button"
                onClick={() => router.back()}
                disabled={isLoading}
                className="flex-1 rounded-lg border border-gray-300 px-6 py-3 font-medium text-gray-700 transition-all hover:bg-gray-50 disabled:opacity-50"
              >
                {dict.t.back || "Back"}
              </button>
              <button
                type="submit"
                disabled={isLoading}
                className="flex-1 rounded-lg bg-brand-green px-6 py-3 font-medium text-white transition-all hover:bg-green-600 disabled:opacity-50"
              >
                {isLoading ? (
                  <span className="flex items-center justify-center gap-2">
                    <span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                    {dict.t.processingPayment || "Processing..."}
                  </span>
                ) : (
                  `${dict.t.confirmAndPay || "Confirm & Pay"}`
                )}
              </button>
            </div>

            {/* Help Text */}
            <p className="text-center text-xs text-gray-500">
              {dict.t.trialPeriodInfo ||
                "You'll get a 14-day free trial. Payment details required but not charged until trial ends."}
            </p>
          </form>

          {/* Link to Skip */}
          <div className="text-center">
            <Link
              href={`/${lang}/signup/company-info`}
              className="text-sm text-gray-600 underline hover:text-brand-green"
            >
              {dict.t.editCompanyInfo || "Edit company information"}
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
