'use client';

import { useEffect, useState } from 'react';
import { loadStripe } from '@stripe/stripe-js';
import {
  Elements,
  PaymentElement,
  useStripe,
  useElements,
} from '@stripe/react-stripe-js';

const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!);

function CheckoutForm({ clientSecret }: { clientSecret: string }) {
  const stripe = useStripe();
  const elements = useElements();
  const [errorMessage, setErrorMessage] = useState('');
  const [isProcessing, setIsProcessing] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!stripe || !elements) return;

    setIsProcessing(true);
    const { error } = await stripe.confirmPayment({
      elements,
      confirmParams: {
        return_url: `${window.location.origin}/payment-success`,
      },
    });

    if (error) {
      setErrorMessage(error.message || 'Payment failed.');
    }

    setIsProcessing(false);
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* <PaymentElement options={{ layout: 'tabs' }} /> */}

       <PaymentElement 
        options={{
          layout: 'tabs',
          defaultValues: {
            billingDetails: {
              email: '',
            },
          },
          // Indian regulations compliance: name and address must be collected for exports
          fields: {
            billingDetails: 'auto'
          }
        }}
       // onReady={() => setIsElementReady(true)}
       // onChange={() => { if (errorMessage) setErrorMessage(''); }}
      />

      {errorMessage && <p style={{ color: 'red' }}>{errorMessage}</p>}

      <button
        type="submit"
        disabled={!stripe || isProcessing}
        style={{
          marginTop: '16px',
          background: '#f97316',
          color: 'white',
          padding: '10px 20px',
          borderRadius: '6px',
        }}
      >
        {isProcessing ? 'Processing...' : 'Complete Payment'}
      </button>
    </form>
  );
}

export default function PaymentPage() {
  const [clientSecret, setClientSecret] = useState<string | null>(null);

  useEffect(() => {
    const createSubscription = async () => {
      const res = await fetch('/api/stripe/create-subscription', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          priceId: 'price_1SIC6gSu5FfZAHjvtycZLpc6',
          email: 'mahesh@example.com',
          name: 'Mahesh Yadav', // ✅ Required
          address: {
            line1: '123 MG Road',
            city: 'Jaipur',
            state: 'Rajasthan',
            postal_code: '302001',
            country: 'IN', // ✅ Must be valid ISO country code
          },

        }),
      });
      const data = await res.json();
      setClientSecret(data.clientSecret);
    };
    createSubscription();
  }, []);

  if (!clientSecret) return <p>Loading payment form...</p>;

  return (
    <Elements stripe={stripePromise} options={{ clientSecret }}>
      <CheckoutForm clientSecret={clientSecret} />
    </Elements>
  );
}




















































































// /api/stripe/webhook/route.ts

// import { NextResponse } from 'next/server';
// import { stripe } from '@/lib/stripe';
// import { buffer } from 'node:stream/consumers';
// import { prisma } from '@/lib/db';

// export const config = {
//   api: {
//     bodyParser: false, // must disable body parsing to verify signature
//   },
// };

// export async function POST(request: Request) {
//   const sig = request.headers.get('stripe-signature')!;
//   const buf = await request.arrayBuffer();
//   const payload = Buffer.from(buf);

//   let event: Stripe.Event;

//   try {
//     event = stripe.webhooks.constructEvent(payload, sig, process.env.STRIPE_WEBHOOK_SECRET!);
//   } catch (err: any) {
//     console.error('Webhook signature verification failed.', err.message);
//     return NextResponse.json({ error: 'Signature mismatch' }, { status: 400 });
//   }

//   // Handle the event
//   switch (event.type) {
//     case 'invoice.payment_succeeded': {
//       const invoice = event.data.object as Stripe.Invoice;
//       const subId = invoice.subscription as string;
//       // find user by subscription id
//       const user = await prisma.user.findFirst({
//         where: { stripeSubscriptionId: subId },
//       });
//       if (user) {
//         await prisma.user.update({
//           where: { id: user.id },
//           data: {
//             stripeStatus: 'active',
//             currentPeriodEnd: new Date(invoice.current_period_end! * 1000),
//           },
//         });
//       }
//       break;
//     }
//     case 'invoice.payment_failed': {
//       const invoice = event.data.object as Stripe.Invoice;
//       const subId = invoice.subscription as string;
//       const user = await prisma.user.findFirst({
//         where: { stripeSubscriptionId: subId },
//       });
//       if (user) {
//         await prisma.user.update({
//           where: { id: user.id },
//           data: {
//             stripeStatus: 'past_due',
//           },
//         });
//       }
//       break;
//     }
//     case 'customer.subscription.deleted':
//     case 'customer.subscription.updated': {
//       const subscription = event.data.object as Stripe.Subscription;
//       const user = await prisma.user.findFirst({
//         where: { stripeSubscriptionId: subscription.id },
//       });
//       if (user) {
//         await prisma.user.update({
//           where: { id: user.id },
//           data: {
//             stripeStatus: subscription.status,
//             currentPeriodEnd: new Date(subscription.current_period_end * 1000),
//           },
//         });
//       }
//       break;
//     }
//     default:
//       console.log(`Unhandled event type ${event.type}`);
//   }

//   return NextResponse.json({ received: true });
// }




