/* eslint-disable @typescript-eslint/no-explicit-any */
import Link from "next/link";
import { stripe } from "@/lib/stripe";
import SetPaymentCookie from "@/component/common/SetPaymentCookie";

export default async function SuccessPage(props: {
  searchParams: Promise<{ session_id?: string }>;
}) {
  const searchParams = await props.searchParams;
  const sessionId = searchParams.session_id;

  let customerName = "Awesome Customer";
  let amountTotal = "0.00";
  let planName = "Monthly Partner";
  let billingCycle = "Monthly";
  let dateFormatted = new Date().toLocaleString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
    hour: "numeric",
    minute: "2-digit",
  });
  let cardLast4 = "••••";
  let invoiceId = "N/A";

  if (sessionId) {
    try {
      const session = await stripe.checkout.sessions.retrieve(sessionId, {
        expand: [
          "subscription", 
          "subscription.default_payment_method", 
          "payment_intent.payment_method", 
          "invoice",
          "invoice.payment_intent.payment_method"
        ],
      });

      customerName = session.customer_details?.name || "Awesome Customer";
      if (session.amount_total) {
        amountTotal = (session.amount_total / 100).toFixed(2);
      }

      if (session.subscription) {
        const sub = session.subscription as any;
        if (sub.items?.data?.[0]?.price?.nickname) {
          planName = sub.items.data[0].price.nickname;
        }

        if (sub.current_period_end) {
          const nextBillingDate = new Date(
            sub.current_period_end * 1000,
          ).toLocaleDateString("en-US", {
            month: "short",
            day: "numeric",
            year: "numeric",
          });
          billingCycle = `Monthly · renews ${nextBillingDate}`;
        } else {
          billingCycle = "Monthly";
        }
      } else {
        billingCycle = "One-time";
      }

      if (session.invoice) {
        const inv = session.invoice as any;
        invoiceId =
          inv.number ||
          inv.receipt_number ||
          sessionId.slice(-12).toUpperCase();
      } else {
        invoiceId = sessionId.slice(-12).toUpperCase();
      }

      let pm: any = null;

      if (session.payment_intent && typeof session.payment_intent !== "string") {
        const pi = session.payment_intent as any;
        pm = pi.payment_method;
      }
      
      if (!pm && session.invoice && typeof session.invoice !== "string") {
        const inv = session.invoice as any;
        if (inv.payment_intent && typeof inv.payment_intent !== "string") {
          pm = inv.payment_intent.payment_method;
        }
      }
      
      if (!pm && session.subscription && typeof session.subscription !== "string") {
        const sub = session.subscription as any;
        if (sub.default_payment_method && typeof sub.default_payment_method !== "string") {
          pm = sub.default_payment_method;
        }
      }

      if (pm && typeof pm !== "string" && pm.card?.last4) {
        cardLast4 = pm.card.last4;
      }

      dateFormatted = new Date(session.created * 1000).toLocaleString("en-US", {
        month: "short",
        day: "numeric",
        year: "numeric",
        hour: "numeric",
        minute: "2-digit",
      });
    } catch (e) {
      console.error("Error fetching stripe session:", e);
    }
  }

  const firstName = customerName.split(" ")[0];

  return (
    <div className="success-page-container">
      <SetPaymentCookie />
      <style>{`
        .success-page-container {
          background: #ffffff;
          color: #1a1916;
          font-family: var(--font-inter, 'DM Sans', sans-serif);
          font-weight: 400;
          display: flex;
          flex-direction: column;
          align-items: center;
          padding: 4rem 1.5rem 3rem;
        }
        
        .success-page-container *, .success-page-container *::before, .success-page-container *::after { 
          box-sizing: border-box; 
          margin: 0; 
          padding: 0; 
        }

        .check-wrap {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          background: #1e5eff;
          box-shadow: 0 10px 25px -5px rgba(30,94,255,0.4);
          display: flex;
          align-items: center;
          justify-content: center;
          margin-bottom: 1.75rem;
          animation: popIn 0.4s cubic-bezier(0.34,1.56,0.64,1) forwards;
        }

        @keyframes popIn {
          from { opacity: 0; transform: scale(0.7); }
          to { opacity: 1; transform: scale(1); }
        }

        .check-icon {
          width: 26px; 
          height: 26px;
          stroke: #ffffff; 
          stroke-width: 3;
          fill: none; 
          stroke-linecap: round; 
          stroke-linejoin: round;
        }

        .check-path {
          stroke-dasharray: 30; 
          stroke-dashoffset: 30;
          animation: drawCheck 0.45s 0.25s ease forwards;
        }

        @keyframes drawCheck { to { stroke-dashoffset: 0; } }

        @keyframes fadeUp {
          from { opacity: 0; transform: translateY(10px); }
          to { opacity: 1; transform: translateY(0); }
        }

        .headline {
          font-family: var(--font-fraunces, 'Instrument Serif', serif);
          font-size: clamp(1.9rem, 5vw, 2.8rem);
          font-weight: 400;
          letter-spacing: -0.03em;
          line-height: 1.1;
          text-align: center;
          margin-bottom: 0.65rem;
          color: #1a1916;
          animation: fadeUp 0.4s 0.1s ease both;
        }

        .headline em { 
          font-style: italic; 
          color: #9a9890; 
        }

        .subtext {
          font-family: var(--font-inter, 'DM Sans', sans-serif);
          font-size: 0.9rem;
          color: #9a9890;
          text-align: center;
          line-height: 1.65;
          max-width: 360px;
          margin-bottom: 2.5rem;
          animation: fadeUp 0.4s 0.15s ease both;
        }

        .receipt-card {
          width: 100%;
          max-width: 440px;
          background: #ffffff;
          border: 1px solid #e8e5e0;
          border-radius: 14px;
          overflow: hidden;
          margin-bottom: 1rem;
          animation: fadeUp 0.4s 0.2s ease both;
        }

        .receipt-header {
          padding: 1.4rem 1.6rem;
          border-bottom: 1px solid #f0ede8;
          display: flex;
          align-items: center;
          justify-content: space-between;
          background: #faf9f7;
        }

        .receipt-label {
          font-family: var(--font-inter, 'DM Sans', sans-serif);
          font-size: 0.7rem;
          font-weight: 600;
          letter-spacing: 0.09em;
          text-transform: uppercase;
          color: #6b6760;
          margin-bottom: 0.3rem;
        }

        .receipt-amount {
          font-family: var(--font-fraunces, 'Instrument Serif', serif);
          font-size: 1.8rem;
          letter-spacing: -0.03em;
          color: #1a1916;
        }

        .badge-success {
          font-family: var(--font-inter, 'DM Sans', sans-serif);
          font-size: 0.68rem;
          font-weight: 500;
          letter-spacing: 0.05em;
          text-transform: uppercase;
          color: #1442b8;
          background: #eef3ff;
          border: 1px solid #c4d5ff;
          padding: 0.3rem 0.7rem;
          border-radius: 100px;
        }

        .receipt-rows { 
          padding: 0.2rem 0; 
        }

        .receipt-row {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 0.85rem 1.6rem;
          border-bottom: 1px solid #f5f3ef;
        }

        .receipt-row:last-child { 
          border-bottom: none; 
        }

        .row-key { 
          font-family: var(--font-inter, 'DM Sans', sans-serif);
          font-size: 0.8rem; 
          font-weight: 500;
          color: #6b6760; 
        }

        .row-val { 
          font-family: var(--font-inter, 'DM Sans', sans-serif);
          font-size: 0.82rem; 
          font-weight: 500;
          color: #1a1916; 
          text-align: right; 
        }

        .row-val.mono {
          font-family: 'Courier New', monospace;
          font-size: 0.76rem;
          letter-spacing: 0.03em;
          color: #4a4845;
        }

        .actions {
          width: 100%;
          max-width: 440px;
          animation: fadeUp 0.4s 0.25s ease both;
          margin-bottom: 2.5rem;
        }

        .btn-primary-sc {
          display: block;
          width: 100%;
          padding: 0.95rem 1.5rem;
          background: #1a1916;
          color: #ffffff;
          border: none;
          border-radius: 10px;
          font-family: var(--font-inter, 'DM Sans', sans-serif);
          font-size: 0.9rem;
          font-weight: 500;
          text-align: center;
          text-decoration: none;
          cursor: pointer;
          transition: opacity 0.2s;
        }

        .btn-primary-sc:hover { 
          opacity: 0.82; 
        }

        .next-steps {
          width: 100%;
          max-width: 440px;
          animation: fadeUp 0.4s 0.3s ease both;
        }

        .steps-label {
          font-family: var(--font-inter, 'DM Sans', sans-serif);
          font-size: 0.68rem;
          font-weight: 600;
          letter-spacing: 0.1em;
          text-transform: uppercase;
          color: #8c8a82;
          margin-bottom: 0.75rem;
        }

        .step-item {
          display: flex;
          gap: 1rem;
          align-items: flex-start;
          padding: 0.85rem 0;
          border-top: 1px solid #f0ede8;
        }

        .step-num {
          width: 22px; 
          height: 22px;
          border-radius: 50%;
          border: 1px solid #dcd9d2;
          background: #faf9f7;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 0.65rem;
          font-weight: 600;
          color: #6b6760;
          flex-shrink: 0;
          margin-top: 1px;
        }

        .step-text strong {
          display: block;
          font-family: var(--font-inter, 'DM Sans', sans-serif);
          font-size: 0.84rem;
          font-weight: 500;
          color: #1a1916;
          margin-bottom: 0.15rem;
        }

        .step-text p { 
          font-family: var(--font-inter, 'DM Sans', sans-serif);
          font-size: 0.78rem; 
          color: #6b6760; 
          line-height: 1.5; 
        }

        .success-footer {
          width: 100%;
          text-align: center;
          padding: 1.75rem 2rem;
          font-family: var(--font-inter, 'DM Sans', sans-serif);
          font-size: 0.72rem;
          font-weight: 500;
          color: #8c8a82;
          margin-top: 2rem;
          background-color: transparent;
        }

        .success-footer hr {
          border: none;
          border-top: 1px solid #e8e5e0;
          margin-bottom: 1.75rem;
          width: 100%;
        }

        .success-footer a { color: #6b6760; text-decoration: none; }
        .success-footer a:hover { color: #1a1916; }
      `}</style>

      <div className="check-wrap">
        <svg className="check-icon" viewBox="0 0 24 24">
          <path className="check-path" d="M5 13l4 4L19 7" />
        </svg>
      </div>

      <h1 className="headline">
        You&apos;re <em>in</em>, welcome
        <br />
        to the club.
      </h1>
      <p className="subtext">
        Hey <strong>{firstName}</strong>, your subscription is <strong>active</strong>. Your project manager will
        reach out within the hour to get everything set up.
      </p>

      <div className="receipt-card">
        <div className="receipt-header">
          <div>
            <div className="receipt-label">Amount charged</div>
            <div className="receipt-amount">${amountTotal}</div>
          </div>
          <span className="badge-success">Payment confirmed</span>
        </div>
        <div className="receipt-rows">
          <div className="receipt-row">
            <span className="row-key">Plan</span>
            <span className="row-val">{planName}</span>
          </div>
          <div className="receipt-row">
            <span className="row-key">Billing cycle</span>
            <span className="row-val">{billingCycle}</span>
          </div>
          <div className="receipt-row">
            <span className="row-key">Date</span>
            <span className="row-val">{dateFormatted}</span>
          </div>
          <div className="receipt-row">
            <span className="row-key">Payment method</span>
            <span className="row-val">Card •••• {cardLast4}</span>
          </div>
          <div className="receipt-row">
            <span className="row-key">Receipt ID</span>
            <span className="row-val mono">{invoiceId}</span>
          </div>
        </div>
      </div>

      <div className="actions">
        <Link
          href={process.env.NEXT_PUBLIC_LOGIN_PORTAL_URL || "/"}
          className="btn-primary-sc"
        >
          Access your member portal →
        </Link>
      </div>

      <div className="next-steps">
        <div className="steps-label">What happens next</div>
        <div className="step-item">
          <div className="step-num">1</div>
          <div className="step-text">
            <strong>PM reaches out within the hour</strong>
            <p>
              Your dedicated project manager sets up your Notion board or Slack
              channel.
            </p>
          </div>
        </div>
        <div className="step-item">
          <div className="step-num">2</div>
          <div className="step-text">
            <strong>Queue your first request</strong>
            <p>
              Submit anything — landing pages, app UI, Webflow builds, brand
              work.
            </p>
          </div>
        </div>
        <div className="step-item">
          <div className="step-num">3</div>
          <div className="step-text">
            <strong>First delivery in ~48 hours</strong>
            <p>
              Designs land in Figma or live in Webflow. Unlimited revisions
              until perfect.
            </p>
          </div>
        </div>
      </div>

      <div className="success-footer">
        <hr />
        Questions?{" "}
        <a href="mailto:support@designshare.net">
          support@designshare.net
        </a>{" "}
        &nbsp;·&nbsp; <a href="https://designshare.net/privacy-policy" target="_blank" rel="noopener noreferrer">Privacy</a> &nbsp;·&nbsp; <a href="https://designshare.net/terms-conditions" target="_blank" rel="noopener noreferrer">Terms</a>
      </div>
    </div>
  );
}
