'use client'
import React, { useState, useEffect } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import Link from 'next/link'
import TopNavOne from '@/components/Header/TopNav/TopNavOne'
import MenuOne from '@/components/Header/Menu/MenuOne'
import Breadcrumb from '@/components/Breadcrumb/Breadcrumb'
import Footer from '@/components/Footer/Footer'
import * as Icon from "@phosphor-icons/react/dist/ssr";
import axios from 'axios'
import { useCart } from '@/context/CartContext'

const BaseURL = 'http://localhost:5000/api'

const StripePayment = () => {
    const router = useRouter()
    const searchParams = useSearchParams()
    const orderId = searchParams.get('orderId')
    const orderNumber = searchParams.get('orderNumber')
    const amount = searchParams.get('amount')

    const { clearCart } = useCart()
    const [loading, setLoading] = useState(false)
    const [paymentProcessing, setPaymentProcessing] = useState(false)

    const handlePayment = async () => {
        setPaymentProcessing(true)

        try {
            const token = localStorage.getItem('token')

            // Simulate Stripe payment processing
            // TODO: Integrate with actual Stripe API
            await new Promise(resolve => setTimeout(resolve, 2000))

            const paymentResult = {
                id: `stripe_${Date.now()}`,
                status: 'completed',
                update_time: new Date().toISOString(),
                payment_method: 'stripe'
            }

            // Update order payment status
            await axios.put(`${BaseURL}/orders/${orderId}/pay`,
                { paymentResult },
                { headers: { Authorization: `Bearer ${token}` } }
            )

            // Clear cart after successful payment
            clearCart()

            // Redirect to success page
            router.push(`/order-success?orderId=${orderId}&orderNumber=${orderNumber}`)

        } catch (error) {
            console.error('Payment error:', error)
            alert('Payment failed. Please try again.')
        } finally {
            setPaymentProcessing(false)
        }
    }

    const handleCancel = () => {
        router.push('/checkout')
    }

    return (
        <>
            <TopNavOne props="style-one bg-black" slogan="New customers save 10% with the code GET10" />
            <div id="header" className='relative w-full'>
                <MenuOne props="bg-transparent" />
                <Breadcrumb heading='Stripe Payment' subHeading='Stripe Payment' />
            </div>
            <div className="payment-block md:py-20 py-10">
                <div className="container">
                    <div className="content-main flex justify-center">
                        <div className="max-w-[600px] w-full">
                            <div className="payment-card bg-surface p-8 rounded-2xl border border-line">
                                <div className="heading flex items-center justify-center mb-6">
                                    <Icon.CreditCard size={48} className="text-blue" />
                                </div>
                                <h3 className="heading3 text-center mb-2">Stripe Payment</h3>
                                <p className="text-center text-secondary mb-8">Complete your secure payment with Stripe</p>

                                <div className="order-details bg-white p-6 rounded-lg mb-6">
                                    <div className="flex justify-between items-center mb-3">
                                        <span className="text-secondary">Order Number:</span>
                                        <strong className="text-title">{orderNumber}</strong>
                                    </div>
                                    <div className="flex justify-between items-center">
                                        <span className="text-secondary">Amount to Pay:</span>
                                        <strong className="heading5">${amount}.00</strong>
                                    </div>
                                </div>

                                <div className="stripe-info bg-blue bg-opacity-10 p-4 rounded-lg mb-6">
                                    <div className="flex items-start gap-3">
                                        <Icon.ShieldCheck size={24} className="text-blue flex-shrink-0 mt-1" />
                                        <div>
                                            <strong className="text-title block mb-1">Secure Payment</strong>
                                            <p className="text-secondary text-sm">Your payment information is encrypted and secure. Stripe is a PCI-DSS compliant payment processor trusted by millions of businesses worldwide.</p>
                                        </div>
                                    </div>
                                </div>

                                <div className="stripe-placeholder bg-white p-6 rounded-lg mb-6 border-2 border-dashed border-line">
                                    <div className="text-center text-secondary">
                                        <Icon.CreditCard size={48} className="mx-auto mb-3 opacity-50" />
                                        <p className="mb-2">Stripe Checkout will be integrated here</p>
                                        <p className="text-sm">For demo purposes, click "Pay Now" to simulate payment</p>
                                    </div>
                                </div>

                                <div className="button-group flex gap-4">
                                    <button
                                        onClick={handleCancel}
                                        className="button-main bg-surface border border-line hover:bg-black text-black hover:text-white flex-1"
                                        disabled={paymentProcessing}
                                    >
                                        Cancel
                                    </button>
                                    <button
                                        onClick={handlePayment}
                                        className="button-main flex-1"
                                        disabled={paymentProcessing}
                                    >
                                        {paymentProcessing ? (
                                            <span className="flex items-center justify-center gap-2">
                                                <Icon.CircleNotch size={20} className="animate-spin" />
                                                Processing...
                                            </span>
                                        ) : (
                                            'Pay Now'
                                        )}
                                    </button>
                                </div>

                                <div className="security-badges flex items-center justify-center gap-4 mt-6 pt-6 border-t border-line">
                                    <div className="flex items-center gap-2 text-secondary text-sm">
                                        <Icon.Lock size={16} />
                                        <span>SSL Encrypted</span>
                                    </div>
                                    <div className="flex items-center gap-2 text-secondary text-sm">
                                        <Icon.ShieldCheck size={16} />
                                        <span>PCI Compliant</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <Footer />
        </>
    )
}

export default StripePayment
