import React, { useState } from 'react';
import { 
  ClipboardList, Edit3, Trash2, Plus, Search, Filter, 
  MapPin, Phone, User, Package, Calendar, Tag, ChevronDown, CheckCircle, X, CheckCircle2, RotateCcw, AlertTriangle, Play, Truck, Clock, RefreshCcw
} from 'lucide-react';
import { Order, Product, PriceConfig } from '../../types';

import CourierManager from '../CourierManager';
import { Printer, Send, RefreshCw, Download, Eye } from 'lucide-react';
const API_BASE = '/api';

const downloadCSV = (data: any[], filename: string, headers: string[]) => {
  const csvRows = [];
  csvRows.push(headers.join(','));
  for (const row of data) {
    const values = [
      row.id,
      new Date(row.date).toLocaleString(),
      `"${(row.customerName || '').replace(/"/g, '""')}"`,
      row.phone,
      `"${(row.address || '').replace(/"/g, '""')}"`,
      `"${(row.items || []).map((i: any) => `${i.name} (${i.quantity})`).join(', ')}"`,
      row.subtotal,
      row.deliveryCharge || row.delivery_charge || 0,
      row.total,
      row.status,
      row.source || 'Website'
    ];
    csvRows.push(values.join(','));
  }
  const blob = new Blob([csvRows.join('\n')], { type: 'text/csv' });
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.setAttribute('href', url);
  a.setAttribute('download', filename);
  a.click();
};
interface OrdersManagerProps {
  orders: Order[];
  updateOrders: (orders: Order[]) => void;
  products: Product[];
  canAccess: (section: string, action?: 'view' | 'edit' | 'delete') => boolean;
  showToast: (msg: string, type: 'success' | 'error') => void;
  deleteItem: (table: string, id: string) => void;
  getTenantHeaders: (extra?: Record<string, string>) => Record<string, string>;
  getBanglaName: (bn: string | undefined, en: string) => string;
}



export default function OrdersManager({
  orders, updateOrders, products, canAccess, showToast, deleteItem, getTenantHeaders, getBanglaName
}: OrdersManagerProps) {
  const [orderSearch, setOrderSearch] = React.useState('');
  const [orderDateFilter, setOrderDateFilter] = React.useState('all');
  const [orderStartDate, setOrderStartDate] = React.useState('');
  const [orderEndDate, setOrderEndDate] = React.useState('');
  const [isSaving, setIsSaving] = useState(false);
  const [editingOrder, setEditingOrder] = useState<Order | null>(null);
  const [isCreatingOrder, setIsCreatingOrder] = useState(false);
  const [orderStatusFilter, setOrderStatusFilter] = useState('all');

  const [selectedOrders, setSelectedOrders] = useState<string[]>([]);
  
  const handleSelectOrder = (orderId: string, checked: boolean) => {
    if (checked) {
      setSelectedOrders(prev => [...prev, orderId]);
    } else {
      setSelectedOrders(prev => prev.filter(id => id !== orderId));
    }
  };

  const sendToSteadFast = async (orderId: string) => {
    try {
      const response = await fetch(`${API_BASE}/courier.php?action=send-single`, {
        method: 'POST',
        headers: getTenantHeaders({
          'Content-Type': 'application/json'
        }),
        body: JSON.stringify({ order_id: orderId })
      });
      const data = await response.json();
      if (data.success) {
        showToast('Successfully sent to SteadFast!', 'success');
        updateOrders(orders.map((o: any) => o.id === orderId ? { ...o, courier_consignment_id: data.consignment_id, courier_status: 'pending' } : o));
      } else {
        throw new Error(data.error || 'Failed to send to courier');
      }
    } catch (e: any) {
      showToast(e.message, 'error');
    }
  };

  const printLabel = (orderId: string) => {
    window.open(`${API_BASE}/courier.php?action=label&order_id=${orderId}`, '_blank');
  };
  const sortedOrders = [...orders]
    .filter(o => {
      const matchSearch = orderSearch ? (o.id.toLowerCase().includes(orderSearch.toLowerCase()) || o.customerName?.toLowerCase().includes(orderSearch.toLowerCase()) || o.phone?.includes(orderSearch)) : true;
      const matchStatus = orderStatusFilter !== 'all' ? o.status === orderStatusFilter : true;
      let matchDate = true;
      if (orderDateFilter === 'today') matchDate = new Date(o.date).toDateString() === new Date().toDateString();
      if (orderDateFilter === 'yesterday') {
        const y = new Date(); y.setDate(y.getDate() - 1);
        matchDate = new Date(o.date).toDateString() === y.toDateString();
      }
      return matchSearch && matchStatus && matchDate;
    })
    .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  const updateOrderStatus = async (orderId: string, newStatus: string) => {
    if (!canAccess('orders', 'edit')) {
      showToast('You do not have permission to update orders', 'error');
      return;
    }

    try {
      const response = await fetch(`/api/admin/orders/${orderId}/status`, {
        method: 'PATCH',
        headers: getTenantHeaders({ 'Accept': 'application/json' }),
        body: JSON.stringify({ status: newStatus })
      });

      if (!response.ok) {
        throw new Error('Failed to update status');
      }

      const data = await response.json();

      if (!data.success) {
        throw new Error(data.error || 'Unknown error');
      }

      const updatedOrders = orders.map(o =>
        o.id === orderId ? { ...o, status: newStatus as any } : o
      );
      updateOrders(updatedOrders);

      showToast(`Order status updated to ${newStatus}`, 'success');
    } catch (err: any) {
      showToast('Error updating status: ' + err.message, 'error');
    }
  };

  const saveEditedOrder = async (order: Order) => {
    if (!canAccess('orders', 'edit')) {
      showToast('You do not have permission to update orders', 'error');
      return;
    }

    setIsSaving(true);
    try {
      const response = await fetch(`/api/admin/orders/${order.id}`, {
        method: 'PUT',
        headers: getTenantHeaders({ 'Accept': 'application/json' }),
        body: JSON.stringify(order)
      });

      if (!response.ok) {
        throw new Error('Failed to save order');
      }

      const data = await response.json();

      if (!data.success) {
        throw new Error(data.error || 'Unknown error');
      }

      const updatedOrders = orders.map((o: Order) =>
        o.id === order.id ? order : o
      );
      updateOrders(updatedOrders);
      setEditingOrder(null);

      showToast('Order customized and saved successfully!', 'success');
    } catch (err: any) {
      showToast('Error saving order: ' + err.message, 'error');
    } finally {
      setIsSaving(false);
    }
  };

  const createNewOrder = async (order: Order) => {
    if (!canAccess('orders', 'edit')) {
      showToast('You do not have permission to create orders', 'error');
      return;
    }

    // Validate required fields before submitting
    if (!order.phone || order.phone.trim() === '') {
      showToast('❌ Phone number is required to create an order', 'error');
      return;
    }
    if (!order.customerName || order.customerName.trim() === '') {
      showToast('❌ Customer name is required', 'error');
      return;
    }

    setIsSaving(true);
    try {
      const payload = {
        id: order.id,
        customerName: order.customerName,
        customer_name: order.customerName,
        phone: order.phone.trim(),
        customer_phone: order.phone.trim(),
        address: order.address,
        customer_address: order.address || 'N/A',
        items: order.items,
        subtotal: order.subtotal,
        deliveryCharge: order.deliveryCharge,
        delivery_charge: order.deliveryCharge,
        total: order.total,
        status: order.status || 'pending',
        source: 'Manual',
        confirmed_at: new Date().toISOString()
      };

      const response = await fetch('/api/admin/orders', {
        method: 'POST',
        headers: getTenantHeaders({ 'Accept': 'application/json' }),
        body: JSON.stringify(payload)
      });

      // Read response body for actual error message
      const data = await response.json();

      if (!response.ok || !data.success) {
        throw new Error(data.error || data.message || `Server error: ${response.status}`);
      }

      // Add to the top of the local orders list
      updateOrders([order, ...orders]);
      setEditingOrder(null);
      setIsCreatingOrder(false);
      showToast('✅ New order created successfully!', 'success');
    } catch (err: any) {
      showToast('❌ Error creating order: ' + err.message, 'error');
    } finally {
      setIsSaving(false);
    }
  };


  return (
    <>
      {!editingOrder && (
        <div className="space-y-5 fade-in">

                  {/* ── Header ─────────────────────────────────── */}
                  <div
                    className="rounded-3xl p-6 flex flex-col md:flex-row md:items-center justify-between gap-4 relative overflow-hidden"
                    style={{ background: 'linear-gradient(135deg, #0d0b18, #1a1533)', border: '1px solid rgba(139,92,246,0.2)' }}
                  >
                    <div className="absolute -top-10 -right-10 w-48 h-48 rounded-full blur-3xl opacity-10" style={{ background: '#7c3aed' }} />
                    <div className="relative z-10 flex items-center gap-4">
                      <div
                        className="w-12 h-12 rounded-2xl flex items-center justify-center shrink-0"
                        style={{ background: 'linear-gradient(135deg,#7c3aed,#4f46e5)', boxShadow: '0 0 20px rgba(124,58,237,0.4)' }}
                      >
                        <ClipboardList size={22} className="text-slate-800 dark:text-white" />
                      </div>
                      <div>
                        <h2 className="text-xl font-black text-white leading-none">Order Management</h2>
                        <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">
                          <span className="text-amber-400 font-bold">{orders.filter(o => o.status === 'pending').length} pending</span>
                          {' · '}{sortedOrders.length} visible
                        </p>
                      </div>
                    </div>
                    <div className="relative z-10 flex flex-wrap items-center gap-2">
                      {canAccess('orders', 'edit') && (
                        <button
                          onClick={() => {
                            const newId = `ORD-${Date.now()}`;
                            const emptyOrder: Order = {
                              id: newId, customerName: '', phone: '', address: '',
                              items: [], subtotal: 0, deliveryCharge: 0, total: 0,
                              status: 'pending', source: 'Manual', date: new Date().toISOString()
                            };
                            setEditingOrder(emptyOrder);
                            setIsCreatingOrder(true);
                          }}
                          className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold text-white shadow-lg transition-all hover:scale-105"
                          style={{ background: 'linear-gradient(135deg,#7c3aed,#4f46e5)' }}
                        >
                          <Plus size={16} /> New Order
                        </button>
                      )}
        
                      <button
                        onClick={() => {
                          const headers = ['Order ID', 'Date', 'Customer', 'Phone', 'Address', 'Items', 'Subtotal', 'Delivery', 'Total', 'Status', 'Source'];
                          downloadCSV(sortedOrders, `orders_${new Date().toISOString().split('T')[0]}.csv`, headers);
                        }}
                        className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all hover:scale-105"
                        style={{ background: 'rgba(5,150,105,0.2)', border: '1px solid rgba(5,150,105,0.3)', color: '#6ee7b7' }}
                      >
                        <Download size={16} /> CSV
                      </button>
                    </div>
                  </div>

                  {/* ── Filter Bar ─────────────────────────────── */}
                  <div className="flex flex-wrap gap-2 items-center">
                    {/* Status pills */}
                    {[
                      { label: 'All', value: 'all', color: '#64748b' },
                      { label: '🕐 Pending', value: 'pending', color: '#d97706' },
                      { label: '✅ Confirmed', value: 'Confirmed Order', color: '#2563eb' },
                      { label: '🎉 Completed', value: 'completed', color: '#059669' },
                      { label: '❌ Cancelled', value: 'cancelled', color: '#dc2626' },
                    ].map(s => (
                      <button
                        key={s.value}
                        onClick={() => setOrderStatusFilter(s.value)}
                        className="px-3 py-1.5 rounded-full text-xs font-bold transition-all"
                        style={orderStatusFilter === s.value
                          ? { background: s.color, color: '#fff', boxShadow: `0 0 12px ${s.color}55` }
                          : { background: '#f1f5f9', color: s.color, border: `1px solid ${s.color}33` }
                        }
                      >
                        {s.label}
                        {s.value !== 'all' && (
                          <span className="ml-1 opacity-60">
                            ({orders.filter(o => o.status === s.value).length})
                          </span>
                        )}
                      </button>
                    ))}

                    {/* Date range */}
                    <div className="flex items-center gap-1.5 bg-white border border-slate-200 px-3 py-1.5 rounded-xl ml-auto text-xs text-slate-500">
                      <Calendar size={14} className="text-slate-500 dark:text-slate-400 shrink-0" />
                      <input type="date" value={orderStartDate} onChange={e => setOrderStartDate(e.target.value)}
                        className="bg-transparent border-none outline-none text-xs w-24 text-slate-600" />
                      <span>–</span>
                      <input type="date" value={orderEndDate} onChange={e => setOrderEndDate(e.target.value)}
                        className="bg-transparent border-none outline-none text-xs w-24 text-slate-600" />
                    </div>
                  </div>

                  {/* ── Courier Manager ────────────────────────── */}
                  <CourierManager
                    orders={orders}
                    selectedOrders={selectedOrders}
                    onRefresh={() => {
                      fetch('/api/admin/orders', { headers: getTenantHeaders() })
                        .then(res => res.json())
                        .then(data => {
                          if (data.success && data.data) {
                            const mappedOrders = data.data.map((order: any) => ({
                              id: order.id,
                              session_id: order.session_id,
                              customerName: order.customer_name || 'Anonymous',
                              phone: order.phone || '',
                              address: order.address || '',
                              items: order.items || [],
                              subtotal: order.subtotal || 0,
                              deliveryCharge: order.delivery_charge || 0,
                              total: order.total || 0,
                              status: order.status || 'pending',
                              source: order.source || 'Website',
                              date: order.created_at || new Date().toISOString(),
                              confirmed_at: order.confirmed_at,
                              courier_status: order.courier_status,
                              courier_consignment_id: order.courier_consignment_id,
                              courier_invoice: order.courier_invoice,
                              label_generated: order.label_generated || 0
                            }));
                            updateOrders(mappedOrders);
                          }
                        });
                    }}
                  />

                  {/* ── Select All bar (when some selected) ────── */}
                  {sortedOrders.length > 0 && (
                    <div className="flex items-center gap-3 px-4 py-2.5 rounded-xl bg-slate-50 border border-slate-200">
                      <label className="flex items-center gap-2 cursor-pointer select-none">
                        <input
                          type="checkbox"
                          className="w-4 h-4 rounded accent-violet-600"
                          checked={selectedOrders.length === sortedOrders.length && sortedOrders.length > 0}
                          onChange={e => {
                            if (e.target.checked) setSelectedOrders(sortedOrders.map((o: Order) => o.id));
                            else setSelectedOrders([]);
                          }}
                        />
                        <span className="text-xs font-bold text-slate-600">
                          {selectedOrders.length > 0 ? `${selectedOrders.length} selected` : 'Select all'}
                        </span>
                      </label>
                      <span className="text-xs text-slate-500 dark:text-slate-400 ml-auto">{sortedOrders.length} orders</span>
                    </div>
                  )}

                  {/* ── Order Cards ─────────────────────────────── */}
                  {sortedOrders.length > 0 ? (
                    <div className="space-y-3">
                      {sortedOrders.map((order, index) => {
                        const statusConfig: Record<string, { bg: string; text: string; dot: string; label: string }> = {
                          'pending': { bg: '#fef3c7', text: '#92400e', dot: '#f59e0b', label: '⏳ Pending' },
                          'Confirmed Order': { bg: '#dbeafe', text: '#1e3a8a', dot: '#3b82f6', label: '✅ Confirmed' },
                          'completed': { bg: '#d1fae5', text: '#065f46', dot: '#059669', label: '🎉 Done' },
                          'cancelled': { bg: '#fee2e2', text: '#7f1d1d', dot: '#ef4444', label: '❌ Cancelled' },
                        };
                        const sc = statusConfig[order.status] || statusConfig['pending'];
                        const isSelected = selectedOrders.includes(order.id);

                        return (
                          <div
                            key={order.id}
                            className="bg-white rounded-2xl border overflow-hidden transition-all duration-200 hover:shadow-md"
                            style={{ border: isSelected ? '1.5px solid #7c3aed' : '1px solid #e2e8f0' }}
                          >
                            {/* Card top strip */}
                            <div className="flex items-center justify-between px-4 py-3 border-b border-slate-100 bg-slate-50/50">
                              <div className="flex items-center gap-3">
                                <input
                                  type="checkbox"
                                  className="w-4 h-4 rounded accent-violet-600"
                                  checked={isSelected}
                                  onChange={e => handleSelectOrder(order.id, e.target.checked)}
                                />
                                <span className="text-[10px] font-black text-slate-500 dark:text-slate-400 font-mono">#{index + 1}</span>
                                <span className="text-[10px] font-bold text-slate-500 dark:text-slate-400 truncate max-w-[80px]">{order.id}</span>
                                <span
                                  className="px-2 py-0.5 rounded-full text-[9px] font-black uppercase"
                                  style={{ background: '#e0f2fe', color: '#0369a1' }}
                                >
                                  {order.source || 'Web'}
                                </span>
                              </div>
                              <div className="flex items-center gap-2">
                                <span
                                  className="w-1.5 h-1.5 rounded-full"
                                  style={{ background: sc.dot, boxShadow: `0 0 5px ${sc.dot}` }}
                                />
                                <span className="text-[10px] font-bold" style={{ color: sc.text }}>{sc.label}</span>
                              </div>
                            </div>

                            {/* Card body */}
                            <div className="p-4">
                              <div className="grid grid-cols-1 md:grid-cols-3 gap-3">

                                {/* Customer */}
                                <div className="flex items-start gap-3">
                                  <div
                                    className="w-9 h-9 rounded-xl flex items-center justify-center text-slate-800 dark:text-white font-black text-sm shrink-0"
                                    style={{ background: 'linear-gradient(135deg,#7c3aed,#4f46e5)' }}
                                  >
                                    {(order.customerName || 'A')[0].toUpperCase()}
                                  </div>
                                  <div className="min-w-0">
                                    <p className="font-bold text-slate-800 text-sm truncate">{order.customerName || 'Anonymous'}</p>
                                    <a
                                      href={`tel:${order.phone}`}
                                      className="flex items-center gap-1 text-xs text-violet-600 font-bold mt-0.5 hover:underline"
                                    >
                                      <Phone size={11} /> {order.phone}
                                    </a>
                                    {/* ✅ Quick contact icon buttons */}
                                    {order.phone && (
                                      <div className="flex items-center gap-2 mt-1.5">
                                        <a
                                          href={`tel:${order.phone}`}
                                          title="Call customer"
                                          className="w-7 h-7 flex items-center justify-center rounded-full bg-green-100 text-green-700 hover:bg-green-200 transition-colors shadow-sm"
                                        >
                                          <Phone size={13} />
                                        </a>
                                        <a
                                          href={`https://wa.me/${order.phone.replace(/\D/g, '').replace(/^0/, '880')}`}
                                          target="_blank"
                                          rel="noopener noreferrer"
                                          title="WhatsApp customer"
                                          className="w-7 h-7 flex items-center justify-center rounded-full bg-[#25D366]/10 text-[#25D366] hover:bg-[#25D366]/20 transition-colors shadow-sm"
                                        >
                                          <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" /></svg>
                                        </a>
                                      </div>
                                    )}
                                    <p className="text-[10px] text-slate-500 dark:text-slate-400 mt-0.5 line-clamp-2">{order.address}</p>

                                    {/* ✅ Steadfast Customer Info */}
                                    {order.steadfast_info && (
                                      <div className="mt-2 bg-purple-50 rounded-lg p-2 border border-purple-100 flex items-center justify-between text-[10px]">
                                        <div className="flex flex-col">
                                          <span className="font-bold text-purple-700">Steadfast Record</span>
                                          <span className="text-slate-500">Delivered: {order.steadfast_info.delivered} / Returned: {order.steadfast_info.returned}</span>
                                        </div>
                                        <div className="flex flex-col items-end">
                                          <span className="font-black text-purple-600 text-xs">{order.steadfast_info.success_rate}%</span>
                                          <span className="text-slate-500">Success</span>
                                        </div>
                                      </div>
                                    )}
                                  </div>
                                </div>

                                {/* Products */}
                                <div className="space-y-1">
                                  {order.items.slice(0, 2).map((item: any, i: number) => (
                                    <div key={i} className="flex items-center justify-between text-xs">
                                      <span className="text-slate-600 truncate max-w-[130px]">{item.nameBangla || item.name}</span>
                                      <span className="font-bold text-slate-700 shrink-0">×{item.quantity || 1}</span>
                                    </div>
                                  ))}
                                  {order.items.length > 2 && (
                                    <p className="text-[10px] text-slate-500 dark:text-slate-400">+{order.items.length - 2} more</p>
                                  )}
                                  <div className="pt-1 flex items-center justify-between">
                                    <span className="text-[10px] text-slate-500 dark:text-slate-400">
                                      {new Date(order.date).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: '2-digit' })}
                                      {' '}
                                      {new Date(order.date).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' })}
                                    </span>
                                    <span className="text-base font-black text-violet-700">৳{order.total}</span>
                                  </div>
                                </div>

                                {/* Actions */}
                                <div className="flex flex-col gap-2">
                                  {/* Status selector */}
                                  <select
                                    value={order.status}
                                    onChange={e => updateOrderStatus(order.id, e.target.value)}
                                    disabled={!canAccess('orders', 'edit')}
                                    className="w-full px-3 py-2 rounded-xl text-xs font-bold border-none outline-none cursor-pointer"
                                    style={{ background: sc.bg, color: sc.text }}
                                  >
                                    <option value="pending">⏳ Pending</option>
                                    <option value="Confirmed Order">✅ Confirmed Order</option>
                                    <option value="completed">🎉 Completed</option>
                                    <option value="cancelled">❌ Cancelled</option>
                                  </select>

                                  {/* Courier */}
                                  {order.courier_consignment_id ? (
                                    <div className="flex items-center gap-2">
                                      <span className="flex-1 px-2 py-1.5 rounded-xl text-[10px] font-bold text-center" style={{ background: '#d1fae5', color: '#065f46' }}>
                                        <Truck size={10} className="inline mr-1" />
                                        {order.courier_consignment_id.substring(0, 10)}…
                                      </span>
                                      <button
                                        onClick={() => printLabel(order.id)}
                                        className="p-2 rounded-xl hover:scale-105 transition-all"
                                        style={{ background: '#dbeafe', color: '#1e40af' }}
                                        title="Print Label"
                                      >
                                        <Printer size={14} />
                                      </button>
                                    </div>
                                  ) : (
                                    <button
                                      onClick={() => sendToSteadFast(order.id)}
                                      className="w-full py-2 rounded-xl text-xs font-bold transition-all hover:scale-105"
                                      style={{ background: 'linear-gradient(135deg,#2563eb,#4f46e5)', color: '#fff' }}
                                    >
                                      <Send size={11} className="inline mr-1" /> Send to SteadFast
                                    </button>
                                  )}

                                  {/* Edit / Delete */}
                                  <div className="flex gap-2">
                                    {canAccess('orders', 'edit') && (
                                      <button
                                        onClick={() => setEditingOrder(order)}
                                        className="flex-1 flex items-center justify-center gap-1 py-2 rounded-xl text-xs font-bold transition-all hover:scale-105"
                                        style={{ background: '#ede9fe', color: '#5b21b6' }}
                                      >
                                        <Edit3 size={13} /> Edit
                                      </button>
                                      )}
                                    {canAccess('orders', 'delete') && (
                                      <button
                                        onClick={() => deleteItem('orders', order.id)}
                                        className="flex-1 flex items-center justify-center gap-1 py-2 rounded-xl text-xs font-bold transition-all hover:scale-105"
                                        style={{ background: '#fee2e2', color: '#991b1b' }}
                                      >
                                        <Trash2 size={13} /> Delete
                                      </button>
                                      )}
                                  </div>
                                </div>

                              </div>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  ) : (
                    <div className="flex flex-col items-center justify-center py-20 text-center">
                      <div
                        className="w-16 h-16 rounded-2xl flex items-center justify-center mb-4"
                        style={{ background: 'linear-gradient(135deg,rgba(124,58,237,0.1),rgba(79,70,229,0.1))' }}
                      >
                        <ClipboardList size={28} className="text-violet-400" />
                      </div>
                      <h3 className="text-lg font-black text-slate-700">No orders found</h3>
                      <p className="text-sm text-slate-500 dark:text-slate-400 mt-1">Try changing the filter or date range</p>
                    </div>
                  )}
                </div>
      )}
      {editingOrder && (
        <div className="bg-white rounded-3xl border border-slate-200 overflow-hidden shadow-sm flex flex-col fade-in min-h-[85vh]">
          <div className="relative w-full h-full max-w-4xl mx-auto flex flex-col flex-grow">

            {/* Modal Header */}
            <div className="px-5 py-4 sm:px-6 sm:pt-6 sm:pb-5 flex items-center justify-between border-b border-slate-100 bg-white sticky top-0 z-10">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-2xl flex items-center justify-center text-white"
                  style={{ background: isCreatingOrder ? 'linear-gradient(135deg,#7c3aed,#4f46e5)' : 'linear-gradient(135deg,#059669,#047857)', boxShadow: '0 0 20px rgba(124,58,237,0.2)' }}>
                  {isCreatingOrder ? <Plus size={20} /> : <Edit3 size={20} />}
                </div>
                <div>
                  <h2 className="text-lg font-black text-slate-800 leading-none">
                    {isCreatingOrder ? 'নতুন অর্ডার তৈরি' : `অর্ডার সম্পাদনা`}
                  </h2>
                  <p className="text-[10px] mt-0.5 text-slate-500 font-medium">
                    {isCreatingOrder ? 'Customer details ও product যোগ করুন' : `#${editingOrder.id}`}
                  </p>
                </div>
              </div>
              <button onClick={() => { setEditingOrder(null); setIsCreatingOrder(false); }}
                className="px-4 py-2 rounded-xl flex items-center gap-2 transition-all bg-slate-100 hover:bg-slate-200 text-slate-700 font-bold text-sm active:scale-95">
                <RotateCcw size={16} /> ফিরে যান
              </button>
            </div>

            <div className="p-5 sm:p-8 space-y-6 overflow-y-auto flex-grow pb-32" style={{ scrollbarWidth: 'none' }}>

              {/* ── Customer Info ── */}
              <div className="rounded-2xl p-5 space-y-4 bg-slate-50 border border-slate-200">
                <p className="text-[10px] font-black uppercase tracking-widest text-slate-400">👤 Customer Information</p>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  {/* Name */}
                  <div>
                    <label className="text-[10px] font-black uppercase tracking-wider mb-1.5 block text-slate-600">Customer Name</label>
                    <input
                      type="text"
                      value={(editingOrder as any).customer_name || editingOrder.customerName || ''}
                      onChange={(e) => setEditingOrder({ ...editingOrder, customerName: e.target.value } as any)}
                      placeholder="নাম লিখুন..."
                      className="w-full px-4 py-3 rounded-xl text-sm font-semibold text-slate-800 bg-white border border-slate-200 placeholder-slate-400 focus:border-violet-500 focus:ring-2 focus:ring-violet-500/20 outline-none transition-all"
                    />
                  </div>
                  {/* Phone */}
                  <div>
                    <label className="text-[10px] font-black uppercase tracking-wider mb-1.5 block text-slate-600">Phone Number *</label>
                    <input
                      type="tel"
                      value={editingOrder.phone}
                      onChange={(e) => setEditingOrder({ ...editingOrder, phone: e.target.value })}
                      placeholder="017XXXXXXXX"
                      className="w-full px-4 py-3 rounded-xl text-sm font-semibold text-slate-800 bg-white border border-slate-200 placeholder-slate-400 focus:border-violet-500 focus:ring-2 focus:ring-violet-500/20 outline-none transition-all"
                    />
                    {isCreatingOrder && (!editingOrder.phone || editingOrder.phone.trim() === '') && (
                      <p className="text-[10px] text-red-500 font-bold mt-1 ml-1">⚠️ Phone number is required</p>
                    )}
                  </div>
                  {/* Address */}
                  <div className="sm:col-span-2">
                    <label className="text-[10px] font-black uppercase tracking-wider mb-1.5 block text-slate-600">Delivery Address</label>
                    <input
                      type="text"
                      value={editingOrder.address}
                      onChange={(e) => setEditingOrder({ ...editingOrder, address: e.target.value })}
                      placeholder="বিস্তারিত ঠিকানা..."
                      className="w-full px-4 py-3 rounded-xl text-sm font-semibold text-slate-800 bg-white border border-slate-200 placeholder-slate-400 focus:border-violet-500 focus:ring-2 focus:ring-violet-500/20 outline-none transition-all"
                    />
                  </div>
                </div>
                {/* Status + Delivery Charge */}
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="text-[10px] font-black uppercase tracking-wider mb-1.5 block text-slate-600">Status</label>
                    <select
                      value={editingOrder.status || 'pending'}
                      onChange={(e) => setEditingOrder({ ...editingOrder, status: e.target.value as any })}
                      className="w-full px-4 py-3 rounded-xl text-sm font-semibold text-slate-800 bg-white border border-slate-200 focus:border-violet-500 focus:ring-2 focus:ring-violet-500/20 outline-none transition-all"
                    >
                      <option value="pending">Pending</option>
                      <option value="Confirmed Order">Confirmed</option>
                      <option value="completed">Completed</option>
                      <option value="cancelled">Cancelled</option>
                    </select>
                  </div>
                  <div>
                    <label className="text-[10px] font-black uppercase tracking-wider mb-1.5 block text-slate-600">Delivery Charge (৳)</label>
                    <input
                      type="number" min="0"
                      value={editingOrder.deliveryCharge ?? (editingOrder as any).delivery_charge ?? 0}
                      onChange={(e) => {
                        const dc = parseFloat(e.target.value) || 0;
                        const sub = (editingOrder.items || []).reduce((s, i: any) => s + ((parseFloat(i.price) || 0) * (parseInt(i.quantity) || 1)), 0);
                        setEditingOrder({ ...editingOrder, deliveryCharge: dc, subtotal: sub, total: sub + dc } as any);
                      }}
                      className="w-full px-4 py-3 rounded-xl text-sm font-semibold text-slate-800 bg-white border border-slate-200 focus:border-violet-500 focus:ring-2 focus:ring-violet-500/20 outline-none transition-all"
                    />
                  </div>
                </div>
              </div>

              {/* ── Order Items ── */}
              <div className="rounded-2xl p-5 space-y-3 bg-slate-50 border border-slate-200">
                <p className="text-[10px] font-black uppercase tracking-widest text-slate-400">🛍️ Order Items</p>
                {(editingOrder.items || []).length === 0 && (
                  <div className="text-center py-6 rounded-xl border border-dashed border-slate-300 bg-white">
                    <p className="text-slate-500 text-sm font-medium">কোনো product যোগ করা হয়নি</p>
                  </div>
                )}
                {(editingOrder.items || []).map((item: any, idx: number) => (
                  <div key={idx} className="flex items-center gap-3 p-3 rounded-xl bg-white border border-slate-200 shadow-sm">
                    {item.image
                      ? <img src={item.image} className="w-11 h-11 rounded-xl object-cover shrink-0" />
                      : <div className="w-11 h-11 rounded-xl shrink-0 flex items-center justify-center bg-slate-100 text-slate-400"><Package size={18} /></div>
                    }
                    <div className="flex-grow min-w-0">
                      <p className="text-sm font-bold text-slate-800 truncate">{item.name}</p>
                      <div className="flex items-center gap-2 mt-1">
                        <select
                          value={item.size}
                          onChange={(e) => {
                            const newSize = e.target.value;
                            const product = products.find(p => p.id === item.id || p.id === item.product_id || p.name === item.name);
                            if (product) {
                              let newPrice = 0;
                              let configs: Record<string, PriceConfig> = {};
                              if (product.priceConfigs) { try { configs = typeof product.priceConfigs === 'string' ? JSON.parse(product.priceConfigs) : product.priceConfigs; const ms = Object.keys(configs).find(k => k === newSize); if (ms && configs[ms]?.salePrice) newPrice = configs[ms].salePrice; } catch { } }
                              if (!newPrice && product.priceMap) { try { const pm = typeof product.priceMap === 'string' ? JSON.parse(product.priceMap) : product.priceMap; const ms = Object.keys(pm).find(k => k === newSize); if (ms) newPrice = parseFloat(pm[ms]); } catch { } }
                              if (!newPrice && product.price) newPrice = product.price;
                              if (newPrice > 0) {
                                const ni = [...editingOrder.items]; ni[idx].size = newSize; ni[idx].price = newPrice;
                                const sub = ni.reduce((s, i) => s + ((Number(i.price) || 0) * (Number(i.quantity) || 1)), 0);
                                setEditingOrder({ ...editingOrder, items: ni, subtotal: sub, total: sub + (Number(editingOrder.deliveryCharge || (editingOrder as any).delivery_charge || 0) || 0) });
                              }
                            }
                          }}
                          className="text-[11px] font-bold px-2 py-1 rounded-lg outline-none bg-violet-50 text-violet-700 border-none"
                        >
                          {(() => {
                            const p = products.find(prod => prod.id === item.id || prod.id === item.product_id || prod.name === item.name);
                            if (!p) return <option value={item.size}>{item.size}</option>;
                            let pm: any = {}; if (p.priceMap) { try { pm = typeof p.priceMap === 'string' ? JSON.parse(p.priceMap) : p.priceMap; } catch { } }
                            let cf: any = {}; if (p.priceConfigs) { try { cf = typeof p.priceConfigs === 'string' ? JSON.parse(p.priceConfigs) : p.priceConfigs; } catch { } }
                            const sizes = Object.keys(pm).length > 0 ? Object.keys(pm) : (Object.keys(cf).length > 0 ? Object.keys(cf) : ['Default']);
                            return sizes.map(s => { const d = s === 'Default' ? (p.highlight || 'Pack') : s; return <option key={d} value={d}>{d}</option>; });
                          })()}
                        </select>
                        <span className="text-[11px] font-black text-violet-600">৳{item.price}</span>
                      </div>
                    </div>
                    <div className="flex items-center gap-2 shrink-0">
                      <button
                        onClick={() => { const ni = [...editingOrder.items]; ni[idx].quantity = Math.max(1, (Number(ni[idx].quantity) || 1) - 1); const sub = ni.reduce((s, i) => s + ((Number(i.price) || 0) * (Number(i.quantity) || 1)), 0); setEditingOrder({ ...editingOrder, items: ni, subtotal: sub, total: sub + (Number(editingOrder.deliveryCharge || (editingOrder as any).delivery_charge || 0) || 0) }); }}
                        className="w-7 h-7 rounded-lg flex items-center justify-center font-black text-slate-600 bg-slate-100 hover:bg-slate-200 transition-all">−</button>
                      <span className="w-6 text-center text-sm font-black text-slate-800">{item.quantity}</span>
                      <button
                        onClick={() => { const ni = [...editingOrder.items]; ni[idx].quantity = (Number(ni[idx].quantity) || 1) + 1; const sub = ni.reduce((s, i) => s + ((Number(i.price) || 0) * (Number(i.quantity) || 1)), 0); setEditingOrder({ ...editingOrder, items: ni, subtotal: sub, total: sub + (Number(editingOrder.deliveryCharge || (editingOrder as any).delivery_charge || 0) || 0) }); }}
                        className="w-7 h-7 rounded-lg flex items-center justify-center font-black text-slate-600 bg-slate-100 hover:bg-slate-200 transition-all">+</button>
                      <button
                        onClick={() => { const ni = editingOrder.items.filter((_: any, i: number) => i !== idx); const sub = ni.reduce((s: number, i: any) => s + ((Number(i.price) || 0) * (Number(i.quantity) || 1)), 0); setEditingOrder({ ...editingOrder, items: ni, subtotal: sub, total: sub + (Number(editingOrder.deliveryCharge || (editingOrder as any).delivery_charge || 0) || 0) }); }}
                        className="w-7 h-7 rounded-lg flex items-center justify-center transition-all ml-1 bg-red-50 hover:bg-red-100 text-red-500">
                        <Trash2 size={13} />
                      </button>
                    </div>
                  </div>
                ))}

                {/* Add Product */}
                <div className="flex gap-3 items-center pt-1">
                  <select
                    id="addProductSelect"
                    className="flex-grow px-4 py-3 rounded-xl text-sm font-semibold text-slate-800 bg-white border border-slate-200 outline-none min-w-0"
                  >
                    <option value="">-- Product বেছে নিন --</option>
                    {products.map(p => {
                      let pm: any = {}; if (p.priceMap) { try { pm = typeof p.priceMap === 'string' ? JSON.parse(p.priceMap) : p.priceMap; } catch { } }
                      let cf: any = {}; if (p.priceConfigs) { try { cf = typeof p.priceConfigs === 'string' ? JSON.parse(p.priceConfigs) : p.priceConfigs; } catch { } }
                      const sizes = Object.keys(pm).length > 0 ? Object.keys(pm) : (Object.keys(cf).length > 0 ? Object.keys(cf) : ['Default']);
                      return sizes.map(size => {
                        let fp = p.price || 0;
                        if (cf[size]?.salePrice) fp = cf[size].salePrice;
                        else if (pm[size]) fp = parseFloat(pm[size]);
                        const d = size === 'Default' ? (p.highlight || 'Pack') : size;
                        return <option key={`${p.id}-${size}`} value={JSON.stringify({ id: p.id, name: p.name, size: d, price: fp, image: p.image })}>{p.name} ({d}) — ৳{fp}</option>;
                      });
                    })}
                  </select>
                  <button
                    onClick={() => {
                      const sel = document.getElementById('addProductSelect') as HTMLSelectElement;
                      if (!sel.value) return;
                      const pData = JSON.parse(sel.value);
                      const ni = [...(editingOrder.items || []), { ...pData, quantity: 1 }];
                      const sub = ni.reduce((s, i: any) => s + ((Number(i.price) || 0) * (Number(i.quantity) || 1)), 0);
                      setEditingOrder({ ...editingOrder, items: ni, subtotal: sub, total: sub + (Number(editingOrder.deliveryCharge || (editingOrder as any).delivery_charge || 0) || 0) });
                      sel.value = '';
                    }}
                    className="shrink-0 px-5 py-3 rounded-xl font-black text-sm text-white flex items-center gap-2 transition-all active:scale-95 bg-violet-600 shadow-md hover:bg-violet-700"
                  >
                    <Plus size={16} /> Add
                  </button>
                </div>
              </div>

              {/* ── Order Summary ── */}
              <div className="rounded-2xl p-5 bg-violet-50 border border-violet-100">
                <div className="flex justify-between text-sm font-bold mb-2 text-violet-800">
                  <span>Subtotal</span><span>৳{editingOrder.subtotal || 0}</span>
                </div>
                <div className="flex justify-between text-sm font-bold mb-3 pb-3 border-b border-violet-200 text-violet-800">
                  <span>Delivery Charge</span><span>৳{editingOrder.deliveryCharge || (editingOrder as any).delivery_charge || 0}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-base font-black text-slate-800">Total</span>
                  <span className="text-2xl font-black text-violet-700">৳{editingOrder.total || 0}</span>
                </div>
              </div>

            </div>

            {/* ── Action Buttons (Sticky Footer) ── */}
            <div className="p-4 sm:p-5 border-t border-slate-100 bg-white sticky bottom-[64px] sm:bottom-0 z-10 w-full shadow-[0_-10px_20px_rgba(0,0,0,0.03)] shrink-0">
              <div className="flex gap-3 max-w-4xl mx-auto">
                <button
                  onClick={() => { setEditingOrder(null); setIsCreatingOrder(false); }}
                  className="flex-1 py-3.5 rounded-xl font-black text-sm transition-all bg-white border border-slate-200 text-slate-600 hover:bg-slate-50 shadow-sm"
                >
                  বাতিল
                </button>
                <button
                  onClick={() => isCreatingOrder ? createNewOrder(editingOrder) : saveEditedOrder(editingOrder)}
                  disabled={isSaving}
                  className="flex-[2] py-3.5 rounded-xl font-black text-sm text-white flex items-center justify-center gap-2 transition-all active:scale-[0.98] disabled:opacity-70 disabled:cursor-not-allowed bg-violet-600 hover:bg-violet-700 shadow-md"
                >
                  {isSaving ? <><RefreshCw size={16} className="animate-spin" /> সংরক্ষণ হচ্ছে...</> : <><CheckCircle size={16} /> {isCreatingOrder ? '✅ অর্ডার তৈরি করুন' : '💾 পরিবর্তন সংরক্ষণ'}</>}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

    </>
  );
}
