'use client'
import React, { useState, useEffect } from 'react'
import Image from 'next/image'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
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 { useCart } from '@/context/CartContext'
import { useSearchParams } from 'next/navigation';
import locationData from '@/data/locations.json'
import axios from 'axios'

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

const Checkout = () => {
    const router = useRouter()
    const searchParams = useSearchParams()
    let discount = searchParams.get('discount')
    let ship = searchParams.get('ship')

    const { cartState, clearCart } = useCart();
    const [cart, setCart] = useState<any[]>([])
    const [totalCart, setTotalCart] = useState<number>(0)
    const [activePayment, setActivePayment] = useState<string>('credit-card')
    const [selectedCountry, setSelectedCountry] = useState<string>('')
    const [availableStates, setAvailableStates] = useState<any[]>([])
    const [selectedState, setSelectedState] = useState<string>('')
    const [loading, setLoading] = useState<boolean>(false)

    // Form state
    const [formData, setFormData] = useState({
        firstName: '',
        lastName: '',
        email: '',
        phoneNumber: '',
        city: '',
        street: '',
        zipCode: '',
        note: ''
    })

    // Fetch cart data from API
    useEffect(() => {
        getCartData()
    }, [])

    // Calculate total whenever cart changes
    useEffect(() => {
        if (cart && cart.length > 0) {
            const total = cart.reduce((acc: number, item: any) => acc + (item.price * item.quantity), 0)
            setTotalCart(total)
        }
    }, [cart])

    const getCartData = async () => {
        const token = localStorage.getItem("token")
        if (!token) {
            console.error("❌ No token found in localStorage");
            return;
        }

        try {
            const res = await axios.get(`${BaseURL}/cart`, {
                headers: {
                    Authorization: `Bearer ${token}`,
                    "Content-Type": "application/json"
                },
                withCredentials: true
            })
            console.log("Cart response ✅:", res.data);
            setCart(res?.data?.cart?.items || [])
        } catch (error) {
            console.error("❌ Error fetching cart:", error)
        }
    }

    const handleCountryChange = (countryName: string) => {
        setSelectedCountry(countryName)
        const country = locationData.countries.find(c => c.name === countryName)
        setAvailableStates(country ? country.states : [])
        setSelectedState('')
    }

    const handlePayment = (item: string) => {
        setActivePayment(item)
    }

    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        setFormData({
            ...formData,
            [e.target.id]: e.target.value
        })
    }

    const handleSubmitOrder = async (e: React.FormEvent) => {
        e.preventDefault()
        setLoading(true)

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

            if (!token) {
                alert('Please login to place an order')
                router.push('/login')
                return
            }

            // Prepare shipping address
            const shippingAddress = {
                firstName: formData.firstName,
                lastName: formData.lastName,
                email: formData.email,
                phone: formData.phoneNumber,
                street: formData.street,
                city: formData.city,
                state: selectedState,
                country: selectedCountry,
                zipCode: formData.zipCode
            }

            // Determine payment method
            let paymentMethodValue = 'cash_on_delivery'
            if (activePayment === 'credit-card') {
                paymentMethodValue = 'credit_card'
            } else if (activePayment === 'stripe') {
                paymentMethodValue = 'credit_card'
            }

            // For Cash on Delivery - Create order directly
            if (activePayment === 'cash-delivery') {
                const orderData = {
                    shippingAddress,
                    paymentMethod: 'cash_on_delivery',
                    couponCode: discount || null,
                    shippingCost: Number(ship) || 0
                }

                const response = await axios.post(`${BaseURL}/orders`, orderData, {
                    headers: { Authorization: `Bearer ${token}` }
                })

                if (response.data.success) {
                    // Clear cart immediately after successful order
                    console.log("💳 Cash on Delivery order successful - clearing cart");
                    clearCart()
                    setCart([])
                    router.push(`/order-success?orderId=${response.data.data._id}&orderNumber=${response.data.data.orderNumber}`)
                }
            }
            // For Credit Card/Stripe - Create order first, then redirect to payment
            else if (activePayment === 'credit-card' || activePayment === 'stripe') {
                const orderData = {
                    shippingAddress,
                    paymentMethod: paymentMethodValue,
                    couponCode: discount || null,
                    shippingCost: Number(ship) || 0
                }

                const response = await axios.post(`${BaseURL}/orders`, orderData, {
                    headers: { Authorization: `Bearer ${token}` }
                })

                if (response.data.success) {
                    const orderId = response.data.data._id

                    // For Stripe - Redirect to Stripe payment page
                    if (activePayment === 'stripe') {
                        console.log("💳 Redirecting to Stripe payment page");
                        // TODO: Integrate with actual Stripe Checkout
                        // For now, redirect to a stripe payment page with order details
                        router.push(`/stripe-payment?orderId=${orderId}&orderNumber=${response.data.data.orderNumber}&amount=${totalCart - Number(discount) + Number(ship)}`)
                        return
                    }

                    // For Credit Card - Process payment directly
                    const paymentResult = {
                        id: `pay_${Date.now()}`,
                        status: 'completed',
                        update_time: new Date().toISOString(),
                        email_address: formData.email
                    }

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

                    // Clear cart immediately after successful order
                    console.log("💳 Credit Card/Stripe order successful - clearing cart");
                    clearCart()
                    setCart([])
                    router.push(`/order-success?orderId=${orderId}&orderNumber=${response.data.data.orderNumber}`)
                }
            }

        } catch (error: any) {
            console.error('Order error:', error)
            alert(error.response?.data?.error || 'Failed to place order. Please try again.')
        } 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" />
                <Breadcrumb heading='Checkout' subHeading='Checkout' />
            </div>
            <div className="cart-block md:py-20 py-10">
                <div className="container">
                    <div className="content-main flex justify-between max-xl:flex-col gap-y-8">
                        <div className="left xl:w-3/5 w-full xl:pr-12">
                            <div className="login bg-surface py-3 px-4 flex justify-between rounded-lg">
                                <div className="left flex items-center"><span className="text-on-surface-variant1 pr-4">Already have an account? </span><Link href="/login" className="text-button text-on-surface hover-underline cursor-pointer">Login</Link></div>
                                <div className="right"><i className="ph ph-caret-down fs-20 d-block cursor-pointer"></i></div>
                            </div>

                            <div className="information mt-5">
                                <div className="heading5">Information</div>
                                <div className="form-checkout mt-5">
                                    <form onSubmit={handleSubmitOrder}>
                                        <div className="grid sm:grid-cols-2 gap-4 gap-y-5 flex-wrap">
                                            <div className="">
                                                <input
                                                    className="border-line px-4 py-3 w-full rounded-lg"
                                                    id="firstName"
                                                    type="text"
                                                    placeholder="First Name *"
                                                    value={formData.firstName}
                                                    onChange={handleInputChange}
                                                    required
                                                />
                                            </div>
                                            <div className="">
                                                <input
                                                    className="border-line px-4 py-3 w-full rounded-lg"
                                                    id="lastName"
                                                    type="text"
                                                    placeholder="Last Name *"
                                                    value={formData.lastName}
                                                    onChange={handleInputChange}
                                                    required
                                                />
                                            </div>
                                            <div className="">
                                                <input
                                                    className="border-line px-4 py-3 w-full rounded-lg"
                                                    id="email"
                                                    type="email"
                                                    placeholder="Email Address *"
                                                    value={formData.email}
                                                    onChange={handleInputChange}
                                                    required
                                                />
                                            </div>
                                            <div className="">
                                                <input
                                                    className="border-line px-4 py-3 w-full rounded-lg"
                                                    id="phoneNumber"
                                                    type="tel"
                                                    placeholder="Phone Numbers *"
                                                    value={formData.phoneNumber}
                                                    onChange={handleInputChange}
                                                    required
                                                />
                                            </div>
                                            <div className="col-span-full select-block">
                                                <select
                                                    className="border border-line px-4 py-3 w-full rounded-lg"
                                                    id="region"
                                                    name="region"
                                                    value={selectedCountry}
                                                    onChange={(e) => handleCountryChange(e.target.value)}
                                                    required
                                                >
                                                    <option value="" disabled>Choose Country/Region</option>
                                                    {locationData.countries.map((country) => (
                                                        <option key={country.code} value={country.name}>{country.name}</option>
                                                    ))}
                                                </select>
                                                <Icon.CaretDown className='arrow-down' />
                                            </div>
                                            <div className="">
                                                <input
                                                    className="border-line px-4 py-3 w-full rounded-lg"
                                                    id="city"
                                                    type="text"
                                                    placeholder="Town/City *"
                                                    value={formData.city}
                                                    onChange={handleInputChange}
                                                    required
                                                />
                                            </div>
                                            <div className="">
                                                <input
                                                    className="border-line px-4 py-3 w-full rounded-lg"
                                                    id="street"
                                                    type="text"
                                                    placeholder="Street,..."
                                                    value={formData.street}
                                                    onChange={handleInputChange}
                                                    required
                                                />
                                            </div>
                                            <div className="select-block">
                                                <select
                                                    className="border border-line px-4 py-3 w-full rounded-lg"
                                                    id="state"
                                                    name="state"
                                                    value={selectedState}
                                                    onChange={(e) => setSelectedState(e.target.value)}
                                                    required
                                                >
                                                    <option value="" disabled>Choose State</option>
                                                    {availableStates.map((state) => (
                                                        <option key={state.name} value={state.name}>{state.name}</option>
                                                    ))}
                                                </select>
                                                <Icon.CaretDown className='arrow-down' />
                                            </div>
                                            <div className="">
                                                <input
                                                    className="border-line px-4 py-3 w-full rounded-lg"
                                                    id="zipCode"
                                                    type="text"
                                                    placeholder="Postal Code *"
                                                    value={formData.zipCode}
                                                    onChange={handleInputChange}
                                                    required
                                                />
                                            </div>
                                            <div className="col-span-full">
                                                <textarea
                                                    className="border border-line px-4 py-3 w-full rounded-lg"
                                                    id="note"
                                                    name="note"
                                                    placeholder="Write note..."
                                                    value={formData.note}
                                                    onChange={handleInputChange}
                                                ></textarea>
                                            </div>
                                        </div>
                                        <div className="payment-block md:mt-10 mt-6">
                                            <div className="heading5">Choose payment Option:</div>
                                            <div className="list-payment mt-5">
                                                <div className={`type bg-surface p-5 border border-line rounded-lg ${activePayment === 'credit-card' ? 'open' : ''}`}>
                                                    <input className="cursor-pointer" type="radio" id="credit" name="payment" checked={activePayment === 'credit-card'} onChange={() => handlePayment('credit-card')} />
                                                    <label className="text-button pl-2 cursor-pointer" htmlFor="credit">Credit Card</label>
                                                    {activePayment === 'credit-card' && (
                                                        <div className="infor">
                                                            <div className="text-on-surface-variant1 pt-4">Make your payment securely with your credit card. Your order will be processed after payment confirmation.</div>
                                                            <div className="row">
                                                                <div className="col-12 mt-3">
                                                                    <label htmlFor="cardNumberCredit">Card Numbers</label>
                                                                    <input className="cursor-pointer border-line px-4 py-3 w-full rounded mt-2" type="text" id="cardNumberCredit" placeholder="ex.1234567290" />
                                                                </div>
                                                                <div className=" mt-3">
                                                                    <label htmlFor="dateCredit">Date</label>
                                                                    <input className="border-line px-4 py-3 w-full rounded mt-2" type="date" id="dateCredit" name="date" />
                                                                </div>
                                                                <div className=" mt-3">
                                                                    <label htmlFor="ccvCredit">CCV</label>
                                                                    <input className="cursor-pointer border-line px-4 py-3 w-full rounded mt-2" type="text" id="ccvCredit" placeholder="****" />
                                                                </div>
                                                            </div>
                                                            <div className="flex items-center gap-2 mt-3">
                                                                <input type="checkbox" id="saveCredit" name="save" />
                                                                <label className="text-button" htmlFor="saveCredit">Save Card Details</label>
                                                            </div>
                                                        </div>
                                                    )}
                                                </div>
                                                <div className={`type bg-surface p-5 border border-line rounded-lg mt-5 ${activePayment === 'cash-delivery' ? 'open' : ''}`}>
                                                    <input className="cursor-pointer" type="radio" id="delivery" name="payment" checked={activePayment === 'cash-delivery'} onChange={() => handlePayment('cash-delivery')} />
                                                    <label className="text-button pl-2 cursor-pointer" htmlFor="delivery">Cash on Delivery</label>
                                                    {activePayment === 'cash-delivery' && (
                                                        <div className="infor">
                                                            <div className="text-on-surface-variant1 pt-4">Pay with cash upon delivery. Your order will be shipped and you can pay when it arrives.</div>
                                                        </div>
                                                    )}
                                                </div>
                                                <div className={`type bg-surface p-5 border border-line rounded-lg mt-5 ${activePayment === 'stripe' ? 'open' : ''}`}>
                                                    <input className="cursor-pointer" type="radio" id="stripe" name="payment" checked={activePayment === 'stripe'} onChange={() => handlePayment('stripe')} />
                                                    <label className="text-button pl-2 cursor-pointer" htmlFor="stripe">Stripe</label>
                                                    {activePayment === 'stripe' && (
                                                        <div className="infor">
                                                            <div className="text-on-surface-variant1 pt-4">Pay securely with Stripe. You will be redirected to Stripe's secure payment page to complete your purchase.</div>
                                                        </div>
                                                    )}
                                                </div>
                                            </div>
                                        </div>
                                        <div className="block-button md:mt-10 mt-6">
                                            <button
                                                type="submit"
                                                className="button-main w-full"
                                                disabled={loading}
                                            >
                                                {loading ? 'Processing...' : 'Place Order'}
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>

                        </div>
                        <div className="right xl:w-2/5 w-full xl:pl-12">
                            <div className="checkout-block bg-surface p-6 rounded-2xl">
                                <div className="heading5 pb-3">Your Order</div>
                                <div className="list-product-checkout">
                                    {cart.length < 1 ? (
                                        <p className='text-button pt-3'>No product in cart</p>
                                    ) : (
                                        cart.map((item, index) => (
                                            <div key={index} className="item flex items-center justify-between w-full pb-5 border-b border-line gap-6 mt-5">
                                                <div className="bg-img w-[100px] aspect-square flex-shrink-0 rounded-lg overflow-hidden">
                                                    <Image
                                                        src={item.product.thumbImage[0]}
                                                        width={500}
                                                        height={500}
                                                        alt='img'
                                                        className='w-full h-full'
                                                    />
                                                </div>
                                                <div className="flex items-center justify-between w-full">
                                                    <div>
                                                        <div className="name text-title">{item.product.name}</div>
                                                        <div className="caption1 text-secondary mt-2">
                                                            <span className='size capitalize'>{item.size}</span>
                                                            <span>/</span>
                                                            <span className='color capitalize'>{item.color}</span>
                                                        </div>
                                                    </div>
                                                    <div className="text-title">
                                                        <span className='quantity'>{item.quantity}</span>
                                                        <span className='px-1'>x</span>
                                                        <span>
                                                            ${item.price}.00
                                                        </span>
                                                    </div>
                                                </div>
                                            </div>
                                        ))
                                    )}
                                </div>
                                <div className="discount-block py-5 flex justify-between border-b border-line">
                                    <div className="text-title">Discounts</div>
                                    <div className="text-title"> <span>-$</span><span className="discount">{discount}</span><span>.00</span></div>
                                </div>
                                <div className="ship-block py-5 flex justify-between border-b border-line">
                                    <div className="text-title">Shipping</div>
                                    <div className="text-title">{Number(ship) === 0 ? 'Free' : `$${ship}.00`}</div>
                                </div>
                                <div className="total-cart-block pt-5 flex justify-between">
                                    <div className="heading5">Total</div>
                                    <div className="heading5 total-cart">${totalCart - Number(discount) + Number(ship)}.00</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <Footer />
        </>
    )
}

export default Checkout