"use client"
import React, { useEffect, useState } from 'react';
import DashboardLayout from '@/app/dashboard/layout';
import { Phone, Calendar, Loader2, ClipboardList } 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 } from 'date-fns';
import { currency } from '@/lib/utils';

const GroceryPOSOrderList = () => {
    const { userInfo } = useGlobalContext();
    const [orders, setOrders] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);

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

        setLoading(true);
        try {
            // Using status=pos and adding is_grocery=true if needed, 
            // but for a grocery vendor, status=pos should suffice.
            const query = `status=pos&page=1&limit=15&restaurant_id=${restaurantId}`;
            const res = await apis.Orders.get(query);
            if (res?.data) {
                setOrders(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]);

    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 {typeLabel} 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 {typeLabel} POS Orders Found</h2>
                    <p className="text-gray-500 mt-2">Any orders placed through the {typeLabel} 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">
                <h1 className="mb-6 text-2xl font-bold text-[#1C1D22]">{typeLabel} POS Order List</h1>

                <div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4 content-start">
                    {orders.map((order) => (
                        <Card key={order._id} 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">
                                    {(() => {
                                        const allItems = [...(order.cart_items || []), ...(order.other_cart_items || [])];
                                        return allItems.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.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>
                            </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 className="text-right text-xs font-medium text-[#999999]">Sales Commission</span> */}
                                    <span />
                                    <span className="text-sm font-bold text-[#121212]">{currency}{(order.tax_amount || 0).toFixed(2)}</span>
                                    {/* <span className="text-right text-sm font-bold text-[#121212]">{currency}{(order.sales_commission || 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>
                    ))}
                </div>
            </div>
        </div>
    );
};

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