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

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

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

    const [order, setOrder] = useState<any>(null)
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        if (orderId) {
            fetchOrderDetails()
        }
    }, [orderId])

    const fetchOrderDetails = async () => {
        try {
            const token = localStorage.getItem('token')
            const response = await axios.get(`${BaseURL}/orders/${orderId}`, {
                headers: { Authorization: `Bearer ${token}` }
            })

            if (response.data.success) {
                setOrder(response.data.data)
            }
        } catch (error) {
            console.error('Error fetching order:', error)
        } finally {
            setLoading(false)
        }
    }

    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" />
            </div>
            <div className="order-success-block md:py-20 py-10">
                <div className="container">
                    <div className="content-main flex flex-col items-center">
                        {loading ? (
                            <div className="text-center">
                                <div className="text-title">Loading order details...</div>
                            </div>
                        ) : (
                            <>
                                <div className="icon-success w-20 h-20 bg-green rounded-full flex items-center justify-center mb-6">
                                    <Icon.CheckCircle size={48} weight="fill" className="text-white" />
                                </div>

                                <div className="heading3 text-center mb-2">Order Placed Successfully!</div>
                                <div className="text-secondary text-center mb-8">
                                    Thank you for your order. We'll send you a confirmation email shortly.
                                </div>

                                <div className="order-info bg-surface p-8 rounded-2xl w-full max-w-2xl mb-8">
                                    <div className="flex justify-between items-center pb-6 border-b border-line">
                                        <div>
                                            <div className="text-secondary">Order Number</div>
                                            <div className="heading5 mt-1">{orderNumber}</div>
                                        </div>
                                        <div className="text-right">
                                            <div className="text-secondary">Order Date</div>
                                            <div className="text-title mt-1">
                                                {order && new Date(order.createdAt).toLocaleDateString('en-US', {
                                                    year: 'numeric',
                                                    month: 'long',
                                                    day: 'numeric'
                                                })}
                                            </div>
                                        </div>
                                    </div>

                                    {order && (
                                        <>
                                            <div className="order-items mt-6">
                                                <div className="heading6 mb-4">Order Items</div>
                                                {order.items.map((item: any, index: number) => (
                                                    <div key={index} className="item flex items-center gap-4 pb-4 mb-4 border-b border-line">
                                                        <div className="bg-img w-20 h-20 rounded-lg overflow-hidden flex-shrink-0">
                                                            <Image
                                                                src={item.product.thumbImage[0]}
                                                                width={80}
                                                                height={80}
                                                                alt={item.product.name}
                                                                className="w-full h-full object-cover"
                                                            />
                                                        </div>
                                                        <div className="flex-1">
                                                            <div className="text-title">{item.product.name}</div>
                                                            <div className="text-secondary mt-1">
                                                                <span className="capitalize">{item.size}</span>
                                                                <span> / </span>
                                                                <span className="capitalize">{item.color}</span>
                                                            </div>
                                                        </div>
                                                        <div className="text-right">
                                                            <div className="text-title">Qty: {item.quantity}</div>
                                                            <div className="text-title mt-1">${item.price}.00</div>
                                                        </div>
                                                    </div>
                                                ))}
                                            </div>

                                            <div className="order-summary mt-6 pt-6 border-t border-line">
                                                <div className="flex justify-between mb-3">
                                                    <div className="text-secondary">Subtotal</div>
                                                    <div className="text-title">${order.subtotal}.00</div>
                                                </div>
                                                {order.discount > 0 && (
                                                    <div className="flex justify-between mb-3">
                                                        <div className="text-secondary">Discount</div>
                                                        <div className="text-title text-green">-${order.discount}.00</div>
                                                    </div>
                                                )}
                                                <div className="flex justify-between mb-3">
                                                    <div className="text-secondary">Shipping</div>
                                                    <div className="text-title">
                                                        {order.shippingCost === 0 ? 'Free' : `$${order.shippingCost}.00`}
                                                    </div>
                                                </div>
                                                <div className="flex justify-between pt-3 border-t border-line">
                                                    <div className="heading6">Total</div>
                                                    <div className="heading6">${order.totalPrice}.00</div>
                                                </div>
                                            </div>

                                            <div className="shipping-info mt-6 pt-6 border-t border-line">
                                                <div className="heading6 mb-4">Shipping Address</div>
                                                <div className="text-secondary">
                                                    {order.shippingAddress.firstName} {order.shippingAddress.lastName}
                                                </div>
                                                <div className="text-secondary mt-1">
                                                    {order.shippingAddress.street}
                                                </div>
                                                <div className="text-secondary mt-1">
                                                    {order.shippingAddress.city}, {order.shippingAddress.state} {order.shippingAddress.zipCode}
                                                </div>
                                                <div className="text-secondary mt-1">
                                                    {order.shippingAddress.country}
                                                </div>
                                                <div className="text-secondary mt-2">
                                                    Phone: {order.shippingAddress.phone}
                                                </div>
                                                <div className="text-secondary mt-1">
                                                    Email: {order.shippingAddress.email}
                                                </div>
                                            </div>

                                            <div className="payment-info mt-6 pt-6 border-t border-line">
                                                <div className="heading6 mb-4">Payment Method</div>
                                                <div className="text-secondary capitalize">
                                                    {order.paymentMethod.replace('_', ' ')}
                                                </div>
                                                <div className={`mt-2 ${order.isPaid ? 'text-green' : 'text-secondary'}`}>
                                                    {order.isPaid ? '✓ Paid' : 'Payment Pending'}
                                                </div>
                                            </div>
                                        </>
                                    )}
                                </div>

                                <div className="action-buttons flex gap-4">
                                    <Link href="/shop" className="button-main">
                                        Continue Shopping
                                    </Link>
                                    <Link href="/my-account" className="button-main bg-white text-black border border-black hover:bg-black hover:text-white">
                                        View My Orders
                                    </Link>
                                </div>
                            </>
                        )}
                    </div>
                </div>
            </div>
            <Footer />
        </>
    )
}

export default OrderSuccess
