'use client'
import React, { useState, useEffect } from 'react'
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 Breadcrumb from '@/components/Breadcrumb/Breadcrumb'
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 MyAccount = () => {
    const [activeTab, setActiveTab] = useState<string>('dashboard')
    const [activeAddress, setActiveAddress] = useState<string | null>('billing')
    const [activeOrders, setActiveOrders] = useState<string>('all')
    const [openDetail, setOpenDetail] = useState<boolean>(false)
    const [orders, setOrders] = useState<any[]>([])
    const [loading, setLoading] = useState<boolean>(true)
    const [selectedOrder, setSelectedOrder] = useState<any>(null)
    const [user, setUser] = useState<any>(null)

    // Fetch user profile and orders on component mount
    useEffect(() => {
        fetchUserProfile()
        fetchOrders()
    }, [])

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

        try {
            const res = await axios.get(`${BaseURL}/users/profile`, {
                headers: {
                    Authorization: `Bearer ${token}`,
                    "Content-Type": "application/json"
                }
            })
            console.log("User profile response ✅:", res.data);
            if (res.data.success) {
                setUser(res.data.data)
            }
        } catch (error) {
            console.error("❌ Error fetching user profile:", error)
        }
    }

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

        try {
            const res = await axios.get(`${BaseURL}/orders/myorders`, {
                headers: {
                    Authorization: `Bearer ${token}`,
                    "Content-Type": "application/json"
                }
            })
            console.log("Orders response ✅:", res.data);
            if (res.data.success) {
                setOrders(res.data.data || [])
            }
        } catch (error) {
            console.error("❌ Error fetching orders:", error)
        } finally {
            setLoading(false)
        }
    }

    const handleActiveAddress = (address: string) => {
        setActiveAddress(prevAddress => prevAddress === address ? null : address)
    }

    const handleActiveOrders = (order: string) => {
        setActiveOrders(order)
    }

    // Filter orders by status
    const getFilteredOrders = () => {
        if (activeOrders === 'all') return orders
        return orders.filter(order => order.status.toLowerCase() === activeOrders)
    }

    // Get order counts by status
    const getOrderCounts = () => {
        return {
            pending: orders.filter(o => o.status === 'pending').length,
            processing: orders.filter(o => o.status === 'processing').length,
            shipped: orders.filter(o => o.status === 'shipped').length,
            delivered: orders.filter(o => o.status === 'delivered').length,
            cancelled: orders.filter(o => o.status === 'cancelled').length,
            total: orders.length
        }
    }

    const counts = getOrderCounts()

    // Get status badge color
    const getStatusColor = (status: string) => {
        switch (status.toLowerCase()) {
            case 'pending':
                return 'bg-yellow text-yellow'
            case 'processing':
                return 'bg-purple text-purple'
            case 'shipped':
                return 'bg-blue text-blue'
            case 'delivered':
                return 'bg-success text-success'
            case 'cancelled':
                return 'bg-red text-red'
            default:
                return 'bg-secondary text-secondary'
        }
    }

    const handleViewOrderDetail = (order: any) => {
        setSelectedOrder(order)
        setOpenDetail(true)
    }

    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='My Account' subHeading='My Account' />
            </div>
            <div className="profile-block md:py-20 py-10">
                <div className="container">
                    <div className="content-main flex gap-y-8 max-md:flex-col w-full">
                        <div className="left md:w-1/3 w-full xl:pr-[3.125rem] lg:pr-[28px] md:pr-[16px]">
                            <div className="user-infor bg-surface lg:px-7 px-4 lg:py-10 py-5 md:rounded-[20px] rounded-xl">
                                <div className="heading flex flex-col items-center justify-center">
                                    <div className="avatar">
                                        <Image
                                            src={'/images/avatar/1.png'}
                                            width={300}
                                            height={300}
                                            alt='avatar'
                                            className='md:w-[140px] w-[120px] md:h-[140px] h-[120px] rounded-full'
                                        />
                                    </div>
                                    <div className="name heading6 mt-4 text-center">{user?.name || 'User'}</div>
                                    <div className="mail heading6 font-normal normal-case text-secondary text-center mt-1">{user?.email || 'user@example.com'}</div>
                                </div>
                                <div className="menu-tab w-full max-w-none lg:mt-10 mt-6">
                                    <Link href={'#!'} scroll={false} className={`item flex items-center gap-3 w-full px-5 py-4 rounded-lg cursor-pointer duration-300 hover:bg-white ${activeTab === 'dashboard' ? 'active' : ''}`} onClick={() => setActiveTab('dashboard')}>
                                        <Icon.HouseLine size={20} />
                                        <strong className="heading6">Dashboard</strong>
                                    </Link>
                                    <Link href={'#!'} scroll={false} className={`item flex items-center gap-3 w-full px-5 py-4 rounded-lg cursor-pointer duration-300 hover:bg-white mt-1.5 ${activeTab === 'orders' ? 'active' : ''}`} onClick={() => setActiveTab('orders')}>
                                        <Icon.Package size={20} />
                                        <strong className="heading6">History Orders</strong>
                                    </Link>
                                    <Link href={'#!'} scroll={false} className={`item flex items-center gap-3 w-full px-5 py-4 rounded-lg cursor-pointer duration-300 hover:bg-white mt-1.5 ${activeTab === 'address' ? 'active' : ''}`} onClick={() => setActiveTab('address')}>
                                        <Icon.Tag size={20} />
                                        <strong className="heading6">My Address</strong>
                                    </Link>
                                    <Link href={'#!'} scroll={false} className={`item flex items-center gap-3 w-full px-5 py-4 rounded-lg cursor-pointer duration-300 hover:bg-white mt-1.5 ${activeTab === 'setting' ? 'active' : ''}`} onClick={() => setActiveTab('setting')}>
                                        <Icon.GearSix size={20} />
                                        <strong className="heading6">Setting</strong>
                                    </Link>
                                    <Link href={'/login'} className="item flex items-center gap-3 w-full px-5 py-4 rounded-lg cursor-pointer duration-300 hover:bg-white mt-1.5">
                                        <Icon.SignOut size={20} />
                                        <strong className="heading6">Logout</strong>
                                    </Link>
                                </div>
                            </div>
                        </div>
                        <div className="right md:w-2/3 w-full pl-2.5">
                            {/* Dashboard Tab */}
                            <div className={`tab text-content w-full ${activeTab === 'dashboard' ? 'block' : 'hidden'}`}>
                                <div className="overview grid sm:grid-cols-3 gap-5">
                                    <div className="item flex items-center justify-between p-5 border border-line rounded-lg box-shadow-xs">
                                        <div className="counter">
                                            <span className="text-secondary">Processing Orders</span>
                                            <h5 className="heading5 mt-1">{counts.processing}</h5>
                                        </div>
                                        <Icon.HourglassMedium className='text-4xl' />
                                    </div>
                                    <div className="item flex items-center justify-between p-5 border border-line rounded-lg box-shadow-xs">
                                        <div className="counter">
                                            <span className="text-secondary">Cancelled Orders</span>
                                            <h5 className="heading5 mt-1">{counts.cancelled}</h5>
                                        </div>
                                        <Icon.ReceiptX className='text-4xl' />
                                    </div>
                                    <div className="item flex items-center justify-between p-5 border border-line rounded-lg box-shadow-xs">
                                        <div className="counter">
                                            <span className="text-secondary">Total Orders</span>
                                            <h5 className="heading5 mt-1">{counts.total}</h5>
                                        </div>
                                        <Icon.Package className='text-4xl' />
                                    </div>
                                </div>
                                <div className="recent_order pt-5 px-5 pb-2 mt-7 border border-line rounded-xl">
                                    <h6 className="heading6">Recent Orders</h6>
                                    {loading ? (
                                        <div className="text-center py-10">Loading orders...</div>
                                    ) : orders.length === 0 ? (
                                        <div className="text-center py-10">No orders found</div>
                                    ) : (
                                        <div className="list overflow-x-auto w-full mt-5">
                                            <table className="w-full max-[1400px]:w-[700px] max-md:w-[700px]">
                                                <thead className="border-b border-line">
                                                    <tr>
                                                        <th scope="col" className="pb-3 text-left text-sm font-bold uppercase text-secondary whitespace-nowrap">Order</th>
                                                        <th scope="col" className="pb-3 text-left text-sm font-bold uppercase text-secondary whitespace-nowrap">Products</th>
                                                        <th scope="col" className="pb-3 text-left text-sm font-bold uppercase text-secondary whitespace-nowrap">Total</th>
                                                        <th scope="col" className="pb-3 text-right text-sm font-bold uppercase text-secondary whitespace-nowrap">Status</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    {orders.slice(0, 6).map((order, index) => (
                                                        <tr key={index} className="item duration-300 border-b border-line">
                                                            <th scope="row" className="py-3 text-left">
                                                                <strong className="text-title">{order.orderNumber}</strong>
                                                            </th>
                                                            <td className="py-3">
                                                                {order.items && order.items.length > 0 && (
                                                                    <div className="product flex items-center gap-3">
                                                                        <Image
                                                                            src={order.items[0].product.thumbImage[0]}
                                                                            width={48}
                                                                            height={48}
                                                                            alt={order.items[0].product.name}
                                                                            className="flex-shrink-0 w-12 h-12 rounded"
                                                                        />
                                                                        <div className="info flex flex-col">
                                                                            <strong className="product_name text-button">{order.items[0].product.name}</strong>
                                                                            <span className="product_tag caption1 text-secondary">
                                                                                {order.items.length > 1 && `+${order.items.length - 1} more`}
                                                                            </span>
                                                                        </div>
                                                                    </div>
                                                                )}
                                                            </td>
                                                            <td className="py-3 price">${order.totalPrice}.00</td>
                                                            <td className="py-3 text-right">
                                                                <span className={`tag px-4 py-1.5 rounded-full bg-opacity-10 ${getStatusColor(order.status)} caption1 font-semibold capitalize`}>
                                                                    {order.status}
                                                                </span>
                                                            </td>
                                                        </tr>
                                                    ))}
                                                </tbody>
                                            </table>
                                        </div>
                                    )}
                                </div>
                            </div>

                            {/* Orders Tab */}
                            <div className={`tab text-content overflow-hidden w-full p-7 border border-line rounded-xl ${activeTab === 'orders' ? 'block' : 'hidden'}`}>
                                <h6 className="heading6">Your Orders</h6>
                                <div className="w-full overflow-x-auto">
                                    <div className="menu-tab grid grid-cols-5 max-lg:w-[500px] border-b border-line mt-3">
                                        {['all', 'pending', 'processing', 'delivered', 'cancelled'].map((item, index) => (
                                            <button
                                                key={index}
                                                className={`item relative px-3 py-2.5 text-secondary text-center duration-300 hover:text-black border-b-2 ${activeOrders === item ? 'active border-black' : 'border-transparent'}`}
                                                onClick={() => handleActiveOrders(item)}
                                            >
                                                <span className='relative text-button z-[1] capitalize'>
                                                    {item}
                                                </span>
                                            </button>
                                        ))}
                                    </div>
                                </div>
                                <div className="list_order">
                                    {loading ? (
                                        <div className="text-center py-10">Loading orders...</div>
                                    ) : getFilteredOrders().length === 0 ? (
                                        <div className="text-center py-10">No orders found</div>
                                    ) : (
                                        getFilteredOrders().map((order, orderIndex) => (
                                            <div key={orderIndex} className="order_item mt-5 border border-line rounded-lg box-shadow-xs">
                                                <div className="flex flex-wrap items-center justify-between gap-4 p-5 border-b border-line">
                                                    <div className="flex items-center gap-2">
                                                        <strong className="text-title">Order Number:</strong>
                                                        <strong className="order_number text-button uppercase">{order.orderNumber}</strong>
                                                    </div>
                                                    <div className="flex items-center gap-2">
                                                        <strong className="text-title">Order status:</strong>
                                                        <span className={`tag px-4 py-1.5 rounded-full bg-opacity-10 ${getStatusColor(order.status)} caption1 font-semibold capitalize`}>
                                                            {order.status}
                                                        </span>
                                                    </div>
                                                </div>
                                                <div className="list_prd px-5">
                                                    {order.items && order.items.map((item: any, itemIndex: number) => (
                                                        <div key={itemIndex} className="prd_item flex flex-wrap items-center justify-between gap-3 py-5 border-b border-line">
                                                            <div className="flex items-center gap-5">
                                                                <div className="bg-img flex-shrink-0 md:w-[100px] w-20 aspect-square rounded-lg overflow-hidden">
                                                                    <Image
                                                                        src={item.product.thumbImage[0]}
                                                                        width={100}
                                                                        height={100}
                                                                        alt={item.product.name}
                                                                        className='w-full h-full object-cover'
                                                                    />
                                                                </div>
                                                                <div>
                                                                    <div className="prd_name text-title">{item.product.name}</div>
                                                                    <div className="caption1 text-secondary mt-2">
                                                                        <span className="prd_size uppercase">{item.size}</span>
                                                                        <span>/</span>
                                                                        <span className="prd_color capitalize">{item.color}</span>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div className='text-title'>
                                                                <span className="prd_quantity">{item.quantity}</span>
                                                                <span> X </span>
                                                                <span className="prd_price">${item.price}.00</span>
                                                            </div>
                                                        </div>
                                                    ))}
                                                </div>
                                                <div className="flex flex-wrap gap-4 p-5">
                                                    <button className="button-main" onClick={() => handleViewOrderDetail(order)}>Order Details</button>
                                                    {order.status === 'pending' && (
                                                        <button className="button-main bg-surface border border-line hover:bg-black text-black hover:text-white">Cancel Order</button>
                                                    )}
                                                </div>
                                            </div>
                                        ))
                                    )}
                                </div>
                            </div>

                            {/* Address Tab - Placeholder */}
                            <div className={`tab_address text-content w-full p-7 border border-line rounded-xl ${activeTab === 'address' ? 'block' : 'hidden'}`}>
                                <h6 className="heading6">My Address</h6>
                                <p className="text-secondary mt-4">Address management coming soon...</p>
                            </div>

                            {/* Settings Tab - Placeholder */}
                            <div className={`tab text-content w-full p-7 border border-line rounded-xl ${activeTab === 'setting' ? 'block' : 'hidden'}`}>
                                <h6 className="heading6">Account Settings</h6>
                                <p className="text-secondary mt-4">Settings management coming soon...</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <Footer />

            {/* Order Detail Modal */}
            <div className={`modal-order-detail-block flex items-center justify-center ${openDetail ? 'open' : ''}`} onClick={() => setOpenDetail(false)}>
                <div className={`modal-order-detail-main grid grid-cols-2 max-w-[1160px] w-full bg-white rounded-2xl ${openDetail ? 'open' : ''}`} onClick={(e) => e.stopPropagation()}>
                    {selectedOrder && (
                        <>
                            <div className="info p-10 border-r border-line">
                                <h5 className="heading5">Order Details</h5>
                                <div className="list_info grid grid-cols-2 gap-10 gap-y-8 mt-5">
                                    <div className="info_item">
                                        <strong className="text-button-uppercase text-secondary">Contact Information</strong>
                                        <h6 className="heading6 order_name mt-2">{selectedOrder.shippingAddress.firstName} {selectedOrder.shippingAddress.lastName}</h6>
                                        <h6 className="heading6 order_phone mt-2">{selectedOrder.shippingAddress.phone}</h6>
                                        <h6 className="heading6 normal-case order_email mt-2">{selectedOrder.shippingAddress.email}</h6>
                                    </div>
                                    <div className="info_item">
                                        <strong className="text-button-uppercase text-secondary">Payment method</strong>
                                        <h6 className="heading6 order_payment mt-2 capitalize">{selectedOrder.paymentMethod.replace('_', ' ')}</h6>
                                    </div>
                                    <div className="info_item col-span-2">
                                        <strong className="text-button-uppercase text-secondary">Shipping address</strong>
                                        <h6 className="heading6 order_shipping_address mt-2">
                                            {selectedOrder.shippingAddress.street}, {selectedOrder.shippingAddress.city}, {selectedOrder.shippingAddress.state} {selectedOrder.shippingAddress.zipCode}, {selectedOrder.shippingAddress.country}
                                        </h6>
                                    </div>
                                </div>
                            </div>
                            <div className="list p-10">
                                <h5 className="heading5">Items</h5>
                                <div className="list_prd">
                                    {selectedOrder.items && selectedOrder.items.map((item: any, index: number) => (
                                        <div key={index} className="prd_item flex flex-wrap items-center justify-between gap-3 py-5 border-b border-line">
                                            <div className="flex items-center gap-5">
                                                <div className="bg-img flex-shrink-0 md:w-[100px] w-20 aspect-square rounded-lg overflow-hidden">
                                                    <Image
                                                        src={item.product.thumbImage[0]}
                                                        width={100}
                                                        height={100}
                                                        alt={item.product.name}
                                                        className='w-full h-full object-cover'
                                                    />
                                                </div>
                                                <div>
                                                    <div className="prd_name text-title">{item.product.name}</div>
                                                    <div className="caption1 text-secondary mt-2">
                                                        <span className="prd_size uppercase">{item.size}</span>
                                                        <span>/</span>
                                                        <span className="prd_color capitalize">{item.color}</span>
                                                    </div>
                                                </div>
                                            </div>
                                            <div className='text-title'>
                                                <span className="prd_quantity">{item.quantity}</span>
                                                <span> X </span>
                                                <span className="prd_price">${item.price}.00</span>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                                <div className="flex items-center justify-between mt-5">
                                    <strong className="text-title">Shipping</strong>
                                    <strong className="order_ship text-title">${selectedOrder.shippingCost}.00</strong>
                                </div>
                                <div className="flex items-center justify-between mt-4">
                                    <strong className="text-title">Discounts</strong>
                                    <strong className="order_discounts text-title">-${selectedOrder.discount}.00</strong>
                                </div>
                                <div className="flex items-center justify-between mt-5 pt-5 border-t border-line">
                                    <h5 className="heading5">Subtotal</h5>
                                    <h5 className="order_total heading5">${selectedOrder.totalPrice}.00</h5>
                                </div>
                            </div>
                        </>
                    )}
                </div>
            </div>
        </>
    )
}

export default MyAccount