'use client'

import React, { useEffect, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { motion, AnimatePresence } from 'framer-motion';
import { getApiPath } from '@/lib/basePath';
import LightHeaderLogo from '@/components/brand/LightHeaderLogo';
import {
  ArrowLeft,
  BarChart2,
  CheckCircle2,
  FileText,
  Heart,
  Lock,
  LogOut,
  Mic,
  Star,
  TrendingDown,
  TrendingUp,
  Trophy,
  XCircle,
} from 'lucide-react';
import { useNavigate } from '@/lib/nextRouterAdapter';
import { useAuth } from '@/lib/AuthContext';
import { fetchUserPlan } from '@/lib/userPlan';
import { appendRegionCurrencyToPath } from '@/lib/regionCurrencyLink';

const lossItems = [
  {
    icon: Mic,
    color: '#D4B038',
    bg: '#FFFBEB',
    border: '#FDE68A',
    title: 'AI coaching sessions',
    desc: 'They continue until expiry, then stop unless you activate renewal again.',
  },
  {
    icon: TrendingUp,
    color: '#3B82F6',
    bg: '#EFF6FF',
    border: '#BFDBFE',
    title: 'Weekly progress tracking',
    desc: 'Fresh progress tracking pauses only after the paid period ends.',
  },
  {
    icon: FileText,
    color: '#8B5CF6',
    bg: '#F5F3FF',
    border: '#DDD6FE',
    title: 'PDF performance reports',
    desc: 'New report downloads continue until your current plan expires.',
  },
  {
    icon: BarChart2,
    color: '#10B981',
    bg: '#ECFDF5',
    border: '#A7F3D0',
    title: 'IELTS and CEFR benchmarking',
    desc: 'Benchmarks stay available for paid sessions left in this plan cycle.',
  },
];

const timelineItems = [
  { day: 'Today', label: 'Access continues', sub: 'Use your paid sessions until expiry', color: '#D4B038' },
  { day: 'Expiry', label: 'Renewal stops', sub: 'No automatic next-month charge', color: '#F59E0B' },
  { day: 'After expiry', label: 'Coaching pauses', sub: 'Restart from the plan page anytime', color: '#EF4444' },
  { day: 'Later', label: 'Reactivate if needed', sub: 'Keep your history and continue again', color: '#DC2626' },
];

function formatDate(isoStr) {
  if (!isoStr) return 'your expiry date';
  return new Date(isoStr).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
}

export default function CancelSubscription() {
  const navigate = useNavigate();
  const { user, logout, isAuthenticated, isLoadingAuth, navigateToLogin } = useAuth();
  const [step, setStep] = useState('confirm');
  const [loading, setLoading] = useState(false);
  const [showFinalWarning, setShowFinalWarning] = useState(false);
  const [cancelError, setCancelError] = useState('');
  const [reactivateError, setReactivateError] = useState('');

  useEffect(() => {
    if (!isLoadingAuth && !isAuthenticated) {
      navigateToLogin('/tools/signin');
    }
  }, [isAuthenticated, isLoadingAuth, navigateToLogin]);

  const { data: userPlanData = { hasPlan: false }, isLoading: isLoadingPlan, refetch } = useQuery({
    queryKey: ['userPlan', user?.id],
    queryFn: () => fetchUserPlan(user?.id),
    enabled: !!user?.id,
    staleTime: 30_000,
    retry: 1,
  });

  const activePlan = userPlanData?.plan;
  const plan = activePlan?.plan_name || 'your plan';
  const isSubscriptionCancelled = String(activePlan?.status || '').toLowerCase() === 'cancelled' || userPlanData?.isRenewalCancelled;
  const accessUntil = formatDate(activePlan?.expires_at);

  const handleCancel = async () => {
    if (!user?.id) return;

    setLoading(true);
    setCancelError('');

    try {
      const res = await fetch(getApiPath('/api/user/plan/cancel'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId: user.id }),
      });
      const payload = await res.json().catch(() => ({}));

      if (!res.ok) {
        throw new Error(payload.message || 'Unable to cancel subscription.');
      }

      await refetch();
      setStep('cancelled');
    } catch (error) {
      setCancelError(error.message || 'Unable to cancel subscription right now.');
    } finally {
      setLoading(false);
    }
  };

  const handleReactivate = async () => {
    if (!user?.id) return;

    setLoading(true);
    setReactivateError('');

    try {
      const res = await fetch(getApiPath('/api/user/plan/reactivate'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId: user.id }),
      });
      const payload = await res.json().catch(() => ({}));

      if (!res.ok) {
        throw new Error(payload.message || 'Unable to reactivate subscription.');
      }

      await refetch();
      setStep('reactivated');
    } catch (error) {
      setReactivateError(error.message || 'Unable to reactivate subscription right now.');
    } finally {
      setLoading(false);
    }
  };

  if (isLoadingAuth || !isAuthenticated || isLoadingPlan) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-[#FAF5F0]">
        <div className="w-8 h-8 border-4 border-[#E5DDD5] border-t-[#4A1429] rounded-full animate-spin" />
      </div>
    );
  }

  if (!userPlanData?.hasPlan) {
    return (
      <div className="min-h-screen bg-[#FAF5F0]">
        <div className="bg-gradient-to-r from-[#2D0A18] via-[#4A1429] to-[#3A0F20] shadow-xl">
          <div className="max-w-3xl mx-auto px-4 py-4 flex items-center justify-between">
            <button onClick={() => navigate('/tools/dashboard')}>
              <LightHeaderLogo />
            </button>
            <button onClick={() => navigate('/tools/dashboard')} className="text-white/50 hover:text-white text-xs font-semibold transition-colors flex items-center gap-1.5">
              <ArrowLeft className="w-3.5 h-3.5" />
              Dashboard
            </button>
          </div>
        </div>
        <div className="max-w-xl mx-auto px-4 py-12">
          <div className="bg-white rounded-3xl border border-[#E5DDD5] p-8 text-center shadow-sm">
            <div className="w-14 h-14 rounded-2xl bg-[#FAF5F0] border border-[#E5DDD5] flex items-center justify-center mx-auto mb-4">
              <CheckCircle2 className="w-7 h-7 text-[#D4B038]" />
            </div>
            <h1 className="text-xl font-extrabold text-[#4A1429] mb-2">No active subscription</h1>
            <p className="text-gray-500 text-sm mb-6">There is no active plan to cancel on this account.</p>
            <button
              onClick={() => navigate('/tools/dashboard')}
              className="w-full py-3.5 rounded-2xl bg-[#4A1429] hover:bg-[#3A1020] text-white font-extrabold text-sm transition-all"
            >
              Back to Dashboard
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[#FAF5F0] flex flex-col">
      <div className="bg-gradient-to-r from-[#2D0A18] via-[#4A1429] to-[#3A0F20] shadow-xl">
        <div className="max-w-3xl mx-auto px-4 py-4 flex items-center justify-between gap-3">
          <button onClick={() => navigate('/tools/dashboard')} className="flex items-center gap-2.5">
            <LightHeaderLogo />
          </button>
          <div className="flex items-center gap-3">
            <button onClick={() => navigate('/tools/active-plan')} className="flex items-center gap-2 text-white/60 hover:text-white transition-colors">
              <ArrowLeft className="w-4 h-4" />
              <span className="text-sm font-semibold">Back to Plan</span>
            </button>
            <button onClick={() => logout(appendRegionCurrencyToPath('/tools/signin'))} className="hidden sm:flex items-center gap-1.5 text-white/50 hover:text-white text-xs transition-colors">
              <LogOut className="w-4 h-4" />
              Log out
            </button>
          </div>
        </div>
      </div>

      <div className="flex-1 px-4 py-8 sm:py-12">
        <div className="w-full max-w-2xl mx-auto">
          <AnimatePresence mode="wait">
            {isSubscriptionCancelled && step === 'confirm' && (
              <motion.div
                key="reactivate"
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -20 }}
                className="bg-white rounded-3xl shadow-sm border border-[#E5DDD5] p-8 text-center"
              >
                <div className="w-16 h-16 bg-amber-50 border border-amber-100 rounded-2xl flex items-center justify-center mx-auto mb-5">
                  <XCircle className="w-8 h-8 text-amber-500" />
                </div>
                <div className="text-[#D4B038] text-xs font-bold uppercase tracking-widest mb-2">{plan}</div>
                <h1 className="text-xl font-extrabold text-[#4A1429] mb-2">Subscription renewal is cancelled</h1>
                <p className="text-gray-500 text-sm leading-relaxed mb-6">
                  You can still use your paid sessions until {accessUntil}. Activate your subscription again to keep renewal on after that date.
                </p>
                <div className="bg-[#FAF5F0] rounded-2xl p-4 mb-6">
                  <CheckCircle2 className="w-5 h-5 text-emerald-500 mx-auto mb-2" />
                  <p className="text-xs text-gray-400">Your test access remains available until the current plan expiry.</p>
                </div>
                {reactivateError && (
                  <div className="bg-red-50 border border-red-100 rounded-2xl p-3 mb-4 text-xs font-semibold text-red-600">
                    {reactivateError}
                  </div>
                )}
                <button
                  onClick={handleReactivate}
                  disabled={loading}
                  className="w-full py-3.5 rounded-2xl bg-[#4A1429] hover:bg-[#3A1020] text-white font-extrabold text-sm transition-all disabled:opacity-50 mb-3"
                >
                  {loading ? 'Activating...' : 'Activate subscription'}
                </button>
                <button
                  onClick={() => navigate('/tools/dashboard')}
                  className="w-full py-3.5 rounded-2xl border border-[#E5DDD5] text-[#4A1429]/70 text-sm font-semibold hover:bg-[#FAF5F0] transition-all"
                >
                  Back to Dashboard
                </button>
              </motion.div>
            )}

            {!isSubscriptionCancelled && step === 'confirm' && !showFinalWarning && (
              <motion.div
                key="confirm"
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -20 }}
                className="space-y-4"
              >
                <div className="relative rounded-3xl overflow-hidden bg-gradient-to-br from-[#2D0A18] via-[#4A1429] to-[#3A0F20]">
                  <div
                    className="absolute inset-0 opacity-[0.06]"
                    style={{ backgroundImage: 'radial-gradient(circle, #fff 1px, transparent 1px)', backgroundSize: '24px 24px' }}
                  />
                  <div
                    className="absolute top-0 right-0 w-56 h-56 pointer-events-none"
                    style={{ background: 'radial-gradient(circle, rgba(212,176,56,0.15) 0%, transparent 70%)', transform: 'translate(20%,-20%)' }}
                  />
                  <div className="relative p-6 sm:p-8 text-center">
                    <motion.div
                      animate={{ scale: [1, 1.08, 1] }}
                      transition={{ repeat: Infinity, duration: 2.5, ease: 'easeInOut' }}
                      className="w-16 h-16 rounded-2xl flex items-center justify-center mx-auto mb-4 bg-[#D4B038]/15 border border-[#D4B038]/30"
                    >
                      <TrendingDown className="w-8 h-8 text-[#D4B038]" />
                    </motion.div>
                    <div className="text-[#D4B038] text-xs font-bold uppercase tracking-widest mb-2">{plan}</div>
                    <h1 className="text-xl sm:text-2xl font-extrabold text-white mb-2 leading-tight">
                      Wait, you are about to lose everything you have built.
                    </h1>
                    <p className="text-white/55 text-sm leading-relaxed max-w-md mx-auto">
                      Cancelling stops the next renewal. You can still use the sessions you already paid for until {accessUntil}.
                    </p>
                  </div>
                </div>

                <div>
                  <p className="text-xs font-extrabold uppercase tracking-widest text-[#4A1429]/50 mb-3 px-1">What changes after cancellation</p>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    {lossItems.map((item, i) => {
                      const Icon = item.icon;
                      return (
                        <motion.div
                          key={item.title}
                          initial={{ opacity: 0, y: 12 }}
                          animate={{ opacity: 1, y: 0 }}
                          transition={{ delay: 0.1 + i * 0.07 }}
                          className="bg-white rounded-2xl p-4 border flex items-start gap-3"
                          style={{ borderColor: item.border }}
                        >
                          <div className="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0 mt-0.5" style={{ background: item.bg }}>
                            <Icon className="w-[18px] h-[18px]" style={{ color: item.color }} />
                          </div>
                          <div className="flex-1">
                            <div className="font-extrabold text-[#4A1429] text-sm mb-0.5">{item.title}</div>
                            <div className="text-gray-400 text-xs leading-relaxed">{item.desc}</div>
                          </div>
                          <XCircle className="w-4 h-4 text-red-300 flex-shrink-0 mt-0.5" />
                        </motion.div>
                      );
                    })}
                  </div>
                </div>

                <motion.div
                  initial={{ opacity: 0, y: 12 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.4 }}
                  className="bg-white rounded-2xl border border-[#E5DDD5] p-5"
                >
                  <p className="text-xs font-extrabold uppercase tracking-widest text-[#4A1429]/50 mb-4">Your plan after cancellation</p>
                  <div className="grid grid-cols-2 gap-3">
                    {timelineItems.map((item, i) => (
                      <div
                        key={item.day}
                        className="rounded-xl p-3 border"
                        style={{ background: i === 0 ? '#FFFBEB' : '#FFF5F5', borderColor: i === 0 ? '#FDE68A' : '#FECACA' }}
                      >
                        <div className="flex items-center gap-2 mb-1.5">
                          <div className="w-6 h-6 rounded-full flex items-center justify-center text-white text-[10px] font-extrabold flex-shrink-0" style={{ backgroundColor: item.color }}>
                            {i + 1}
                          </div>
                          <span className="text-[10px] font-extrabold uppercase tracking-wide" style={{ color: item.color }}>{item.day}</span>
                        </div>
                        <div className="font-bold text-[#4A1429] text-xs mb-0.5">{item.label}</div>
                        <div className="text-gray-400 text-[11px] leading-relaxed">{item.sub}</div>
                      </div>
                    ))}
                  </div>
                </motion.div>

                <motion.div
                  initial={{ opacity: 0, y: 12 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.5 }}
                  className="rounded-2xl p-5 border border-amber-200 bg-gradient-to-br from-[#FFFBEB] to-[#FEF3C7]"
                >
                  <div className="flex items-start gap-3">
                    <div className="w-10 h-10 rounded-xl bg-amber-100 flex items-center justify-center flex-shrink-0">
                      <Trophy className="w-5 h-5 text-amber-500" />
                    </div>
                    <div>
                      <div className="font-extrabold text-amber-900 text-sm mb-1">The real cost of stopping now</div>
                      <p className="text-amber-700 text-xs leading-relaxed">
                        Every week without coaching adds more uncertainty to your prep timeline. Private tutors can cost Rs. 800 to Rs. 2,000 per session. Keeping your plan keeps practice structured and affordable.
                      </p>
                    </div>
                  </div>
                </motion.div>

                <motion.div
                  initial={{ opacity: 0, y: 12 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.6 }}
                  className="space-y-3"
                >
                  <button
                    onClick={() => navigate('/tools/active-plan')}
                    className="w-full py-4 rounded-2xl font-extrabold text-sm sm:text-base transition-all flex items-center justify-center gap-2 shadow-lg hover:scale-[1.01] bg-gradient-to-br from-[#D4B038] to-[#C49A20] text-[#4A1429]"
                  >
                    <Star className="w-4 h-4 sm:w-5 sm:h-5 shrink-0" />
                    <span>Keep my subscription and keep improving</span>
                  </button>
                  <button
                    onClick={() => setShowFinalWarning(true)}
                    className="w-full py-3 rounded-2xl border border-red-200 text-red-400 text-sm font-semibold hover:bg-red-50 transition-all"
                  >
                    I still want to cancel
                  </button>
                </motion.div>
              </motion.div>
            )}

            {!isSubscriptionCancelled && step === 'confirm' && showFinalWarning && (
              <motion.div
                key="final"
                initial={{ opacity: 0, scale: 0.97 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0 }}
                className="bg-white rounded-3xl border border-red-100 overflow-hidden shadow-sm"
              >
                <div className="h-1.5 bg-gradient-to-r from-red-300 to-red-500" />
                <div className="p-6 sm:p-8 text-center">
                  <div className="w-16 h-16 bg-red-50 border border-red-100 rounded-2xl flex items-center justify-center mx-auto mb-5">
                    <Lock className="w-8 h-8 text-red-400" />
                  </div>
                  <h2 className="text-xl font-extrabold text-[#4A1429] mb-2">Are you absolutely sure?</h2>
                  <p className="text-gray-500 text-sm leading-relaxed mb-6">
                    Once cancelled, renewal stops but your paid plan access remains until {accessUntil}. You can reactivate renewal before expiry.
                  </p>

                  <div className="bg-red-50 border border-red-100 rounded-2xl p-4 mb-5 text-left space-y-2.5">
                    {[
                      `You can still use paid sessions until ${accessUntil}`,
                      'Next-month renewal will stop',
                      'You can activate the subscription again before expiry',
                    ].map((item) => (
                      <div key={item} className="flex items-center gap-2.5 text-sm text-red-600">
                        <XCircle className="w-4 h-4 flex-shrink-0 text-red-400" />
                        {item}
                      </div>
                    ))}
                  </div>

                  {cancelError && (
                    <div className="bg-red-50 border border-red-100 rounded-2xl p-3 mb-4 text-xs font-semibold text-red-600">
                      {cancelError}
                    </div>
                  )}

                  <button
                    onClick={handleCancel}
                    disabled={loading}
                    className="w-full py-3.5 rounded-2xl border border-red-300 text-red-500 text-sm font-semibold hover:bg-red-50 transition-all mb-3 disabled:opacity-50"
                  >
                    {loading ? 'Cancelling...' : 'Yes, cancel my subscription'}
                  </button>
                  <button
                    onClick={() => { setShowFinalWarning(false); navigate('/tools/active-plan'); }}
                    className="w-full py-3.5 rounded-2xl font-extrabold text-sm transition-all bg-gradient-to-br from-[#D4B038] to-[#C49A20] text-[#4A1429]"
                  >
                    No, keep my subscription
                  </button>
                </div>
              </motion.div>
            )}

            {step === 'cancelled' && (
              <motion.div
                key="cancelled"
                initial={{ opacity: 0, scale: 0.95 }}
                animate={{ opacity: 1, scale: 1 }}
                className="bg-white rounded-3xl shadow-sm border border-[#E5DDD5] p-8 text-center"
              >
                <motion.div
                  initial={{ scale: 0 }}
                  animate={{ scale: 1 }}
                  transition={{ delay: 0.1, type: 'spring', stiffness: 200 }}
                  className="w-16 h-16 bg-[#FAF5F0] rounded-2xl flex items-center justify-center mx-auto mb-5"
                >
                  <Heart className="w-8 h-8 text-[#D4B038]" />
                </motion.div>
                <h1 className="text-xl font-extrabold text-[#4A1429] mb-2">Subscription cancelled</h1>
                <p className="text-gray-500 text-sm leading-relaxed mb-6">
                  Your renewal has been cancelled. You can still use your paid sessions until {accessUntil}, and you can activate renewal again before expiry.
                </p>
                <div className="bg-[#FAF5F0] rounded-2xl p-4 mb-6">
                  <CheckCircle2 className="w-5 h-5 text-emerald-500 mx-auto mb-2" />
                  <p className="text-xs text-gray-400">Cancellation completed. Your previous results and current access remain safe.</p>
                </div>
                {reactivateError && (
                  <div className="bg-red-50 border border-red-100 rounded-2xl p-3 mb-4 text-xs font-semibold text-red-600">
                    {reactivateError}
                  </div>
                )}
                <button
                  onClick={handleReactivate}
                  disabled={loading}
                  className="w-full py-3.5 rounded-2xl bg-[#D4B038] hover:bg-[#C9A830] text-[#4A1429] font-extrabold text-sm transition-all disabled:opacity-50 mb-3"
                >
                  {loading ? 'Activating...' : 'Activate subscription again'}
                </button>
                <button
                  onClick={() => navigate('/tools/dashboard')}
                  className="w-full py-3.5 rounded-2xl bg-[#4A1429] hover:bg-[#3A1020] text-white font-extrabold text-sm transition-all"
                >
                  Back to Dashboard
                </button>
              </motion.div>
            )}

            {step === 'reactivated' && (
              <motion.div
                key="reactivated"
                initial={{ opacity: 0, scale: 0.95 }}
                animate={{ opacity: 1, scale: 1 }}
                className="bg-white rounded-3xl shadow-sm border border-[#E5DDD5] p-8 text-center"
              >
                <div className="w-16 h-16 bg-emerald-50 border border-emerald-100 rounded-2xl flex items-center justify-center mx-auto mb-5">
                  <CheckCircle2 className="w-8 h-8 text-emerald-500" />
                </div>
                <h1 className="text-xl font-extrabold text-[#4A1429] mb-2">Subscription activated</h1>
                <p className="text-gray-500 text-sm leading-relaxed mb-6">
                  Your subscription renewal is active again. Your plan access continues as normal.
                </p>
                <button
                  onClick={() => navigate('/tools/dashboard')}
                  className="w-full py-3.5 rounded-2xl bg-[#4A1429] hover:bg-[#3A1020] text-white font-extrabold text-sm transition-all"
                >
                  Back to Dashboard
                </button>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </div>
    </div>
  );
}
