"use client"
import React, { useEffect, useState } from 'react';
import DashboardLayout from '@/app/dashboard/layout';
import { Phone, Calendar, Loader2, ShoppingBag, Banknote, CreditCard, QrCode } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Card } from '@/components/ui/card';
import apis from '@/utils/apis';
import { useGlobalContext } from '@/context/Provider';
import { format, isToday } from 'date-fns';
import { currency } from '@/lib/utils';

import { useSearchParams, useRouter } from 'next/navigation';
import PaginationCompo from '@/components/common/pagination';

const OrderCard = ({ order }: { order: any }) => {
    const [showAllItems, setShowAllItems] = useState(false);
    const allItems = [...(order.cart_items || []), ...(order.other_cart_items || [])];
    const displayedItems = showAllItems ? allItems : allItems.slice(0, 2);
    const hasMoreItems = allItems.length > 2;

    return (
        <Card className="flex flex-col border-none bg-white p-5 shadow-[0px_4px_20px_0px_rgba(0,0,0,0.05)] rounded-2xl hover:shadow-[0px_8px_30px_0px_rgba(0,0,0,0.08)] transition-all">
            {/* Header */}
            <div className="flex items-center justify-between mb-2">
                <span className="text-sm font-medium text-[#999999]"># {order.order_id}</span>
                <Badge variant="secondary" className="bg-[#E7F7EF] text-[#0FAF62] border-none flex items-center gap-1.5 px-3 py-1 hover:bg-[#D7EFE3] transition-colors">
                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12.25 4.08331H1.75C1.10567 4.08331 0.583336 4.60565 0.583336 5.24998V11.0833C0.583336 11.7276 1.10567 12.25 1.75 12.25H12.25C12.8943 12.25 13.4167 11.7276 13.4167 11.0833V5.24998C13.4167 4.60565 12.8943 4.08331 12.25 4.08331Z" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" />
                        <circle cx="7" cy="8.16667" r="1.16667" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" />
                        <rect x="2.91666" y="5.83331" width="1.16667" height="1.16667" rx="0.583333" fill="currentColor" />
                        <rect x="9.91666" y="5.83331" width="1.16667" height="1.16667" rx="0.583333" fill="currentColor" />
                    </svg>
                    <span className="font-semibold text-xs capitalize">{order.payment_type || 'Cash'}</span>
                </Badge>
            </div>

            <h2 className="mb-6 text-xl font-bold text-[var(--orange-500)] line-clamp-1 h-7">
                {order.add_receiver_detail?.name || order.customer_id?.name || 'Walk-in Customer'}
            </h2>

            {/* Items */}
            <div className="mb-6 flex-1">
                <h3 className="mb-4 text-[10px] font-bold uppercase tracking-widest text-[#999999]">ITEMS</h3>
                <div className="space-y-4">
                    {displayedItems.map((item: any, idx: number) => {
                        const displayUnit = item.unit?.toLowerCase().includes(item.quantity?.toString().toLowerCase())
                            ? item.unit
                            : `${item.quantity || ''} ${item.unit || ''}`.trim();

                        return (
                            <div key={idx} className="flex flex-col">
                                <div className="flex items-center justify-between">
                                    <span className="text-sm font-semibold text-[#121212]">{item.no_of_quantity}x {item.name}</span>
                                    <span className="text-sm font-bold text-[#121212]">{currency}{(item?.total_price !== undefined && item?.total_price !== null ? Number(item.total_price) : item.price * item.no_of_quantity).toFixed(2)}</span>
                                </div>
                                {displayUnit && (
                                    <div className="mt-1">
                                        <span className="inline-block bg-[#FFF1E5] text-[var(--orange-500)] text-[10px] font-bold py-0.5 px-2 rounded capitalize">
                                            {displayUnit}
                                        </span>
                                    </div>
                                )}
                            </div>
                        );
                    })}
                </div>

                {hasMoreItems && (
                    <button
                        onClick={() => setShowAllItems(!showAllItems)}
                        className="mt-4 text-xs font-semibold text-[var(--orange-500)] hover:underline flex items-center gap-1 focus:outline-none"
                    >
                        {showAllItems ? 'Show Less' : `+ View Details (${allItems.length - 2} more items)`}
                    </button>
                )}
            </div>

            <div className="mb-6 border-t border-dashed border-[#E0E0E0]" />

            {/* Summary */}
            <div className="space-y-4 pt-1">
                <div className="grid grid-cols-2 gap-x-4 gap-y-1">
                    <span className="text-xs font-medium text-[#999999]">Subtotal</span>
                    <span className="text-right text-xs font-medium text-[#999999]">Discount</span>
                    <span className="text-sm font-bold text-[#121212]">{currency}{(order.cart_amount || 0).toFixed(2)}</span>
                    <span className="text-right text-sm font-bold text-[#0FAF62]">-{currency}{(order.coupon_amount || 0).toFixed(2)}</span>
                </div>

                <div className="grid grid-cols-2 gap-x-4 gap-y-1 pt-2">
                    <span className="text-xs font-medium text-[#999999]">Tax</span>
                    <span />
                    <span className="text-sm font-bold text-[#121212]">{currency}{(order.tax_amount || 0).toFixed(2)}</span>
                    <span />
                </div>

                <div className="grid grid-cols-2 gap-x-4 gap-y-1 pt-2">
                    <span className="text-xs font-medium text-[#999999]">Total Amount</span>
                    <span />
                    <span className="text-lg font-bold text-[var(--orange-500)]">{currency}{(order.total_amount || 0).toFixed(2)}</span>
                    <span />
                </div>
            </div>

            <div className="mt-6 pt-6 border-t border-[#F0F0F0] space-y-3">
                {(() => {
                    const phone = order.add_receiver_detail?.phone || order.customer_id?.phone;
                    if (!phone) return null;
                    return (
                        <div className="flex items-center gap-3 text-xs text-[#999999] font-medium">
                            <Phone size={14} className="text-[#999999]" />
                            <span>{phone?.startsWith('+') ? '' : '+'}{phone}</span>
                        </div>
                    );
                })()}
                <div className="flex items-center gap-3 text-xs text-[#999999] font-medium">
                    <Calendar size={14} className="text-[#999999]" />
                    <span>{order.order_placed_at ? format(new Date(order.order_placed_at), 'dd MMM, yyyy hh:mm a') : 'N/A'}</span>
                </div>
            </div>
        </Card>
    );
};

const GroceryPOSOrderList = () => {
    const { userInfo } = useGlobalContext();
    const searchParams = useSearchParams();
    const router = useRouter();

    const [orders, setOrders] = useState<any[]>([]);
    const [totalCount, setTotalCount] = useState<number>(0);
    const [loading, setLoading] = useState(true);
    const [salesStats, setSalesStats] = useState({ total: 0, cash: 0, card: 0, upi: 0, count: 0 });

    const currentPage = Number(searchParams.get('page')) || 1;
    const itemsPerPage = Number(searchParams.get('limit')) || 15;

    const computeSalesSummary = (allOrders: any[]) => {
        let total = 0;
        let cash = 0;
        let card = 0;
        let upi = 0;

        const todayOrders = allOrders.filter((order: any) => {
            const orderDate = order.order_placed_at || order.createdAt;
            if (!orderDate) return true;
            try {
                return isToday(new Date(orderDate));
            } catch {
                return true;
            }
        });

        const listToSum = (todayOrders.length === 0 && allOrders.length > 0) ? allOrders : todayOrders;

        listToSum.forEach((order: any) => {
            const amt = Number(order.total_amount || order.cart_amount || 0);
            total += amt;

            const pType = (order.payment_type || 'cash').toString().toLowerCase();
            if (pType.includes('card')) {
                card += amt;
            } else if (pType.includes('upi') || pType.includes('online') || pType.includes('netbanking') || pType.includes('qr')) {
                upi += amt;
            } else {
                cash += amt;
            }
        });

        return { total, cash, card, upi, count: listToSum.length };
    };

    const fetchOrders = async () => {
        const restaurantId = userInfo?.restaurant_id?._id;
        if (!restaurantId) return;

        setLoading(true);
        try {
            const query = `status=pos&page=${currentPage}&limit=${itemsPerPage}&restaurant_id=${restaurantId}`;
            const res = await apis.Orders.get(query);
            if (res?.data) {
                setOrders(res.data);
                const countVal = res?.data_count ?? res?.count ?? res?.total ?? 0;
                setTotalCount(countVal);

                if (res?.payment_summary) {
                    setSalesStats({
                        total: Number(res.payment_summary.total || 0),
                        cash: Number(res.payment_summary.cash || 0),
                        card: Number(res.payment_summary.card || 0),
                        upi: Number(res.payment_summary.upi || 0) + Number(res.payment_summary.wallet || 0),
                        count: countVal,
                    });
                } else {
                    try {
                        const summaryQuery = `status=pos&page=1&limit=1000&restaurant_id=${restaurantId}`;
                        const summaryRes = await apis.Orders.get(summaryQuery);
                        if (summaryRes?.payment_summary) {
                            setSalesStats({
                                total: Number(summaryRes.payment_summary.total || 0),
                                cash: Number(summaryRes.payment_summary.cash || 0),
                                card: Number(summaryRes.payment_summary.card || 0),
                                upi: Number(summaryRes.payment_summary.upi || 0) + Number(summaryRes.payment_summary.wallet || 0),
                                count: countVal,
                            });
                        } else if (summaryRes?.data) {
                            setSalesStats(computeSalesSummary(summaryRes.data));
                        } else if (res?.data) {
                            setSalesStats(computeSalesSummary(res.data));
                        }
                    } catch (err) {
                        if (res?.data) {
                            setSalesStats(computeSalesSummary(res.data));
                        }
                    }
                }
            }
        } catch (error) {
            console.error('Error fetching grocery POS orders:', error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (userInfo?.restaurant_id?._id) {
            fetchOrders();
        }
    }, [userInfo?.restaurant_id?._id, searchParams]);

    const handlePageChange = (newPage: number) => {
        const params = new URLSearchParams(searchParams.toString());
        params.set('page', newPage.toString());
        router.push(`/grocery-pos-order-list?${params.toString()}`);
    };

    const rawType = userInfo?.restaurant_id?.type || 'grocery';
    const typeLabel = rawType === 'food' ? 'Grocery' : rawType.charAt(0).toUpperCase() + rawType.slice(1);

    if (loading) {
        return (
            <div className="flex h-[calc(100vh-140px)] flex-col items-center justify-center bg-[#F9F9F9]">
                <Loader2 className="h-8 w-8 animate-spin text-[var(--orange-500)]" />
                <p className="mt-2 text-sm text-gray-500 font-medium">Loading POS orders...</p>
            </div>
        );
    }

    if (orders.length === 0) {
        return (
            <div className="flex h-[calc(100vh-140px)] flex-col items-center justify-center bg-[#F9F9F9]">
                <div className="flex bg-white p-10 rounded-3xl shadow-sm border items-center flex-col">
                    <h2 className="text-xl font-bold text-gray-800">No POS Orders Found</h2>
                    <p className="text-gray-500 mt-2">Any orders placed through the POS will appear here.</p>
                </div>
            </div>
        );
    }

    return (
        <div className="flex h-[calc(100vh-140px)] flex-col bg-[#F9F9F9] overflow-auto custom-scrollbar">
            <div className="p-6 flex-1 flex flex-col justify-between">
                <div>
                    <h1 className="mb-6 text-2xl font-bold text-[#1C1D22]">POS Order List</h1>

                    {/* POS Sales Summary Cards */}
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                        {/* Total Today POS Sale */}
                        <div className="bg-white rounded-2xl p-5 border border-orange-100 shadow-[0px_4px_20px_0px_rgba(0,0,0,0.03)] flex items-center justify-between">
                            <div>
                                <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider">Today's POS Sale</p>
                                <p className="text-2xl font-bold text-[var(--orange-500)] mt-1">{currency}{salesStats.total.toFixed(2)}</p>
                                <span className="text-[11px] text-gray-400 mt-0.5 block">{salesStats.count} total orders today</span>
                            </div>
                            <div className="h-12 w-12 rounded-xl bg-orange-50 flex items-center justify-center text-[var(--orange-500)] flex-shrink-0">
                                <ShoppingBag size={24} />
                            </div>
                        </div>

                        {/* Cash Sale */}
                        <div className="bg-white rounded-2xl p-5 border border-emerald-100 shadow-[0px_4px_20px_0px_rgba(0,0,0,0.03)] flex items-center justify-between">
                            <div>
                                <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider">Cash Sale</p>
                                <p className="text-2xl font-bold text-emerald-600 mt-1">{currency}{salesStats.cash.toFixed(2)}</p>
                                <span className="text-[11px] text-gray-400 mt-0.5 block">Paid via Cash</span>
                            </div>
                            <div className="h-12 w-12 rounded-xl bg-emerald-50 flex items-center justify-center text-emerald-600 flex-shrink-0">
                                <Banknote size={24} />
                            </div>
                        </div>

                        {/* Card Sale */}
                        <div className="bg-white rounded-2xl p-5 border border-blue-100 shadow-[0px_4px_20px_0px_rgba(0,0,0,0.03)] flex items-center justify-between">
                            <div>
                                <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider">Card Sale</p>
                                <p className="text-2xl font-bold text-blue-600 mt-1">{currency}{salesStats.card.toFixed(2)}</p>
                                <span className="text-[11px] text-gray-400 mt-0.5 block">Paid via Card</span>
                            </div>
                            <div className="h-12 w-12 rounded-xl bg-blue-50 flex items-center justify-center text-blue-600 flex-shrink-0">
                                <CreditCard size={24} />
                            </div>
                        </div>

                        {/* UPI / Online Sale */}
                        <div className="bg-white rounded-2xl p-5 border border-amber-100 shadow-[0px_4px_20px_0px_rgba(0,0,0,0.03)] flex items-center justify-between">
                            <div>
                                <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider">UPI / Online Sale</p>
                                <p className="text-2xl font-bold text-amber-600 mt-1">{currency}{salesStats.upi.toFixed(2)}</p>
                                <span className="text-[11px] text-gray-400 mt-0.5 block">Paid via UPI / Online</span>
                            </div>
                            <div className="h-12 w-12 rounded-xl bg-amber-50 flex items-center justify-center text-amber-600 flex-shrink-0">
                                <QrCode size={24} />
                            </div>
                        </div>
                    </div>

                    <div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4 items-start content-start">
                        {orders.map((order) => (
                            <OrderCard key={order._id} order={order} />
                        ))}
                    </div>
                </div>

                {totalCount > itemsPerPage && (
                    <div className="mt-8 flex justify-center bg-white p-3 rounded-xl border border-gray-200 shadow-sm">
                        <PaginationCompo
                            totalDataCount={totalCount}
                            currentPage={currentPage}
                            itemsPerPage={itemsPerPage}
                            onPageChange={handlePageChange}
                        />
                    </div>
                )}
            </div>
        </div>
    );
};

export default function GroceryPOSOrderListPage() {
    return (
        <DashboardLayout>
            <GroceryPOSOrderList />
        </DashboardLayout>
    );
}
