import { cookies, headers } from 'next/headers';
import { notFound, redirect } from 'next/navigation';
import Link from 'next/link';
import CVHeader from '@/components/layout/CVHeader';
import CVFooter from '@/components/layout/CVFooter';
import ConfettiAnimation from './ConfettiAnimation';
import ProgrammeClaimPanel from './ProgrammeClaimPanel';
import {
  getCheckoutOrder,
  getCheckoutPageBySlug,
  getCheckoutThanks,
} from '@/lib/checkoutData';
import { getContentMetadataForRequest, getRequestMetadataInput } from '@/lib/siteSeo';
import { getAuthenticatedUserFromToken } from '@/lib/adminAccess';
import { getProgrammeCheckout, getProgrammeDashboardUrl } from '@/lib/programmeCheckout';
import { getProgrammeClaimOrder } from '@/lib/programmeCheckoutClaim';

export const dynamic = 'force-dynamic';

export async function generateMetadata({ params }) {
  const { slug } = await params;
  const checkoutPage = await getCheckoutPageBySlug(slug);

  return getContentMetadataForRequest({
    ...getRequestMetadataInput(await headers(), {
      pathname: `/checkout/${slug}/thank-you`,
    }),
    title: `Payment Successful - ${checkoutPage?.course_short_code || 'Checkout'} | Cambridge Veritas`,
  });
}

function CheckIcon({ className = 'h-10 w-10' }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
      <path d="M20 6 9 17l-5-5" />
    </svg>
  );
}

function MailIcon({ className = 'h-7 w-7' }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect width="20" height="16" x="2" y="4" rx="2" />
      <path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7" />
    </svg>
  );
}

function CalendarIcon({ className = 'h-7 w-7' }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M8 2v4" />
      <path d="M16 2v4" />
      <rect width="18" height="18" x="3" y="4" rx="2" />
      <path d="M3 10h18" />
    </svg>
  );
}

function BookIcon({ className = 'h-7 w-7' }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 7v14" />
      <path d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z" />
    </svg>
  );
}

function ArrowRightIcon({ className = 'h-5 w-5' }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M5 12h14" />
      <path d="m12 5 7 7-7 7" />
    </svg>
  );
}

function JourneyCard({ icon, title, text }) {
  return (
    <div className="rounded-3xl bg-white border-2 border-[#E6D3B1]/50 shadow-lg p-6 text-center">
      <div className="w-16 h-16 rounded-full bg-[#F6EFE9] border-2 border-[#E6D3B1] text-[#8B1C1C] flex items-center justify-center mx-auto mb-4">
        {icon}
      </div>
      <h3 className="text-xl font-black text-[#4A141E] mb-3">{title}</h3>
      <p className="text-[#4A141E]/70 leading-relaxed">{text}</p>
    </div>
  );
}

function AlgebraMiniBrand() {
  return (
    <div className="mb-8 flex items-center gap-2.5">
      <div
        className="flex h-9 w-9 items-center justify-center rounded-lg text-[10px] font-extrabold"
        style={{ background: 'linear-gradient(135deg, #4A1429, #8B2252)', color: '#D4AF37' }}
      >
        CV
      </div>
      <div>
        <div className="text-xs font-extrabold tracking-wide" style={{ color: '#2D0A18', fontFamily: "'Fraunces', Georgia, serif" }}>
          Cambridge Veritas
        </div>
        <div className="text-[9px] font-bold uppercase tracking-[0.18em]" style={{ color: '#B8912E' }}>
          Algebra I Â· Enrollment
        </div>
      </div>
    </div>
  );
}

function AlgebraThankYouView({
  needsAccountActivation,
  orderReference,
  orderRecord,
  claim,
  claimReturnPath,
  viewer,
  programmeDashboardUrl,
  programmeCheckout,
}) {
  return (
    <main
      className="min-h-screen overflow-x-hidden"
      style={{
        background: '#FAF6EF',
        color: '#2D0A18',
        fontFamily: 'ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',
      }}
    >
      <ConfettiAnimation />
      <div className="relative z-10 mx-auto max-w-2xl px-5 py-10 sm:py-14">
        <AlgebraMiniBrand />

        <h1 className="mb-3 text-3xl font-extrabold leading-tight sm:text-4xl" style={{ fontFamily: "'Fraunces', Georgia, serif" }}>
          Payment successful!
        </h1>
        <p className="mb-7 text-sm font-medium leading-relaxed" style={{ color: '#4A3A30' }}>
          Your $179 monthly Algebra I subscription is confirmed. {needsAccountActivation
            ? 'Create your family account below to open the student dashboard.'
            : 'Your student dashboard is ready.'}
        </p>

        <section
          className="mb-6 rounded-3xl p-6 shadow-xl sm:p-8"
          style={{ background: '#FBF7EE', border: '1.5px dashed rgba(212,175,56,0.65)' }}
        >
          <span className="mb-4 inline-flex items-center gap-1.5 rounded-full px-3.5 py-1.5 text-[10px] font-bold uppercase tracking-widest" style={{ background: '#D4AF37', color: '#2D0A18' }}>
            <CheckIcon className="h-3.5 w-3.5" /> Monthly subscription active
          </span>
          <h2 className="mb-3 text-xl font-extrabold sm:text-2xl" style={{ fontFamily: "'Fraunces', Georgia, serif" }}>
            {needsAccountActivation ? 'One quick step, then you’re in.' : 'Your Algebra I access is ready.'}
          </h2>
          <p className="text-sm font-medium leading-relaxed" style={{ color: '#4A3A30' }}>
            {needsAccountActivation
              ? 'Use the same email address from checkout, verify it with the code we send, and we’ll take you straight to the dashboard.'
              : 'Classes, practice, feedback, notes and parent reports are now available in your dashboard.'}
          </p>
          {orderReference ? <p className="mt-4 text-[11px] font-semibold" style={{ color: '#9A8A70' }}>Reference #{String(orderReference).padStart(6, '0')}</p> : null}
        </section>

        {needsAccountActivation ? (
          <ProgrammeClaimPanel
            claimToken={claim}
            customerEmail={orderRecord.email}
            customerFirstName={orderRecord.first_name || ''}
            customerLastName={orderRecord.last_name || ''}
            customerPhone={orderRecord.phone || ''}
            programmeSlug="algebra-1-tutoring"
            returnPath={claimReturnPath}
            isAuthenticated={Boolean(viewer)}
            initialDashboardUrl={programmeDashboardUrl}
            redirectAfterClaim={Boolean(programmeCheckout.redirectAfterClaim)}
          />
        ) : (
          <section className="mb-6 rounded-3xl bg-white p-6 text-center sm:p-8" style={{ border: '1.5px solid rgba(212,175,56,0.5)' }}>
            <p className="mb-1.5 text-sm font-extrabold">Registration is already complete.</p>
            <p className="mb-2 text-xs font-semibold" style={{ color: '#9A8A70' }}>
              This subscription is linked to the account
            </p>
            <p className="mb-6 break-all text-sm font-extrabold" style={{ color: '#731F32' }}>
              {viewer?.email || orderRecord?.email}
            </p>
            <Link href={programmeDashboardUrl} className="inline-flex items-center justify-center gap-2 rounded-xl px-6 py-3.5 text-sm font-bold transition-opacity hover:opacity-90" style={{ background: '#D4AF37', color: '#2D0A18' }}>
              Open Algebra dashboard <ArrowRightIcon className="h-4 w-4" />
            </Link>
          </section>
        )}

        <section className="mb-6 rounded-3xl bg-white p-6 sm:p-8" style={{ border: '1.5px solid rgba(212,175,56,0.5)' }}>
          <p className="mb-5 text-[10px] font-bold uppercase tracking-[0.22em]" style={{ color: '#B8912E' }}>What happens next</p>
          <div className="space-y-4 text-sm font-medium leading-relaxed" style={{ color: '#4A3A30' }}>
            {needsAccountActivation ? (
              <>
                <p><strong style={{ color: '#2D0A18' }}>1. Create your account.</strong> Enter the parent and student details in the registration form above.</p>
                <p><strong style={{ color: '#2D0A18' }}>2. Verify your email.</strong> Enter the secure six-digit code we send to the checkout email.</p>
                <p><strong style={{ color: '#2D0A18' }}>3. Dashboard opens.</strong> Course access is activated immediately after verification.</p>
              </>
            ) : (
              <>
                <p><strong style={{ color: '#2D0A18' }}>1. Registration complete.</strong> Your payment and Algebra I subscription are linked to the account shown above.</p>
                <p><strong style={{ color: '#2D0A18' }}>2. Dashboard ready.</strong> Your child&apos;s course, practice and progress tools are available in one place.</p>
                <p><strong style={{ color: '#2D0A18' }}>3. Aisha welcomes you.</strong> We&apos;ll follow up with the class schedule and onboarding details.</p>
              </>
            )}
          </div>
        </section>

        <p className="text-center text-xs font-semibold" style={{ color: '#9A8A70' }}>
          Need help? <a className="font-bold underline" style={{ color: '#731F32' }} href="mailto:contact@cambridgeveritas.com">contact@cambridgeveritas.com</a>
        </p>
      </div>
    </main>
  );
}

export default async function ThankYouPage({ params, searchParams }) {
  const { slug } = await params;
  const query = await searchParams;
  const order_id = Array.isArray(query.order_id) ? query.order_id[0] : query.order_id;
  const claim = Array.isArray(query.claim) ? query.claim[0] : query.claim;
  const checkoutPage = await getCheckoutPageBySlug(slug);

  if (!checkoutPage) notFound();

  const programmeCheckout = getProgrammeCheckout(checkoutPage.checkout_slug);
  const programmeDashboardUrl = getProgrammeDashboardUrl(checkoutPage.checkout_slug);
  const programmeName = checkoutPage.course_short_name || checkoutPage.course_name || 'course';
  const thanks = await getCheckoutThanks(checkoutPage.id);
  const orderRecord = claim
    ? await getProgrammeClaimOrder(claim, checkoutPage.checkout_slug)
    : (order_id ? await getCheckoutOrder(order_id, checkoutPage.checkout_slug) : null);
  let viewer = null;
  if (programmeCheckout) {
    const token = (await cookies()).get('token')?.value || '';
    viewer = token ? await getAuthenticatedUserFromToken(token).catch(() => null) : null;
    if (
      !orderRecord
      || String(orderRecord.payment_status || '').toLowerCase() !== 'paid'
    ) {
      notFound();
    }
    if (!claim && (!viewer || String(orderRecord.user_id || '') !== String(viewer.id))) {
      const returnPath = `/checkout/${checkoutPage.checkout_slug}/thank-you?order_id=${encodeURIComponent(order_id)}`;
      redirect(`/login?redirect=${encodeURIComponent(returnPath)}`);
    }
  }
  const needsAccountActivation = Boolean(programmeCheckout && claim && !orderRecord?.access_granted_at);
  const claimReturnPath = claim
    ? `/checkout/${checkoutPage.checkout_slug}/thank-you?claim=${encodeURIComponent(claim)}`
    : '';
  const journeyPoints = programmeCheckout
    ? [
        `Your payment is verified and your ${programmeName} access is active.`,
        `Open your learning dashboard to access ${programmeName}.`,
        'Start learning now and return to your dashboard whenever you need it.',
      ]
    : [
        thanks?.journey_point1 || 'Check your inbox for your confirmation email and payment receipt.',
        thanks?.journey_point2 || 'Our admissions team will share your batch and onboarding details shortly.',
        thanks?.journey_point3 || 'Keep your documents and preferred class time ready for smooth onboarding.',
      ];
  const supportEmail = 'contact@cambridgeveritas.com';
  const supportPhone = '+918068212576';
  const orderReference = orderRecord?.id || order_id;

  if (checkoutPage.checkout_slug === 'algebra-1-tutoring') {
    return (
      <AlgebraThankYouView
        needsAccountActivation={needsAccountActivation}
        orderReference={orderReference}
        orderRecord={orderRecord}
        claim={claim}
        claimReturnPath={claimReturnPath}
        viewer={viewer}
        programmeDashboardUrl={programmeDashboardUrl}
        programmeCheckout={programmeCheckout}
      />
    );
  }

  return (
    <>
      <CVHeader />

      <main className="relative min-h-screen overflow-hidden bg-gradient-to-br from-[#F6EFE9] via-white to-[#E6D3B1]/20 px-4 py-12 md:py-16">
        <ConfettiAnimation />

        <div className="relative z-10 max-w-5xl mx-auto">
          <section className="rounded-3xl bg-white border-2 border-[#E6D3B1]/60 shadow-2xl p-8 md:p-10 text-center">
            <div className="w-20 h-20 rounded-full bg-gradient-to-br from-[#D4AF37] to-[#8B6914] text-white flex items-center justify-center mx-auto mb-6 shadow-xl">
              <CheckIcon className="h-9 w-9" />
            </div>

            <div className="inline-flex items-center gap-2 rounded-full bg-[#D4AF37]/20 border border-[#D4AF37]/40 px-4 py-2 text-[#8B1C1C] text-sm font-black mb-5">
              <CheckIcon className="h-4 w-4" />
              Payment Successful
            </div>

            <h1 className="text-3xl md:text-4xl font-black text-[#4A141E] mb-5">
              {needsAccountActivation
                ? 'Payment successful — activate your course access'
                : (programmeCheckout ? `Your ${programmeName} access is ready!` : 'Welcome to Cambridge Veritas!')}
            </h1>
            <p className="text-lg text-[#4A141E]/75 leading-relaxed max-w-3xl mx-auto">
              {needsAccountActivation
                ? 'Your payment is confirmed. Complete the account step below using the same email address entered at checkout.'
                : programmeCheckout
                ? `${programmeName} has been added to your learning dashboard.`
                : thanks?.header_subheading ||
                "You've taken the first step towards professional excellence. We're thrilled to have you on board."}
            </p>

            {orderReference && (
              <p className="mt-6 text-sm text-[#4A141E]/50">
                Order reference: <span className="font-mono font-bold">#{String(orderReference).padStart(6, '0')}</span>
              </p>
            )}

            {needsAccountActivation && (
              <ProgrammeClaimPanel
                claimToken={claim}
                customerEmail={orderRecord.email}
                customerFirstName={orderRecord.first_name || ''}
                customerLastName={orderRecord.last_name || ''}
                customerPhone={orderRecord.phone || ''}
                programmeSlug={checkoutPage.checkout_slug}
                returnPath={claimReturnPath}
                isAuthenticated={Boolean(viewer)}
                initialDashboardUrl={programmeDashboardUrl}
                redirectAfterClaim={Boolean(programmeCheckout.redirectAfterClaim)}
              />
            )}
          </section>

          <section className="mt-10">
            <h2 className="text-2xl md:text-3xl font-black text-[#4A141E] text-center mb-3">What Happens Next?</h2>
            <p className="text-center text-[#4A141E]/65 text-base md:text-lg mb-8">
              {needsAccountActivation
                ? 'Three quick steps complete your enrolment'
                : (thanks?.journey_detail || "Here's what to expect in the coming hours")}
            </p>

            <div className="grid md:grid-cols-3 gap-6">
              <JourneyCard
                icon={<MailIcon />}
                title={needsAccountActivation ? 'Payment Confirmed' : (programmeCheckout ? 'Access Activated' : 'Confirmation Email')}
                text={needsAccountActivation ? 'Razorpay has confirmed your one-time programme payment.' : journeyPoints[0]}
              />
              <JourneyCard
                icon={<CalendarIcon />}
                title={needsAccountActivation ? 'Create or Sign In' : (programmeCheckout ? 'Open Dashboard' : 'Batch Details')}
                text={needsAccountActivation ? 'Use the payment email to create your verified account, or sign in if it already exists.' : journeyPoints[1]}
              />
              <JourneyCard
                icon={<BookIcon />}
                title={needsAccountActivation ? 'Access the Course' : (programmeCheckout ? 'Start Learning' : 'Start Preparing')}
                text={needsAccountActivation ? 'Course access is activated automatically as soon as authentication is complete.' : journeyPoints[2]}
              />
            </div>
          </section>

          <section className="mt-10 rounded-3xl bg-gradient-to-br from-[#4A141E] to-[#3B0F18] border-2 border-[#D4AF37] shadow-xl p-8 text-center">
            <h2 className="text-2xl font-black text-[#E6D3B1] mb-4">Need Help?</h2>
            <p className="text-[#F6EFE9]/80 leading-relaxed max-w-2xl mx-auto mb-7">
              Our student advisor team is available to help with your payment confirmation, batch details, and onboarding.
            </p>
            <div className="flex flex-col sm:flex-row items-center justify-center gap-4">
              <a
                href={`mailto:${supportEmail}`}
                className="inline-flex items-center justify-center rounded-2xl bg-white/10 border-2 border-[#E6D3B1]/30 px-7 py-3 font-black text-[#F6EFE9] hover:bg-white/20 transition-colors"
              >
                {supportEmail}
              </a>
              <a
                href={`tel:${supportPhone.replace(/\s+/g, '')}`}
                className="inline-flex items-center justify-center rounded-2xl bg-white/10 border-2 border-[#E6D3B1]/30 px-7 py-3 font-black text-[#F6EFE9] hover:bg-white/20 transition-colors"
              >
                {supportPhone}
              </a>
            </div>
          </section>

          {!needsAccountActivation && <div className="mt-10 text-center">
            <Link
              href={programmeCheckout ? programmeDashboardUrl : '/'}
              className="inline-flex items-center justify-center gap-3 rounded-2xl bg-[#8B1C1C] border-2 border-[#8B1C1C] hover:border-[#D4AF37] px-9 py-4 text-white font-black shadow-xl transition-colors"
            >
              {programmeCheckout ? 'Open Your Dashboard' : 'Back to Home'}
              <ArrowRightIcon />
            </Link>
          </div>}
        </div>
      </main>

      <CVFooter />
    </>
  );
}
