'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { ShieldCheck } from 'lucide-react';
import { PricingCard, FreeTrialCard } from '@/components/shared/PricingCard';
import { PageLoader } from '@/components/shared/Loader';
import { useAuth } from '@/hooks/useAuth';
import { useSubscription } from '@/hooks/useSubscription';
import { planService } from '@/services/plan.service';
import type { Plan } from '@/types';
import { FEATURES, ROUTES } from '@/constants';
import toast from 'react-hot-toast';
import { cn } from '@/utils';
import { setMobileCheckoutReturn } from '@/utils/sessionFlow';

interface ChoosePlanSectionProps {
  compact?: boolean;
}

export function ChoosePlanSection({ compact = false }: ChoosePlanSectionProps) {
  const { isAuthenticated } = useAuth();
  const { subscription, activateTrial, checkout, fetchSub } = useSubscription();
  const router = useRouter();

  const [plans, setPlans] = useState<Plan[]>([]);
  const [plansLoading, setPlansLoading] = useState(true);
  const [checkoutLoadingId, setCheckoutLoadingId] = useState<string | null>(null);
  const [trialLoading, setTrialLoading] = useState(false);

  useEffect(() => {
    planService
      .getPlans()
      .then((res) => setPlans(res.data))
      .catch(() => toast.error('Failed to load plans'))
      .finally(() => setPlansLoading(false));

    if (isAuthenticated) fetchSub();
  }, [isAuthenticated, fetchSub]);

  const handleSelectPlan = async (planId: string) => {
    if (!isAuthenticated) {
      router.push(ROUTES.LOGIN);
      return;
    }
    if (compact) {
      setMobileCheckoutReturn();
    }
    setCheckoutLoadingId(planId);
    await checkout(planId);
    setCheckoutLoadingId(null);
  };

  const handleStartTrial = async () => {
    if (!isAuthenticated) {
      router.push(ROUTES.LOGIN);
      return;
    }
    setTrialLoading(true);
    await activateTrial();
    setTrialLoading(false);
  };

  const hasTrialed =
    subscription?.status === 'trial_expired' ||
    subscription?.status === 'trialing' ||
    subscription?.status === 'active';

  return (
    <div className={cn('space-y-8', compact && 'space-y-6')}>
      <div className={cn('text-center space-y-3', compact ? 'space-y-2' : 'space-y-4')}>
        <h2
          className={cn(
            'font-bold',
            compact ? 'text-2xl' : 'text-4xl sm:text-5xl',
          )}
        >
          Choose your <span className="text-gradient-blue">plan</span>
        </h2>
        <p
          className={cn(
            'text-muted-foreground mx-auto',
            compact ? 'text-sm max-w-md' : 'text-lg max-w-xl',
          )}
        >
          Start with a free trial or go premium for full, uninterrupted access to everything
          Activate Abundanate has to offer.
        </p>
      </div>

      <div
        className={cn(
          'grid gap-3',
          compact ? 'grid-cols-1' : 'grid-cols-2 sm:grid-cols-3',
        )}
      >
        {FEATURES.slice(0, 3).map((f) => (
          <div
            key={f.title}
            className="flex items-center gap-3 rounded-xl border border-border bg-card shadow-card p-3 sm:p-4"
          >
            <span className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-500/10 text-brand-500 dark:text-brand-300 text-sm shrink-0">
              {f.icon}
            </span>
            <span className="text-sm font-medium">{f.title}</span>
          </div>
        ))}
      </div>

      {plansLoading ? (
        <PageLoader text="Loading plans…" />
      ) : (
        <div
          className={cn(
            'grid gap-4 items-start',
            compact ? 'grid-cols-1' : 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6',
          )}
        >
          <FreeTrialCard
            onStartTrial={handleStartTrial}
            isLoading={trialLoading}
            hasTrialed={hasTrialed}
          />

          {plans.map((plan) => (
            <PricingCard
              key={plan.id}
              plan={plan}
              isCurrentPlan={
                subscription?.plan_id === plan.id && subscription?.status === 'active'
              }
              isNextPlan={subscription?.next_plan_id === plan.id}
              nextPlanStartDate={subscription?.next_plan_start_date}
              onSelect={handleSelectPlan}
              isLoading={checkoutLoadingId === String(plan.id)}
              isAuthenticated={isAuthenticated}
            />
          ))}
        </div>
      )}

      <div className="flex flex-wrap items-center justify-center gap-4 pt-2">
        {[
          { icon: '🔒', label: 'Secure payments via Stripe' },
          { icon: '↩️', label: 'Cancel anytime' },
          { icon: '📱', label: 'Works on iOS & Android' },
        ].map((badge) => (
          <div key={badge.label} className="flex items-center gap-2 text-xs text-muted-foreground">
            <span>{badge.icon}</span>
            <span>{badge.label}</span>
          </div>
        ))}
      </div>

      <div className="text-center text-xs text-muted-foreground space-y-1">
        <div className="flex items-center justify-center gap-1.5">
          <ShieldCheck className="h-3.5 w-3.5 shrink-0" />
          <span>Payments are securely processed by Stripe. We never store your card details.</span>
        </div>
        <p>
          Subscriptions auto-renew. Cancel anytime — access continues until the end of your billing
          period.
        </p>
      </div>
    </div>
  );
}
