"use client"

import { useState, useMemo, useEffect, useCallback } from 'react';
import { useNewOrderFMS } from '@/hooks/use-new-order-fms';

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { BackButton } from "@/components/back-button"
import Loader from "@/components/Loader"

import {
    Package,
    Clock,
    TrendingUp,
    CheckCircle,
    AlertCircle,
    XCircle,
    PauseCircle,
    Filter,
    RefreshCw,
    Search,
    Building,
    Calendar,
    DollarSign,
    BarChart3,
    Box,
    ArrowUpDown,
    ArrowUp,
    ArrowDown
} from "lucide-react"

/* ─────────────────────────────────────────────
   TYPES
───────────────────────────────────────────── */
interface Order {
    id: number;
    timestamp: string;
    buyerId: string;
    orderId: string;
    name: string;
    mobile: string;
    email: string;
    billingType: string;
    orderType: string;
    billingAddress: string;
    shippingAddress: string;
    invoiceAmount: string;
    totalAmtBeforeDiscount: string;
    uploadedImageLink: string;
    paymentTerms: string;
    paymentCollectionDate: string;
    orderTakenBy: string;
    whatsappSMS: string;
    piLink: string;
    piUrl: string;
    planned: string;
    actualDelay: string;
    fmsUserName: string;
    activeStage: number; // 0–6
    status?: 'Cancelled' | 'Hold' | 'Normal';
    editOrderLink?: string;
}


interface StageModalState {
    order: Order;
    stageIndex: number;
}

/* ─────────────────────────────────────────────
   CONSTANTS
───────────────────────────────────────────── */
const STAGE_NAMES = [
    'Order Verify Status',
    'Inventory Verify Status',
    'Payment Verify Status',
    'Order Packing Status',
    'QC Verify Status',
    'Address ReVerify Status',
    'Dispatch Status',
    'Tracking Update Status',
    'Stock Deduction Status',
];

const STAGE_SHORT = [
    'Order Verify',
    'Inventory Verify',
    'Payment Verify',
    'Order Packing',
    'QC Verify',
    'Address ReVerify',
    'Dispatch',
    'Tracking Update',
    'Stock Deduction',
];

/* ─────────────────────────────────────────────
   MOCK DATA (10 orders)
───────────────────────────────────────────── */
// Mock data removed. Using useNewOrderFMS hook.


/* ─────────────────────────────────────────────
   HELPERS
───────────────────────────────────────────── */
function getInitials(name: string): string {
    return name
        .replace(/^(Ms\.|Mr\.|Dr\.)\s*/i, '')
        .split(' ')
        .slice(0, 2)
        .map((w) => w[0])
        .join('');
}

function parseCurrency(val: string): number {
    if (!val) return 0;
    return Number(val.replace(/[₹,]/g, '')) || 0;
}

function formatCurrency(val: number): string {
    return new Intl.NumberFormat('en-IN', {
        style: 'currency',
        currency: 'INR',
        maximumFractionDigits: 0
    }).format(val);
}

function StageBadge({
    order,
    stageIndex,
    onClick,
}: {
    order: Order;
    stageIndex: number;
    onClick: () => void;
}) {
    const isDone = stageIndex < order.activeStage;
    const isActive = stageIndex === order.activeStage;

    let bg = '';
    let text = '';
    let border = '';
    let label = '';

    if (isDone) {
        bg = '#EAF3DE';
        text = '#27500A';
        border = 'transparent';
        label = '✓ Done';
    } else if (isActive) {
        bg = '#E6F1FB';
        text = '#0C447C';
        border = '#185FA5';
        label = '● Active';
    } else {
        bg = '#FCEBEB';
        text = '#791F1F';
        border = '#F09595';
        label = 'Pending';
    }

    return (
        <button
            onClick={onClick}
            style={{
                background: bg,
                color: text,
                border: `1.5px solid ${border}`,
                borderRadius: '20px',
                padding: '3px 10px',
                fontSize: '11px',
                fontWeight: 500,
                cursor: 'pointer',
                whiteSpace: 'nowrap',
            }}
        >
            {label}
        </button>
    );
}

/* ─────────────────────────────────────────────
   STAGE POPUP CONTENT — DARK THEME
───────────────────────────────────────────── */

const VALUE_COLORS: Record<string, string> = {
    green: '#3B6D11',
    red: '#A32D2D',
    amber: '#854F0B',
    blue: '#185FA5',
    gray: '#888',
};

/** Single label : value row inside an InfoCard */
function Row({
    label,
    value,
    color,
    isLast = false,
}: {
    label: string;
    value: string;
    color?: string;
    isLast?: boolean;
}) {
    return (
        <div
            style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'flex-start',
                gap: 12,
                padding: '7px 0',
                borderBottom: isLast ? 'none' : '1px solid #f0f2f5',
            }}
        >
            <span style={{ fontSize: 13, color: '#4a5a7a', fontWeight: 600, flexShrink: 0, minWidth: 90 }}>{label}</span>
            <span
                style={{
                    fontSize: 13,
                    fontWeight: 600,
                    color: color ? VALUE_COLORS[color] ?? '#1a1a2e' : '#1a1a2e',
                    textAlign: 'right',
                    flex: 1,
                    wordBreak: 'break-word',
                }}
            >
                {value}
            </span>
        </div>
    );
}

/** Label : link row */
function RowLink({ label, href, text = 'View Document', isLast = false }: { label: string; href: string; text?: string; isLast?: boolean }) {
    return (
        <div
            style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                gap: 12,
                padding: '7px 0',
                borderBottom: isLast ? 'none' : '1px solid #f0f2f5',
            }}
        >
            <span style={{ fontSize: 13, color: '#4a5a7a', fontWeight: 600, flexShrink: 0, minWidth: 90 }}>{label}</span>
            <a
                href={href}
                target="_blank"
                rel="noreferrer"
                style={{ fontSize: 13, fontWeight: 600, color: '#185FA5', textAlign: 'right', display: 'flex', alignItems: 'center', gap: 4 }}
            >
                <svg width="12" height="12" viewBox="0 0 12 12" fill="none" style={{ display: 'inline' }}>
                    <path d="M2 2h3.5M10 2v8H2V4.5M6 6l4-4M7 2h3v3" stroke="#185FA5" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
                {text}
            </a>
        </div>
    );
}

/** Card with icon + colored title — light theme */
function InfoCard({
    title,
    titleColor = '#185FA5',
    icon,
    badge,
    children,
    fullWidth = false,
    highlight = false,
}: {
    title: string;
    titleColor?: string;
    icon?: React.ReactNode;
    badge?: React.ReactNode;
    children: React.ReactNode;
    fullWidth?: boolean;
    highlight?: boolean;
}) {
    return (
        <div
            style={{
                border: highlight ? '1.5px solid #b8d0ea' : '1px solid #e5e7eb',
                borderRadius: 12,
                overflow: 'hidden',
                background: highlight ? '#f6faff' : '#fff',
                gridColumn: fullWidth ? '1 / -1' : undefined,
                boxShadow: highlight ? '0 2px 10px rgba(24,95,165,0.08)' : undefined,
            }}
        >
            <div style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                padding: '10px 14px',
                background: highlight
                    ? 'linear-gradient(90deg, #deeaf8 0%, #eaf3ff 100%)'
                    : '#f5f8fc',
                borderBottom: highlight ? '1.5px solid #b8d0ea' : '1px solid #e5e7eb',
            }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    {icon && (
                        <span style={{
                            width: 28, height: 28, borderRadius: 7,
                            background: `${titleColor}18`,
                            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                        }}>{icon}</span>
                    )}
                    <span style={{ fontSize: 14, fontWeight: 700, color: titleColor }}>{title}</span>
                </div>
                {badge}
            </div>
            <div style={{ padding: '4px 14px 8px' }}>
                {children}
            </div>
        </div>
    );
}

/** Status badge pill — light pastel */
function StatusBadge({ label, type }: { label: string; type: 'done' | 'active' | 'pending' | 'warn' | 'fail' }) {
    const styles: Record<string, { bg: string; border: string; color: string }> = {
        done: { bg: '#EAF3DE', border: '#b6d98a', color: '#27500A' },
        active: { bg: '#E6F1FB', border: '#93c5fd', color: '#0C447C' },
        pending: { bg: '#FFFBF0', border: '#fde68a', color: '#854F0B' },
        warn: { bg: '#FFF3CD', border: '#fde68a', color: '#7A5200' },
        fail: { bg: '#FCEBEB', border: '#fca5a5', color: '#791F1F' },
    };
    const s = styles[type] ?? styles.pending;
    return (
        <span style={{
            display: 'inline-block',
            padding: '3px 10px',
            borderRadius: 20,
            fontSize: 11,
            fontWeight: 700,
            background: s.bg,
            border: `1px solid ${s.border}`,
            color: s.color,
            letterSpacing: '.3px',
        }}>
            {label}
        </span>
    );
}

/** Delay badge — shows raw HH:MM:SS delay value */
function DelayBadge({ delay }: { delay: string }) {
    if (!delay || delay === '—') return null;
    return (
        <span style={{
            display: 'inline-block',
            padding: '3px 10px',
            borderRadius: 20,
            fontSize: 11,
            fontWeight: 700,
            background: '#FCEBEB',
            border: '1px solid #fca5a5',
            color: '#791F1F',
        }}>
            {delay}
        </span>
    );
}

/** 2-column responsive card grid */
const cardGrid: React.CSSProperties = {
    display: 'grid',
    gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))',
    gap: 14,
};

function StageContent({ stageIndex, order }: { stageIndex: number; order: Order }) {
    if (stageIndex === 0) {
        const orderStatusType = order.activeStage > 0 ? 'done' : order.activeStage === 0 ? 'active' : 'pending';
        const orderStatusLabel = order.activeStage > 0 ? 'Completed' : order.activeStage === 0 ? 'In Progress' : 'Pending';
        const [plannedDate, plannedTime] = (order.planned || '').split(' ');
        const [actualDate, actualTime] = (order.timestamp || '').split(' ');

        return (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                {/* Order Details Card */}
                <InfoCard
                    title="Order Details"
                    titleColor="#185FA5"
                    icon={
                        <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                            <rect x="1" y="2" width="12" height="10" rx="2" stroke="#185FA5" strokeWidth="1.3" />
                            <path d="M4 5h6M4 7.5h4" stroke="#185FA5" strokeWidth="1.3" strokeLinecap="round" />
                        </svg>
                    }
                    badge={<StatusBadge label={orderStatusLabel} type={orderStatusType} />}
                    highlight
                >
                    <Row label="Order Status" value={orderStatusLabel} color={orderStatusType === 'done' ? 'green' : orderStatusType === 'active' ? 'blue' : 'amber'} />
                    <Row label="Dispatch From" value="Delhi Warehouse" />
                    <Row
                        label="WhatsApp Status"
                        value={order.whatsappSMS}
                        color={order.whatsappSMS === 'Sent' ? 'green' : order.whatsappSMS === 'Failed' ? 'red' : 'amber'}
                    />
                    <Row label="Shipping Addr. Changed?" value="No" />
                    <RowLink label="Update Address" href="https://crm.kairali.ai/edit" text="Edit in CRM" />
                    <Row label="Remarks / PI Edit Remarks" value="Standard order — no changes required" isLast />
                </InfoCard>

                {/* Timing Card */}
                <InfoCard
                    title="Timing"
                    titleColor="#CC7A00"
                    icon={
                        <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                            <circle cx="7" cy="7" r="5.5" stroke="#CC7A00" strokeWidth="1.3" />
                            <path d="M7 4v3l2 1.5" stroke="#CC7A00" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" />
                        </svg>
                    }
                    badge={<DelayBadge delay={order.actualDelay} />}
                >
                    {/* 3-column timing grid */}
                    <div style={{
                        display: 'grid',
                        gridTemplateColumns: '1fr 1fr 1fr',
                        gap: 0,
                        borderRadius: 8,
                        overflow: 'hidden',
                        border: '1px solid #e5e7eb',
                        marginBottom: 0,
                        marginTop: 4,
                    }}>
                        {/* PLANNED */}
                        <div style={{ padding: '10px 14px', textAlign: 'center', borderRight: '1px solid #e5e7eb', background: '#fafbfc' }}>
                            <div style={{ fontSize: 10, fontWeight: 700, color: '#64748b', letterSpacing: '.5px', marginBottom: 6, textTransform: 'uppercase' }}>PLANNED</div>
                            <div style={{ fontSize: 14, fontWeight: 700, color: '#1a1a2e' }}>{[plannedDate, plannedTime].filter(Boolean).join(' ') || '—'}</div>
                        </div>
                        {/* ACTUAL */}
                        <div style={{ padding: '10px 14px', textAlign: 'center', borderRight: '1px solid #e5e7eb', background: '#fafbfc' }}>
                            <div style={{ fontSize: 10, fontWeight: 700, color: '#64748b', letterSpacing: '.5px', marginBottom: 6, textTransform: 'uppercase' }}>ACTUAL</div>
                            <div style={{ fontSize: 14, fontWeight: 700, color: '#1a1a2e' }}>{[actualDate, actualTime].filter(Boolean).join(' ') || '—'}</div>
                        </div>
                        {/* ORDER TAKEN BY */}
                        <div style={{ padding: '10px 12px', textAlign: 'center', background: '#fafafa', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 4 }}>
                            <div style={{ fontSize: 10, fontWeight: 700, color: '#64748b', letterSpacing: '.5px', textTransform: 'uppercase' }}>ORDER TAKEN BY</div>
                            <span style={{ fontSize: 13, fontWeight: 700, color: '#1a1a2e', marginTop: 4 }}>{order.orderTakenBy}</span>
                        </div>
                    </div>
                </InfoCard>
            </div>
        );
    }

    if (stageIndex === 1)
        return (
            <div style={cardGrid}>
                <InfoCard title="PI Details" titleColor="#185FA5"
                    badge={<StatusBadge label="IN PROGRESS" type="pending" />}
                >
                    <Row label="PI No" value="PI-20240420" />
                    <Row label="Dispatch From" value="Delhi Warehouse" isLast />
                    <RowLink label="PI URL" href="https://example.com/pi" isLast />
                </InfoCard>
                <InfoCard title="Timing" titleColor="#CC7A00">
                    <Row label="Planned" value="20/04/2026 10:00" />
                    <Row label="Actual" value="20/04/2026 11:30" />
                    <Row label="Time Delay" value="01:30:00" color="red" isLast />
                </InfoCard>
                <InfoCard title="Inventory & Transfer" titleColor="#3B6D11" fullWidth>
                    <Row label="FMS User" value="Vigneshkumar" />
                    <Row label="Delivery Note No" value="DN-2024-881" />
                    <Row label="DN Remarks" value="Packed & Ready" />
                    <Row label="WhatsApp Status" value="Sent" color="green" />
                    <Row label="Transfer to Accounts" value="Pending" color="amber" />
                    <RowLink label="Edit Order" href="https://crm.kairali.ai/edit" text="Open CRM" isLast />
                </InfoCard>
            </div>
        );

    if (stageIndex === 2)
        return (
            <div style={cardGrid}>
                <InfoCard title="PI Details" titleColor="#185FA5"
                    badge={<StatusBadge label="PAYMENT PENDING" type="fail" />}
                >
                    <Row label="PI No" value="PI-20240420" />
                    <Row label="Dispatch From" value="Delhi Warehouse" />
                    <RowLink label="PI URL" href="https://example.com/pi" isLast />
                </InfoCard>
                <InfoCard title="Timing" titleColor="#CC7A00">
                    <Row label="Planned" value="20/04/2026 12:00" />
                    <Row label="Actual" value="20/04/2026 14:30" />
                    <Row label="Time Delay" value="02:30:00" color="red" isLast />
                </InfoCard>
                <InfoCard title="Payment & Transfer" titleColor="#3B6D11" fullWidth>
                    <Row label="FMS User / Doer" value="Vigneshkumar" />
                    <Row label="Eway Bill No" value="EWB-2024-12345" />
                    <Row label="Advance Collected" value="₹5,000" />
                    <Row label="WhatsApp Status" value="Sent" color="green" />
                    <Row label="Transfer to Dispatch FMS" value="Done" color="green" />
                    <Row label="Transfer to Collection FMS" value="Pending" color="amber" />
                    <Row label="Helping Ticket" value="Closed" color="green" />
                    <RowLink label="Invoice Link" href="https://example.com/invoice" text="View Invoice" />
                    <RowLink label="Edit Order" href="https://crm.kairali.ai/edit" text="Open CRM" isLast />
                </InfoCard>
            </div>
        );

    if (stageIndex === 3)
        return (
            <div style={cardGrid}>
                <InfoCard title="Timing" titleColor="#CC7A00">
                    <Row label="Planned" value="21/04/2026 09:00" />
                    <Row label="Actual" value="21/04/2026 10:15" />
                    <Row label="Time Delay" value="01:15:00" color="red" isLast />
                </InfoCard>
                <InfoCard title="QC & Packing" titleColor="#3B6D11">
                    <Row label="QC Status" value="Passed" color="green" />
                    <RowLink label="QC Upload URL" href="https://example.com/qc" text="View QC Doc" />
                    <Row label="Remarks" value="All items verified, packed securely" isLast />
                </InfoCard>
            </div>
        );

    if (stageIndex === 4)
        return (
            <div style={cardGrid}>
                <InfoCard title="Timing" titleColor="#CC7A00">
                    <Row label="Planned" value="21/04/2026 11:00" />
                    <Row label="Actual" value="21/04/2026 11:45" />
                    <Row label="Time Delay" value="00:45:00" color="amber" isLast />
                </InfoCard>
                <InfoCard title="Address & Dispatch" titleColor="#3B6D11">
                    <Row label="Dispatch Status" value="Ready to Ship" color="green" />
                    <RowLink label="Dispatch Doc" href="https://example.com/dispatch" text="View Details" />
                    <Row label="Remarks" value="Address confirmed with client via call" isLast />
                </InfoCard>
            </div>
        );

    if (stageIndex === 5)
        return (
            <div style={cardGrid}>
                <InfoCard title="Tracking Info" titleColor="#185FA5">
                    <Row label="Tracking ID" value="BD123456789IN" color="blue" />
                    <Row label="Dispatch Via" value="BlueDart Express" />
                    <RowLink label="Tracking URL" href="https://bluedartonline.com/track" text="Track Shipment" isLast />
                </InfoCard>
                <InfoCard title="Dispatch Timing" titleColor="#CC7A00">
                    <Row label="Planned" value="21/04/2026 13:00" />
                    <Row label="Actual" value="21/04/2026 14:30" />
                    <Row label="Time Delay" value="01:30:00" color="red" isLast />
                </InfoCard>
            </div>
        );

    if (stageIndex === 6)
        return (
            <div style={cardGrid}>
                <InfoCard title="Dispatch Details" titleColor="#185FA5"
                    badge={<StatusBadge label="PENDING" type="pending" />}
                >
                    <Row label="AWB / Docket No" value="—" />
                    <Row label="Courier Partner" value="—" />
                    <Row label="Pickup Status" value="Pending" color="amber" />
                    <Row label="Pickup Date & Time" value="—" isLast />
                </InfoCard>
                <InfoCard title="Stock Minus Status" titleColor="#7B3FA0">
                    <Row label="Stock Deduction" value="Pending" color="amber" isLast />
                </InfoCard>
            </div>
        );

    if (stageIndex === 7)
        return (
            <div style={cardGrid}>
                <InfoCard title="Live Tracking" titleColor="#185FA5">
                    <Row label="Current Status" value="In Transit" color="amber" />
                    <Row label="Last Location" value="Delhi Hub" />
                    <Row label="Est. Delivery" value="23/04/2026" />
                    <Row label="Delivered On" value="—" isLast />
                </InfoCard>
                <InfoCard title="Delivery Confirmation" titleColor="#3B6D11">
                    <RowLink label="Proof of Delivery" href="#" text="Upload POD" />
                    <Row label="WhatsApp Notified" value="Pending" color="amber" isLast />
                </InfoCard>
            </div>
        );

    if (stageIndex === 8)
        return (
            <div style={cardGrid}>
                <InfoCard title="Stock Deduction" titleColor="#7B3FA0"
                    badge={<StatusBadge label="PENDING" type="pending" />}
                    fullWidth
                >
                    <Row label="Deduction Status" value="Pending" color="amber" />
                    <Row label="Deducted By" value="—" />
                    <Row label="Deduction Date" value="—" />
                    <Row label="System Sync" value="Not Synced" color="amber" />
                    <Row label="Remarks" value="Awaiting delivery confirmation to deduct stock" isLast />
                </InfoCard>
            </div>
        );

    return null;
}

/* ─────────────────────────────────────────────
   STAGE MODAL — DARK THEME (matches screenshot)
───────────────────────────────────────────── */
function StageModal({
    state,
    onClose,
}: {
    state: StageModalState;
    onClose: () => void;
}) {
    const { order, stageIndex } = state;

    const stageStatusType =
        stageIndex < order.activeStage ? 'done' :
            stageIndex === order.activeStage ? 'active' : 'pending';
    const stageStatusLabel =
        stageStatusType === 'done' ? 'COMPLETED' :
            stageStatusType === 'active' ? 'ACTIVE' : 'PENDING';

    // PI number derived from order (mock — real data would come from order fields)
    const piNo = 'PI-20240420';

    const headerChip: React.CSSProperties = {
        display: 'inline-flex', alignItems: 'center', gap: 5,
        background: 'rgba(255,255,255,0.12)',
        padding: '5px 10px', borderRadius: 6,
        border: '1px solid rgba(255,255,255,0.18)',
    };

    return (
        <div
            onClick={(e) => e.target === e.currentTarget && onClose()}
            style={{
                position: 'fixed',
                inset: 0,
                background: 'rgba(0,0,0,0.45)',
                display: 'flex',
                alignItems: 'flex-start',
                justifyContent: 'center',
                zIndex: 1000,
                padding: '24px 16px',
                overflowY: 'auto',
            }}
        >
            <div
                style={{
                    background: '#fff',
                    borderRadius: 16,
                    width: '100%',
                    maxWidth: 680,
                    boxShadow: '0 20px 60px rgba(0,0,0,0.18)',
                    overflow: 'hidden',
                    border: '1px solid #e5e7eb',
                }}
            >
                {/* ── GRADIENT HEADER ── */}
                <div style={{
                    background: 'linear-gradient(135deg, #0C447C 0%, #185FA5 60%, #378ADD 100%)',
                    padding: '16px 20px',
                }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
                        <h2 style={{ fontSize: 15, fontWeight: 500, color: 'rgba(255,255,255,0.85)', margin: 0 }}>
                            {STAGE_NAMES[stageIndex]} —{' '}
                            <span style={{ color: '#fff', fontWeight: 700 }}>{order.orderId}</span>
                        </h2>
                        <button
                            onClick={onClose}
                            style={{
                                width: 30, height: 30, borderRadius: '50%',
                                border: '1px solid rgba(255,255,255,0.25)',
                                background: 'rgba(255,255,255,0.12)',
                                cursor: 'pointer',
                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                                fontSize: 16, color: '#fff', flexShrink: 0,
                            }}
                        >×</button>
                    </div>

                    {/* chips row inside header */}
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
                        <div style={headerChip}>
                            <svg width="12" height="12" viewBox="0 0 14 14" fill="none">
                                <rect x="1" y="1" width="12" height="12" rx="2.5" stroke="rgba(255,255,255,0.7)" strokeWidth="1.1" />
                                <path d="M4 5h6M4 7.5h4" stroke="rgba(255,255,255,0.7)" strokeWidth="1.1" strokeLinecap="round" />
                            </svg>
                            <span style={{ fontSize: 12, color: '#fff', fontWeight: 500 }}>{order.name}</span>
                        </div>
                        <div style={headerChip}>
                            <svg width="12" height="12" viewBox="0 0 14 14" fill="none">
                                <path d="M3 2h2.5l1 2.5-1.5 1a7 7 0 003 3l1-1.5L11.5 8V10.5A1.5 1.5 0 0110 12C5.5 12 2 8.5 2 4a1.5 1.5 0 011.5-1.5" stroke="rgba(255,255,255,0.7)" strokeWidth="1.1" strokeLinecap="round" />
                            </svg>
                            <span style={{ fontSize: 12, color: '#fff' }}>+91 {order.mobile.replace(/^91/, '').replace(/(\d{5})(\d{5})/, '$1 $2')}</span>
                        </div>
                        <div style={headerChip}>
                            <span style={{ fontSize: 12, color: '#fff' }}>{piNo}</span>
                        </div>
                        <a
                            href={order.piUrl || '#'}
                            target="_blank"
                            rel="noreferrer"
                            style={{
                                fontSize: 12, padding: '5px 12px', borderRadius: 6,
                                border: '1.5px solid #fff', color: '#185FA5',
                                background: '#fff', cursor: 'pointer', fontWeight: 700,
                                display: 'inline-flex', alignItems: 'center', gap: 4,
                                textDecoration: 'none',
                            }}
                        >
                            <svg width="10" height="10" viewBox="0 0 12 12" fill="none">
                                <path d="M2 2h6.5M8.5 2v6.5M2 10L8.5 2" stroke="#185FA5" strokeWidth="1.8" strokeLinecap="round" />
                            </svg>
                            View PI
                        </a>
                    </div>
                </div>

                {/* ── STAGE-SPECIFIC CONTENT ── */}
                <div style={{ padding: '18px 24px 24px' }}>
                    <StageContent stageIndex={stageIndex} order={order} />
                </div>
            </div>
        </div>
    );
}

/* ─────────────────────────────────────────────
   MAIN PAGE
───────────────────────────────────────────── */
export default function NewOrderFMS() {
    const { orders, loading: apiLoading, error: apiError, refresh } = useNewOrderFMS();
    const [search, setSearch] = useState('');
    const [filterOrderType, setFilterOrderType] = useState('All');
    const [filterBillingType, setFilterBillingType] = useState('All');
    const [filterStage, setFilterStage] = useState('All');
    const [filterTakenBy, setFilterTakenBy] = useState('All');
    const [datePreset, setDatePreset] = useState('this_week');

    const [customDateRange, setCustomDateRange] = useState({ start: '', end: '' });
    const [stageModal, setStageModal] = useState<StageModalState | null>(null);
    const [currentPage, setCurrentPage] = useState(1);
    const [rowsPerPage, setRowsPerPage] = useState(5);
    const [goPage, setGoPage] = useState('');
    const [sortConfig, setSortConfig] = useState<{ key: string; direction: 'asc' | 'desc' } | null>({ key: 'timestamp', direction: 'desc' });

    const uniqueOrderTypes = useMemo(() => {
        const types = new Set(orders.map(o => o.orderType).filter(Boolean));
        return Array.from(types).sort();
    }, [orders]);

    const uniqueBillingTypes = useMemo(() => {
        const types = new Set(orders.map(o => o.billingType).filter(Boolean));
        return Array.from(types).sort();
    }, [orders]);

    const uniqueAgents = useMemo(() => {
        const agents = new Set(orders.map(o => o.orderTakenBy).filter(Boolean));
        return Array.from(agents).sort();
    }, [orders]);




    const handleSort = (key: string) => {
        let direction: 'asc' | 'desc' = 'asc';
        if (sortConfig && sortConfig.key === key && sortConfig.direction === 'asc') {
            direction = 'desc';
        }
        setSortConfig({ key, direction });
    };

    // Loading state is now handled by the hook


    const parseDateStr = (str: string) => {
        if (!str || str === '—') return new Date(NaN);
        const parts = str.split(' ')[0].split('/');
        if (parts.length !== 3) return new Date(NaN);
        const [d, m, y] = parts;
        return new Date(parseInt(y), parseInt(m) - 1, parseInt(d));
    };

    const isInDateRange = (timestamp: string) => {
        if (datePreset === 'all') return true;
        const d = parseDateStr(timestamp);
        if (isNaN(d.getTime())) return false;

        const now = new Date();
        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());

        switch (datePreset) {
            case 'today':
                return d.getTime() === today.getTime();
            case 'yesterday': {
                const yesterday = new Date(today);
                yesterday.setDate(today.getDate() - 1);
                return d.getTime() === yesterday.getTime();
            }
            case 'this_week': {
                const startOfWeek = new Date(today);
                const day = today.getDay() || 7;
                startOfWeek.setDate(today.getDate() - (day - 1));
                return d >= startOfWeek && d <= today;
            }
            case 'last_week': {
                const day = today.getDay() || 7;
                const startOfLastWeek = new Date(today);
                startOfLastWeek.setDate(today.getDate() - day - 6);
                const endOfLastWeek = new Date(today);
                endOfLastWeek.setDate(today.getDate() - day);
                return d >= startOfLastWeek && d <= endOfLastWeek;
            }
            case 'this_month':
                return d.getMonth() === today.getMonth() && d.getFullYear() === today.getFullYear();
            case 'last_month': {
                const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
                return d.getMonth() === lastMonth.getMonth() && d.getFullYear() === lastMonth.getFullYear();
            }
            case 'this_year':
                return d.getFullYear() === today.getFullYear();
            case 'last_year':
                return d.getFullYear() === today.getFullYear() - 1;
            case 'custom': {
                if (!customDateRange.start || !customDateRange.end) return true;
                const [sY, sM, sD] = customDateRange.start.split('-').map(Number);
                const [eY, eM, eD] = customDateRange.end.split('-').map(Number);
                const cS = new Date(sY, sM - 1, sD);
                const cE = new Date(eY, eM - 1, eD);
                return d >= cS && d <= cE;
            }
            default:
                return true;
        }
    };

    const parseFullDateStr = (str: string) => {
        if (!str || str === '—') return new Date(0);
        const parts = str.split(' ');
        const dateParts = parts[0].split('/');
        if (dateParts.length !== 3) return new Date(0);
        const d = parseInt(dateParts[0]);
        const m = parseInt(dateParts[1]) - 1;
        const y = parseInt(dateParts[2]);
        const date = new Date(y, m, d);
        if (parts[1]) {
            const timeParts = parts[1].split(':');
            if (timeParts.length >= 2) {
                date.setHours(parseInt(timeParts[0]), parseInt(timeParts[1]));
            }
        }
        return date;
    };


    const filtered = useMemo(() => {
        return orders.filter((o) => {

            const q = search.toLowerCase();
            if (
                q &&
                !o.name.toLowerCase().includes(q) &&
                !o.orderId.toLowerCase().includes(q) &&
                !o.buyerId.toLowerCase().includes(q) &&
                !o.mobile.includes(q) &&
                !o.email.toLowerCase().includes(q)
            )
                return false;
            if (filterOrderType !== 'All' && o.orderType !== filterOrderType) return false;
            if (filterBillingType !== 'All' && o.billingType !== filterBillingType) return false;
            if (filterTakenBy !== 'All' && o.orderTakenBy !== filterTakenBy) return false;
            if (filterStage !== 'All') {
                const si = parseInt(filterStage);
                if (o.activeStage !== si) return false;
            }
            if (!isInDateRange(o.timestamp)) return false;
            return true;
        });
    }, [orders, search, filterOrderType, filterBillingType, filterStage, filterTakenBy, datePreset, customDateRange]);


    /* KPI */
    const kpi = useMemo(() => {
        const total = filtered.length;
        const totalValue = filtered.reduce((acc, o) => acc + parseCurrency(o.invoiceAmount), 0);

        // Filter out Cancelled and Hold for the main stage-based KPIs
        const activeOrders = filtered.filter(o => !o.status || o.status === 'Normal');

        const completed = activeOrders.filter((o) => o.activeStage === 6).length;
        const completedValue = activeOrders.filter((o) => o.activeStage === 6).reduce((acc, o) => acc + parseCurrency(o.invoiceAmount), 0);

        const pending = activeOrders.filter((o) => o.activeStage === 0).length;
        const pendingValue = activeOrders.filter((o) => o.activeStage === 0).reduce((acc, o) => acc + parseCurrency(o.invoiceAmount), 0);

        const inProgress = activeOrders.filter((o) => o.activeStage > 0 && o.activeStage < 6).length;
        const inProgressValue = activeOrders.filter((o) => o.activeStage > 0 && o.activeStage < 6).reduce((acc, o) => acc + parseCurrency(o.invoiceAmount), 0);

        const delayed = filtered.filter((o) => o.actualDelay !== '—').length;

        const cancelled = filtered.filter((o) => o.status === 'Cancelled').length;
        const cancelledValue = filtered.filter((o) => o.status === 'Cancelled').reduce((acc, o) => acc + parseCurrency(o.invoiceAmount), 0);

        const hold = filtered.filter((o) => o.status === 'Hold').length;
        const holdValue = filtered.filter((o) => o.status === 'Hold').reduce((acc, o) => acc + parseCurrency(o.invoiceAmount), 0);

        return {
            total, totalValue,
            inProgress, inProgressValue,
            completed, completedValue,
            pending, pendingValue,
            delayed,
            cancelled, cancelledValue,
            hold, holdValue
        };
    }, [filtered]);


    /* SORTING */
    const sortedData = useMemo(() => {
        if (!sortConfig) return filtered;
        return [...filtered].sort((a, b) => {
            const key = sortConfig.key as keyof Order;
            const aVal = a[key] ?? '';
            const bVal = b[key] ?? '';

            if (key === 'timestamp' || key === 'paymentCollectionDate') {
                const dateA = parseFullDateStr(aVal as string).getTime();
                const dateB = parseFullDateStr(bVal as string).getTime();
                return sortConfig.direction === 'asc' ? dateA - dateB : dateB - dateA;
            }

            if (aVal < bVal) return sortConfig.direction === 'asc' ? -1 : 1;
            if (aVal > bVal) return sortConfig.direction === 'asc' ? 1 : -1;
            return 0;
        });
    }, [filtered, sortConfig]);

    /* PAGINATION */
    const totalPages = Math.max(1, Math.ceil(sortedData.length / rowsPerPage));
    const paginated = sortedData.slice((currentPage - 1) * rowsPerPage, currentPage * rowsPerPage);

    const clearFilters = () => {
        setSearch('');
        setFilterOrderType('All');
        setFilterBillingType('All');
        setFilterStage('All');
        setFilterTakenBy('All');
        setDatePreset('all');
        setCustomDateRange({ start: '', end: '' });
        setSortConfig({ key: 'timestamp', direction: 'desc' });
        setCurrentPage(1);
    };

    /* STYLES */
    const thBase: React.CSSProperties = {
        padding: '8px 12px',
        fontWeight: 500,
        whiteSpace: 'nowrap',
        textAlign: 'left',
        fontSize: 13,
        borderRight: '1px solid rgba(255,255,255,0.08)',
    };
    const thDetail: React.CSSProperties = {
        ...thBase,
        background: '#2b3235',
        color: '#ffffff',
    };
    const thStage: React.CSSProperties = {
        ...thBase,
        background: '#0581a0',
        color: '#ffffff',
        textAlign: 'center',
        fontSize: 12,
    };

    const SortableHeader = ({ label, sortKey, style }: { label: string, sortKey: string, style: React.CSSProperties }) => {
        const isActive = sortConfig?.key === sortKey;
        return (
            <th
                style={{ ...style, cursor: 'pointer', userSelect: 'none' }}
                onClick={() => handleSort(sortKey)}
                className="hover:bg-[#3d4548] transition-colors"
            >
                <div className="flex items-center gap-2">
                    {label}
                    {isActive ? (
                        sortConfig.direction === 'asc' ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />
                    ) : (
                        <ArrowUpDown className="h-3 w-3 opacity-30" />
                    )}
                </div>
            </th>
        );
    };
    const tdBase: React.CSSProperties = {
        padding: '8px 12px',
        fontSize: 13,
        color: '#1a1a2e',
        borderRight: '1px solid #e5e7eb',
        verticalAlign: 'middle',
        whiteSpace: 'nowrap',
    };
    const [isMobile, setIsMobile] = useState(typeof window !== "undefined" && window.innerWidth < 768);
    useEffect(() => {
        const handleResize = () => setIsMobile(window.innerWidth < 768);
        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
    }, []);
    const stickyBase: React.CSSProperties = {
        position: 'sticky',
        zIndex: 1,
    };

    const now = new Date();
    const lastUpdated = now.toLocaleDateString('en-GB').replace(/\//g, '/') + ', ' +
        now.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', second: '2-digit' });

    const selectStyle: React.CSSProperties = {
        padding: '7px 10px',
        borderRadius: 6,
        border: '1px solid #e0d8cc',
        background: '#fff',
        fontSize: 13,
        color: '#1a1a2e',
        cursor: 'pointer',
    };
    const inputStyle: React.CSSProperties = {
        padding: '7px 12px',
        borderRadius: 6,
        border: '1px solid #e0d8cc',
        background: '#fff',
        fontSize: 13,
        color: '#1a1a2e',
        outline: 'none',
    };

    return (
        <div style={{ background: '#f4f6fa', minHeight: '100vh', width: '100%', fontFamily: "'Geist', 'Inter', sans-serif" }}>
            <Loader isLoading={apiLoading && orders.length === 0} contentOnly={true} />


            <div style={{
                opacity: (apiLoading && orders.length === 0) ? 0 : 1,
                transition: 'opacity 0.3s ease-in-out'
            }}>

                {/* ── PAGE HEADER (Premium Villa Raag Style - Full Width Breakout) ── */}
                <div className="relative overflow-hidden -mt-6 sm:-mt-10 -mx-4 sm:-mx-6 lg:-mx-8 mb-6 border-b border-white/10 shadow-[0_4px_24px_rgba(0,0,0,0.3)]"
                    style={{ background: 'linear-gradient(135deg, #0f1f45 0%, #162d6b 45%, #1a3080 100%)' }}>

                    {/* Ambient depth layers */}
                    <div className="absolute inset-0 bg-gradient-to-r from-cyan-500/5 via-transparent to-violet-600/10 pointer-events-none" />
                    <div className="absolute -top-10 left-1/4 w-[500px] h-32 bg-blue-400/10 blur-3xl rounded-full pointer-events-none" />
                    <div className="absolute -top-6 right-1/4 w-64 h-20 bg-indigo-400/10 blur-2xl rounded-full pointer-events-none" />

                    <div className="relative w-full px-4 sm:px-6 lg:px-8 py-5">
                        <BackButton className="mb-4" />
                        <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-6">
                            <div className="flex items-center gap-5">
                                {/* ICON CONTAINER */}
                                <div className="h-14 w-14 rounded-2xl flex items-center justify-center flex-shrink-0 border border-blue-300/25 shadow-[0_0_24px_rgba(147,197,253,0.2)]"
                                    style={{ background: 'linear-gradient(135deg, rgba(59,130,246,0.35) 0%, rgba(99,102,241,0.25) 100%)' }}>
                                    <Box className="h-7 w-7 text-blue-200" />
                                </div>
                                <div className="min-w-0 flex-1">
                                    <h1 className="text-3xl sm:text-4xl lg:text-5xl font-bold tracking-tight leading-tight text-white drop-shadow-sm">
                                        New Order FMS
                                    </h1>
                                    <p className="text-sm lg:text-base mt-1.5 font-normal tracking-wide text-blue-200/55">
                                        Order Management&nbsp;&nbsp;·&nbsp;&nbsp;Stage Tracking&nbsp;&nbsp;·&nbsp;&nbsp;Real-time Monitoring
                                    </p>
                                </div>
                            </div>

                            {/* LAST UPDATED */}
                            <div className="flex w-full lg:w-auto justify-start lg:justify-end">
                                <div className="w-full sm:w-auto rounded-xl px-4 py-3 border border-blue-300/15 shadow-[inset_0_1px_0_rgba(255,255,255,0.06)]"
                                    style={{ background: 'rgba(255,255,255,0.05)' }}>
                                    <p className="text-xs text-blue-300/50 font-semibold uppercase tracking-widest">
                                        Last Updated
                                    </p>
                                    <p className="text-sm font-semibold text-white/80 mt-1">
                                        {lastUpdated}
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                {/* ── CONTENT ── */}
                <div style={{ padding: '0px 0px 32px 0px', display: 'flex', flexDirection: 'column', gap: 16, width: '100%' }}>

                    {/* ── FILTERS (Professional Upgrade) ── */}
                    <div className="mt-4">
                        <div className="rounded-xl border border-slate-200 bg-white shadow-md">

                            {/* HEADER */}
                            <div className="
            flex flex-col sm:flex-row
            items-start sm:items-center
            justify-between
            gap-4
            px-4 sm:px-5
            py-4
            bg-gradient-to-r from-blue-50 via-white to-indigo-50
            border-b border-slate-200
        ">
                                <div className="flex items-center gap-3">
                                    <div className="
                    w-9 h-9 sm:w-10 sm:h-10
                    rounded-lg
                    bg-gradient-to-br
                    from-[#0f172a]
                    via-[#1e3a5f]
                    to-[#1d4ed8]
                    flex items-center justify-center
                    shadow-md
                    border border-[#1e40af]/40
                ">
                                        <Filter className="w-5 h-5 text-white" />
                                    </div>

                                    <div>
                                        <h3 className="text-base font-semibold text-[#1e3a5f]">
                                            Filters & Search
                                        </h3>
                                        <p className="text-xs text-[#64748b]">
                                            Refine your order feed using smart parameters
                                        </p>
                                    </div>
                                </div>

                                <Button
                                    onClick={clearFilters}
                                    className="
                    w-full sm:w-auto
                    bg-gradient-to-r from-[#1e3a5f] to-[#1d4ed8]
                    text-white
                    border-none
                    hover:opacity-90
                    shadow-sm
                "
                                >
                                    Clear Filters
                                </Button>
                            </div>

                            {/* CONTENT */}
                            <div className="px-4 sm:px-6 py-5">
                                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-4">

                                    {/* SEARCH */}
                                    <div className="flex flex-col gap-1.5 w-full">
                                        <Label className="text-[11px] font-medium uppercase tracking-wide text-[#1e3a5f]">
                                            Search Orders
                                        </Label>
                                        <div className="relative w-full">
                                            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-[#1d4ed8]" />
                                            <Input
                                                placeholder="Order ID, Client..."
                                                value={search}
                                                onChange={(e) => {
                                                    setSearch(e.target.value)
                                                    setCurrentPage(1)
                                                }}
                                                className="
                                h-10 w-full pl-9 text-sm
                                border-[#bfdbfe]
                                focus:border-[#1d4ed8]
                                focus:ring-1 focus:ring-[#1d4ed8]/20
                                rounded-md
                                transition-all duration-200
                            "
                                            />
                                        </div>
                                    </div>

                                    {/* DATE RANGE */}
                                    <div className="flex flex-col gap-1.5 w-full">
                                        <Label className="text-[11px] font-medium uppercase tracking-wide text-[#1e3a5f]">
                                            Date Range
                                        </Label>
                                        <Select value={datePreset} onValueChange={(v) => { setDatePreset(v); setCurrentPage(1) }}>
                                            <SelectTrigger className="h-10 w-full text-sm border-[#bfdbfe] focus:border-[#1d4ed8] focus:ring-1 focus:ring-[#1d4ed8]/20 rounded-md">
                                                <SelectValue placeholder="All Dates" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="all">All Dates</SelectItem>
                                                <SelectItem value="today">Today</SelectItem>
                                                <SelectItem value="yesterday">Yesterday</SelectItem>
                                                <SelectItem value="this_week">This Week</SelectItem>
                                                <SelectItem value="last_week">Last Week</SelectItem>
                                                <SelectItem value="this_month">This Month</SelectItem>
                                                <SelectItem value="last_month">Last Month</SelectItem>
                                                <SelectItem value="this_year">This Year</SelectItem>
                                                <SelectItem value="last_year">Last Year</SelectItem>
                                                <SelectItem value="custom">Custom Range</SelectItem>
                                            </SelectContent>
                                        </Select>
                                    </div>

                                    {/* ORDER TYPE */}
                                    <div className="flex flex-col gap-1.5 w-full">
                                        <Label className="text-[11px] font-medium uppercase tracking-wide text-[#1e3a5f]">
                                            Order Type
                                        </Label>
                                        <Select value={filterOrderType} onValueChange={(v) => { setFilterOrderType(v); setCurrentPage(1) }}>
                                            <SelectTrigger className="h-10 w-full text-sm border-[#bfdbfe] focus:border-[#1d4ed8] rounded-md">
                                                <SelectValue placeholder="All Types" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="All">All Types</SelectItem>
                                                {uniqueOrderTypes.map(t => (
                                                    <SelectItem key={t} value={t}>{t}</SelectItem>
                                                ))}
                                            </SelectContent>

                                        </Select>
                                    </div>

                                    {/* BILLING TYPE */}
                                    <div className="flex flex-col gap-1.5 w-full">
                                        <Label className="text-[11px] font-medium uppercase tracking-wide text-[#1e3a5f]">
                                            Billing Type
                                        </Label>
                                        <Select value={filterBillingType} onValueChange={(v) => { setFilterBillingType(v); setCurrentPage(1) }}>
                                            <SelectTrigger className="h-10 w-full text-sm border-[#bfdbfe] focus:border-[#1d4ed8] rounded-md">
                                                <SelectValue placeholder="All Billing" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="All">All Billing</SelectItem>
                                                {uniqueBillingTypes.map(t => (
                                                    <SelectItem key={t} value={t}>{t}</SelectItem>
                                                ))}
                                            </SelectContent>

                                        </Select>
                                    </div>

                                    {/* STAGE */}
                                    <div className="flex flex-col gap-1.5 w-full">
                                        <Label className="text-[11px] font-medium uppercase tracking-wide text-[#1e3a5f]">
                                            Order Stage
                                        </Label>
                                        <Select value={filterStage} onValueChange={(v) => { setFilterStage(v); setCurrentPage(1) }}>
                                            <SelectTrigger className="h-10 w-full text-sm border-[#bfdbfe] focus:border-[#1d4ed8] rounded-md">
                                                <SelectValue placeholder="All Stages" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="All">All Stages</SelectItem>
                                                {STAGE_SHORT.map((s, i) => (
                                                    <SelectItem key={i} value={String(i)}>{s}</SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                    </div>

                                    {/* TAKEN BY */}
                                    <div className="flex flex-col gap-1.5 w-full">
                                        <Label className="text-[11px] font-medium uppercase tracking-wide text-[#1e3a5f]">
                                            Taken By
                                        </Label>
                                        <Select value={filterTakenBy} onValueChange={(v) => { setFilterTakenBy(v); setCurrentPage(1) }}>
                                            <SelectTrigger className="h-10 w-full text-sm border-[#bfdbfe] focus:border-[#1d4ed8] rounded-md">
                                                <SelectValue placeholder="All Agents" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="All">All Agents</SelectItem>
                                                {uniqueAgents.map(a => (
                                                    <SelectItem key={a} value={a}>{a}</SelectItem>
                                                ))}
                                            </SelectContent>

                                        </Select>
                                    </div>

                                </div>

                                {/* CUSTOM DATE */}
                                {datePreset === "custom" && (
                                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-4 pt-4 border-t border-[#bfdbfe]">
                                        <Input 
                                            className="h-10 w-full border-[#bfdbfe] focus:border-[#1d4ed8]" 
                                            type="date" 
                                            value={customDateRange.start}
                                            onChange={(e) => {
                                                setCustomDateRange(prev => ({ ...prev, start: e.target.value }));
                                                setCurrentPage(1);
                                            }}
                                        />
                                        <Input 
                                            className="h-10 w-full border-[#bfdbfe] focus:border-[#1d4ed8]" 
                                            type="date" 
                                            value={customDateRange.end}
                                            onChange={(e) => {
                                                setCustomDateRange(prev => ({ ...prev, end: e.target.value }));
                                                setCurrentPage(1);
                                            }}
                                        />
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                    {/* ── KPI CARDS (Premium Grid) ── */}
                    <div className="mt-5">

                        {/* ================= KPI WRAPPER ================= */}
                        <div className="
    rounded-2xl
    border border-[#dbeafe]
    bg-[#f8fafc]
    shadow-[0_10px_30px_rgba(30,58,138,0.08)]
    px-4 sm:px-5 py-5
  ">

                            {/* ================= UPDATED HEADER ================= */}
                            <div className="flex items-center justify-between mb-4">

                                <div className="flex items-center gap-3">

                                    {/* ICON */}
                                    <div className="
          w-10 h-10
          rounded-lg
          bg-gradient-to-br from-[#2563eb] to-[#1e40af]
          flex items-center justify-center
          shadow-md
        ">
                                        <BarChart3 className="w-5 h-5 text-white" />
                                    </div>

                                    {/* TEXT */}
                                    <div>
                                        <h3 className="text-base font-semibold text-[#1e3a8a]">
                                            Key Performance Indicators
                                        </h3>
                                        <p className="text-xs text-[#64748b]">
                                            Overview of order metrics & performance
                                        </p>
                                    </div>

                                </div>




                            </div>

                            {/* ================= KPI GRID ================= */}
                            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-4">

                                {/* TOTAL ORDERS */}
                                <div className="rounded-xl border border-[#93c5fd] bg-blue-50 p-5 hover:shadow-md transition-all duration-300">
                                    <div className="flex items-center justify-between">
                                        <div className="space-y-1">
                                            <p className="text-[11px] font-semibold text-[#64748b] uppercase tracking-wide">
                                                Total Orders
                                            </p>
                                            <p className="text-2xl font-bold text-[#0f172a]">{kpi.total}</p>
                                            <p className="text-sm font-medium text-emerald-600">
                                                {formatCurrency(kpi.totalValue)}
                                            </p>
                                        </div>

                                        <div className="h-11 w-11 rounded-lg bg-blue-50 flex items-center justify-center">
                                            <Package className="h-5 w-5 text-blue-600" />
                                        </div>
                                    </div>

                                    <div className="mt-3 flex items-center gap-2">
                                        <span className="text-xs px-2 py-1 rounded-md bg-blue-100 text-blue-700">
                                            All Records
                                        </span>
                                    </div>
                                </div>

                                {/* COMPLETED */}
                                <div className="rounded-xl border border-emerald-300 bg-emerald-50 p-5 hover:shadow-md transition-all duration-300">
                                    <div className="flex items-center justify-between">
                                        <div className="space-y-1">
                                            <p className="text-[11px] font-semibold text-[#64748b] uppercase tracking-wide">
                                                Completed
                                            </p>
                                            <p className="text-2xl font-bold text-[#0f172a]">{kpi.completed}</p>
                                            <p className="text-sm font-medium text-emerald-600">
                                                {formatCurrency(kpi.completedValue)}
                                            </p>
                                        </div>

                                        <div className="h-11 w-11 rounded-lg bg-emerald-50 flex items-center justify-center">
                                            <CheckCircle className="h-5 w-5 text-emerald-600" />
                                        </div>
                                    </div>

                                    <div className="mt-3">
                                        <span className="text-xs px-2 py-1 rounded-md bg-emerald-100 text-emerald-700">
                                            Stage 6
                                        </span>
                                    </div>
                                </div>

                                {/* IN PROGRESS (PROGRESS) */}
                                <div className="rounded-xl border border-amber-300 bg-amber-50 p-5 hover:shadow-md transition-all duration-300">
                                    <div className="flex items-center justify-between">
                                        <div className="space-y-1">
                                            <p className="text-[11px] font-semibold text-[#64748b] uppercase tracking-wide">
                                                Progress
                                            </p>
                                            <p className="text-2xl font-bold text-[#0f172a]">{kpi.inProgress}</p>
                                            <p className="text-sm font-medium text-amber-600">
                                                {formatCurrency(kpi.inProgressValue)}
                                            </p>
                                        </div>

                                        <div className="h-11 w-11 rounded-lg bg-amber-50 flex items-center justify-center">
                                            <TrendingUp className="h-5 w-5 text-amber-500" />
                                        </div>
                                    </div>

                                    <div className="mt-3">
                                        <span className="text-xs px-2 py-1 rounded-md bg-amber-100 text-amber-700">
                                            Processing
                                        </span>
                                    </div>
                                </div>

                                {/* PENDING */}
                                <div className="rounded-xl border border-rose-300 bg-rose-50 p-5 hover:shadow-md transition-all duration-300">
                                    <div className="flex items-center justify-between">
                                        <div className="space-y-1">
                                            <p className="text-[11px] font-semibold text-[#64748b] uppercase tracking-wide">
                                                Pending
                                            </p>
                                            <p className="text-2xl font-bold text-[#0f172a]">{kpi.pending}</p>
                                            <p className="text-sm font-medium text-rose-600">
                                                {formatCurrency(kpi.pendingValue)}
                                            </p>
                                        </div>

                                        <div className="h-11 w-11 rounded-lg bg-rose-50 flex items-center justify-center">
                                            <Clock className="h-5 w-5 text-rose-500" />
                                        </div>
                                    </div>

                                    <div className="mt-3">
                                        <span className="text-xs px-2 py-1 rounded-md bg-rose-100 text-rose-600">
                                            Stage 0
                                        </span>
                                    </div>
                                </div>

                                {/* HOLD */}
                                <div className="rounded-xl border border-violet-300 bg-violet-50 p-5 hover:shadow-md transition-all duration-300">
                                    <div className="flex items-center justify-between">
                                        <div className="space-y-1">
                                            <p className="text-[11px] font-semibold text-[#64748b] uppercase tracking-wide">
                                                Hold
                                            </p>
                                            <p className="text-2xl font-bold text-[#0f172a]">{kpi.hold}</p>
                                            <p className="text-sm font-medium text-violet-600">
                                                {formatCurrency(kpi.holdValue)}
                                            </p>
                                        </div>

                                        <div className="h-11 w-11 rounded-lg bg-violet-50 flex items-center justify-center">
                                            <PauseCircle className="h-5 w-5 text-violet-500" />
                                        </div>
                                    </div>

                                    <div className="mt-3">
                                        <span className="text-xs px-2 py-1 rounded-md bg-violet-100 text-violet-700">
                                            On Hold
                                        </span>
                                    </div>
                                </div>

                                {/* CANCELLED */}
                                <div className="rounded-xl border border-slate-300 bg-slate-50 p-5 hover:shadow-md transition-all duration-300">
                                    <div className="flex items-center justify-between">
                                        <div className="space-y-1">
                                            <p className="text-[11px] font-semibold text-[#64748b] uppercase tracking-wide">
                                                Cancelled
                                            </p>
                                            <p className="text-2xl font-bold text-[#0f172a]">{kpi.cancelled}</p>
                                            <p className="text-sm font-medium text-slate-600">
                                                {formatCurrency(kpi.cancelledValue)}
                                            </p>
                                        </div>

                                        <div className="h-11 w-11 rounded-lg bg-slate-50 flex items-center justify-center">
                                            <XCircle className="h-5 w-5 text-slate-500" />
                                        </div>
                                    </div>

                                    <div className="mt-3">
                                        <span className="text-xs px-2 py-1 rounded-md bg-slate-100 text-slate-700">
                                            Terminated
                                        </span>
                                    </div>
                                </div>


                            </div>
                        </div>
                    </div>

                    {/* ── TABLE SECTION ── */}
                    <div className="bg-white rounded-xl shadow-xl border border-slate-200 overflow-hidden">
                        {/* Table header bar */}
                        <div
                            className="bg-gradient-to-r from-blue-100 via-white to-indigo-100 border-b border-slate-200"
                            style={{
                                padding: '10px 20px',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'space-between',
                            }}
                        >
                            <div className="flex items-center gap-3">
                                <div className="bg-blue-600/10 p-2 rounded-lg border border-blue-200">
                                    <Package className="h-5 w-5 text-blue-600" />
                                </div>
                                <div>
                                    <h3 className="text-sm font-bold text-[#1e3a8a] uppercase tracking-wider leading-none">Order FMS Records</h3>
                                    <p className="text-[10px] text-slate-500 mt-1 font-medium">
                                        {filtered.length} of {orders.length} total orders
                                    </p>

                                </div>
                            </div>
                            <Badge variant="secondary" className="bg-blue-600 text-white hover:bg-blue-600 border-none font-bold">
                                {filtered.length} Records
                            </Badge>
                        </div>

                        {/* Scrollable table */}
                        <div className="overflow-x-auto">
                            <table
                                style={{
                                    borderCollapse: 'collapse',
                                    width: 'max-content',
                                    minWidth: '100%',
                                    fontSize: 13,
                                }}
                            >
                                <thead className="bg-slate-50 border-b border-slate-200">
                                    <tr>
                                        <th style={{ ...thDetail, position: 'sticky', left: 0, zIndex: 3, minWidth: 40, borderRight: '2px solid rgba(255,255,255,0.2)' }}>S.NO</th>
                                        <SortableHeader label="Order Date & Time" sortKey="timestamp" style={{ ...thDetail, ...(isMobile ? {} : { position: 'sticky', left: 40, zIndex: 3 }), minWidth: 130, borderRight: '1px solid rgba(255,255,255,0.1)' }} />
                                        <SortableHeader label="Buyer ID" sortKey="buyerId" style={{ ...thDetail, ...(isMobile ? {} : { position: 'sticky', left: 170, zIndex: 3 }), minWidth: 90, borderRight: '1px solid rgba(255,255,255,0.1)' }} />
                                        <SortableHeader label="Order ID" sortKey="orderId" style={{ ...thDetail, ...(isMobile ? {} : { position: 'sticky', left: 260, zIndex: 3 }), minWidth: 90, borderRight: '1px solid rgba(255,255,255,0.1)' }} />
                                        <th style={{ ...thDetail, position: 'sticky', left: isMobile ? 40 : 350, zIndex: 3, minWidth: 200, borderRight: '2px solid rgba(255,255,255,0.2)' }}>Client Details</th>
                                        <SortableHeader label="Billing Type" sortKey="billingType" style={{ ...thDetail, minWidth: 110, borderRight: '1px solid rgba(255,255,255,0.1)' }} />
                                        <SortableHeader label="Order Type" sortKey="orderType" style={{ ...thDetail, minWidth: 100 }} />
                                        <th style={{ ...thDetail, minWidth: 300 }}>Billing Address</th>
                                        <th style={{ ...thDetail, minWidth: 300 }}>Shipping Address</th>

                                        <th style={{ ...thDetail, minWidth: 120 }}>Invoice Amount</th>
                                        {/* <th style={{ ...thDetail, minWidth: 170 }}>Total Amt</th>
                                    <th style={{ ...thDetail, minWidth: 140 }}>Image</th> */}
                                        <SortableHeader label="Payment Terms" sortKey="paymentTerms" style={{ ...thDetail, minWidth: 120 }} />
                                        <SortableHeader label="Payment Collection Date" sortKey="paymentCollectionDate" style={{ ...thDetail, minWidth: 160 }} />
                                        <SortableHeader label="Order Taken By" sortKey="orderTakenBy" style={{ ...thDetail, minWidth: 130 }} />
                                        <th style={{ ...thDetail, minWidth: 120 }}>WhatsApp SMS</th>
                                        <SortableHeader label="PI No" sortKey="piLink" style={{ ...thDetail, minWidth: 100 }} />
                                        <th style={{ ...thDetail, minWidth: 80 }}>PI URL</th>

                                        {/* <th style={{ ...thDetail, minWidth: 135 }}>Planned</th>
                                    <th style={{ ...thDetail, minWidth: 120 }}>Actual Delay</th>
                                    <th style={{ ...thDetail, minWidth: 135 }}>FMS User Name</th> */}
                                        {STAGE_NAMES.map((s) => (
                                            <th key={s} style={{ ...thStage, minWidth: s === 'Order QC and Packed Status' ? 175 : 140 }}>
                                                {s}
                                            </th>
                                        ))}
                                    </tr>
                                </thead>
                                <tbody>
                                    {apiLoading && orders.length === 0 ? (
                                        Array.from({ length: 5 }).map((_, i) => (
                                            <tr key={i} className="animate-pulse">
                                                <td colSpan={19 + STAGE_NAMES.length} className="p-10 text-center">
                                                    <div className="flex items-center justify-center gap-3">
                                                        <RefreshCw className="animate-spin h-5 w-5 text-slate-300" />
                                                        <span className="text-slate-400 font-medium text-sm italic">Loading your order data...</span>
                                                    </div>
                                                </td>
                                            </tr>
                                        ))
                                    ) : apiError ? (
                                        <tr>
                                            <td colSpan={19 + STAGE_NAMES.length} className="p-20 text-center">
                                                <div className="flex flex-col items-center gap-3">
                                                    <AlertCircle className="h-10 w-10 text-rose-500" />
                                                    <p className="text-rose-600 font-bold">{apiError}</p>
                                                    <Button onClick={refresh} variant="outline" className="mt-2">Try Again</Button>
                                                </div>
                                            </td>
                                        </tr>
                                    ) : paginated.length === 0 ? (
                                        <tr>
                                            <td
                                                colSpan={19 + STAGE_NAMES.length}
                                                style={{ padding: '60px', textAlign: 'center' }}
                                            >
                                                <div className="flex flex-col items-center gap-3">
                                                    <div className="h-16 w-16 bg-slate-50 rounded-full flex items-center justify-center mb-2">
                                                        <Package className="h-8 w-8 text-slate-300" />
                                                    </div>
                                                    <p className="font-bold text-slate-500 uppercase tracking-widest text-base">No orders found</p>
                                                    <p className="text-sm text-slate-400 font-medium">Try adjusting your filters or search terms.</p>
                                                    <Button variant="outline" size="sm" onClick={clearFilters} className="mt-2 text-slate-600 border-slate-200 font-bold hover:bg-slate-50">
                                                        Reset All Filters
                                                    </Button>
                                                </div>
                                            </td>
                                        </tr>
                                    ) : (
                                        paginated.map((o, idx) => {
                                            const rowBg = idx % 2 === 1 ? '#f9fafb' : '#fff';
                                            const sn = (currentPage - 1) * rowsPerPage + idx + 1;
                                            return (
                                                <tr key={o.id} style={{ borderBottom: '1px solid #e5e7eb', background: rowBg }} className="hover:bg-slate-50 shadow-sm transition-colors">
                                                    <td style={{ ...tdBase, ...stickyBase, left: 0, background: rowBg, minWidth: 40, textAlign: 'center', color: '#888', zIndex: 1, borderRight: '2px solid #e2e8f0' }}>
                                                        {sn}
                                                    </td>
                                                    <td style={{ ...tdBase, ...(isMobile ? {} : { ...stickyBase, left: 40, zIndex: 1 }), background: rowBg, minWidth: 130, fontSize: 12, borderRight: '1px solid #e5e7eb' }}>
                                                        {o.timestamp}
                                                    </td>
                                                    <td style={{ ...tdBase, ...(isMobile ? {} : { ...stickyBase, left: 170, zIndex: 1 }), background: rowBg, minWidth: 90, borderRight: '1px solid #e5e7eb' }}>
                                                        {o.buyerId}
                                                    </td>
                                                    <td style={{ ...tdBase, ...(isMobile ? {} : { ...stickyBase, left: 260, zIndex: 1 }), background: rowBg, minWidth: 90, color: '#185FA5', fontWeight: 600, borderRight: '1px solid #e5e7eb' }}>
                                                        {o.orderId}
                                                    </td>
                                                    <td style={{ ...tdBase, ...stickyBase, left: isMobile ? 40 : 350, background: rowBg, minWidth: 200, zIndex: 1, borderRight: '2px solid #e2e8f0' }}>
                                                        <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
                                                            <span style={{ fontSize: 13, fontWeight: 700, color: '#1a1a2e' }}>{o.name}</span>
                                                            <div className="flex flex-col gap-0.5 text-[11px] font-medium">
                                                                <span className="text-slate-500">{o.mobile}</span>
                                                                <span className="text-blue-600 truncate max-w-[150px]">{o.email}</span>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td style={{ ...tdBase, background: 'inherit' }}>
                                                        <Badge variant="outline" className="bg-slate-100 text-slate-700 border-slate-200 font-bold text-[10px] px-2 py-0">
                                                            {o.billingType}
                                                        </Badge>
                                                    </td>
                                                    <td style={{ ...tdBase, background: 'inherit' }}>
                                                        <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200 font-bold text-[10px] px-2 py-0">
                                                            {o.orderType}
                                                        </Badge>
                                                    </td>
                                                    <td style={{ ...tdBase, background: 'inherit', fontSize: 12, maxWidth: 300, whiteSpace: 'normal', lineHeight: 1.4 }}>{o.billingAddress}</td>
                                                    <td style={{ ...tdBase, background: 'inherit', fontSize: 12, maxWidth: 300, whiteSpace: 'normal', lineHeight: 1.4 }}>{o.shippingAddress}</td>

                                                    <td style={{ ...tdBase, background: 'inherit', fontWeight: 600, color: '#059669' }}>{o.invoiceAmount}</td>
                                                    {/* <td style={{ ...tdBase, background: 'inherit' }}>{o.totalAmtBeforeDiscount}</td> */}
                                                    {/* <td style={{ ...tdBase, background: 'inherit' }}>
                                                    <a href={o.uploadedImageLink} target="_blank" rel="noreferrer" className="text-blue-600 hover:underline font-bold text-[11px] flex items-center gap-1">
                                                        View Image <Box className="h-3 w-3" />
                                                    </a>
                                                </td> */}
                                                    <td style={{ ...tdBase, background: 'inherit' }}>{o.paymentTerms}</td>
                                                    <td style={{ ...tdBase, background: 'inherit', fontSize: 12 }}>{o.paymentCollectionDate}</td>
                                                    <td style={{ ...tdBase, background: 'inherit' }}>
                                                        <div className="flex items-center gap-2">
                                                            <div className="w-6 h-6 rounded-full bg-slate-200 flex items-center justify-center text-[10px] font-bold text-slate-600 uppercase">
                                                                {getInitials(o.orderTakenBy)}
                                                            </div>
                                                            <span className="font-medium">{o.orderTakenBy}</span>
                                                        </div>
                                                    </td>
                                                    <td style={{ ...tdBase, background: 'inherit', textAlign: 'center' }}>
                                                        <span
                                                            style={{
                                                                padding: '2px 8px',
                                                                borderRadius: 20,
                                                                fontSize: 11,
                                                                fontWeight: 600,
                                                                background:
                                                                    o.whatsappSMS === 'Sent' ? '#EAF3DE' : o.whatsappSMS === 'Failed' ? '#FCEBEB' : '#FFFBF0',
                                                                color:
                                                                    o.whatsappSMS === 'Sent' ? '#27500A' : o.whatsappSMS === 'Failed' ? '#791F1F' : '#BA7517',
                                                            }}
                                                        >
                                                            {o.whatsappSMS}
                                                        </span>
                                                    </td>
                                                    <td style={{ ...tdBase, background: 'inherit', textAlign: 'center', fontWeight: 600, color: '#185FA5' }}>
                                                        {o.piLink}
                                                    </td>
                                                    <td style={{ ...tdBase, background: 'inherit', fontSize: 12, textAlign: 'center' }}>
                                                        {o.piUrl ? (
                                                            <a href={o.piUrl} target="_blank" rel="noreferrer" style={{ color: '#185FA5', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4, fontWeight: 700 }}>
                                                                <svg width="11" height="11" viewBox="0 0 12 12" fill="none"><path d="M2 2h3.5M10 2v8H2V4.5M6 6l4-4M7 2h3v3" stroke="#185FA5" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" /></svg>
                                                                View
                                                            </a>
                                                        ) : '—'}
                                                    </td>

                                                    {/* <td style={{ ...tdBase, background: 'inherit', fontSize: 12 }}>{o.planned}</td>
                                                <td style={{ ...tdBase, background: 'inherit', fontWeight: 600, color: o.actualDelay === '—' ? '#94a3b8' : '#e11d48' }}>
                                                    {o.actualDelay}
                                                </td>
                                                <td style={{ ...tdBase, background: 'inherit' }}>{o.fmsUserName}</td> */}
                                                    {STAGE_NAMES.map((_, si) => (
                                                        <td key={si} style={{ ...tdBase, background: 'inherit', textAlign: 'center' }}>
                                                            <StageBadge
                                                                order={o}
                                                                stageIndex={si}
                                                                onClick={() => setStageModal({ order: o, stageIndex: si })}
                                                            />
                                                        </td>
                                                    ))}
                                                </tr>
                                            );
                                        })
                                    )}
                                </tbody>
                            </table>
                        </div>

                        {/* Pagination */}
                        <div
                            style={{
                                padding: '12px 18px',
                                borderTop: '1px solid #e5e7eb',
                                display: 'flex',
                                alignItems: 'center',
                                gap: 12,
                                flexWrap: 'wrap',
                                justifyContent: 'space-between',
                            }}
                        >
                            <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: '#666' }}>
                                <span>Rows</span>
                                <select
                                    value={rowsPerPage}
                                    onChange={(e) => { setRowsPerPage(Number(e.target.value)); setCurrentPage(1); }}
                                    style={{ ...selectStyle, padding: '4px 8px', fontSize: 13 }}
                                >
                                    {[5, 10, 20, 50].map((n) => <option key={n}>{n}</option>)}
                                </select>
                                <span>
                                    Showing {filtered.length === 0 ? 0 : (currentPage - 1) * rowsPerPage + 1}–
                                    {Math.min(currentPage * rowsPerPage, filtered.length)} of {filtered.length}
                                </span>
                            </div>

                            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                                <span style={{ fontSize: 13, color: '#666' }}>
                                    Page {currentPage} of {totalPages}
                                </span>
                                <input
                                    type="number"
                                    value={goPage}
                                    onChange={(e) => setGoPage(e.target.value)}
                                    placeholder="Go"
                                    style={{ ...inputStyle, width: 60, padding: '4px 8px' }}
                                    min={1}
                                    max={totalPages}
                                />
                                <button
                                    onClick={() => {
                                        const p = parseInt(goPage);
                                        if (p >= 1 && p <= totalPages) { setCurrentPage(p); setGoPage(''); }
                                    }}
                                    style={{
                                        background: '#1c2333',
                                        color: '#fff',
                                        border: 'none',
                                        borderRadius: 6,
                                        padding: '5px 14px',
                                        fontSize: 13,
                                        cursor: 'pointer',
                                        fontWeight: 500,
                                    }}
                                >
                                    Go
                                </button>
                                <button
                                    onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                                    disabled={currentPage === 1}
                                    style={{
                                        background: '#fff',
                                        border: '1px solid #e5e7eb',
                                        borderRadius: 6,
                                        padding: '5px 14px',
                                        fontSize: 13,
                                        cursor: currentPage === 1 ? 'not-allowed' : 'pointer',
                                        color: currentPage === 1 ? '#bbb' : '#1a1a2e',
                                    }}
                                >
                                    Previous
                                </button>
                                <button
                                    onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                                    disabled={currentPage === totalPages}
                                    style={{
                                        background: '#1c2333',
                                        color: '#fff',
                                        border: 'none',
                                        borderRadius: 6,
                                        padding: '5px 14px',
                                        fontSize: 13,
                                        cursor: currentPage === totalPages ? 'not-allowed' : 'pointer',
                                        opacity: currentPage === totalPages ? 0.6 : 1,
                                    }}
                                >
                                    Next
                                </button>
                            </div>
                        </div>
                    </div>
                </div >

                {stageModal && (
                    <StageModal
                        state={stageModal}
                        onClose={() => setStageModal(null)}
                    />
                )}
            </div>
        </div>
    )
}
