import re

with open("resources/js/components/AdminDashboard.tsx", "r", encoding="utf-8") as f:
    lines = f.readlines()

def get_block(start_str, end_strs):
    start_idx = -1
    for i, l in enumerate(lines):
        if start_str in l:
            start_idx = i
            break
    if start_idx == -1: return [], -1, -1
    
    end_idx = -1
    for i in range(start_idx+1, len(lines)):
        for e in end_strs:
            if e in lines[i]:
                end_idx = i
                return lines[start_idx:end_idx], start_idx, end_idx
    return [], -1, -1

# 1. State Variables
search_lines = []
for i, l in enumerate(lines):
    if "const [editingOrder" in l or "const [isCreatingOrder" in l or "const [orderSearch" in l or "const [orderStatusFilter" in l or "const [orderDateFilter" in l:
        search_lines.append(l)

# 2. updateOrderStatus
uos_block, uos_s, uos_e = get_block("const updateOrderStatus", ["  const saveEditedOrder"])

# 3. saveEditedOrder
seo_block, seo_s, seo_e = get_block("const saveEditedOrder", ["  const createNewOrder"])

# 4. createNewOrder
cno_block, cno_s, cno_e = get_block("const createNewOrder", ["  const handleImageUpload", "  const saveContent", "  const uploadImageToPHP"])

# 5. Orders Grid
og_block, og_s, og_e = get_block("              {activeTab === 'orders' && canAccess('orders') && (", ["              {activeTab === 'leads'"])

# 6. Order Editor Modal
oem_block, oem_s, oem_e = get_block("      {editingOrder && (", ["      {editingLead && (", "      {showReceipt && (", "  );"])
if oem_block and "      {editingLead && (" in lines[oem_e]:
    oem_e -= 1

print(f"uos: {uos_s} to {uos_e}")
print(f"seo: {seo_s} to {seo_e}")
print(f"cno: {cno_s} to {cno_e}")
print(f"og: {og_s} to {og_e}")
print(f"oem: {oem_s} to {oem_e}")

# Build OrdersManager.tsx
om_content = """import React, { useState } from 'react';
import { 
  ClipboardList, Edit3, Trash2, Plus, Search, Filter, 
  MapPin, Phone, User, Package, Calendar, Tag, ChevronDown, CheckCircle, X
} from 'lucide-react';
import { Order, Product } from '../../types';

interface OrdersManagerProps {
  orders: Order[];
  updateOrders: (orders: Order[]) => void;
  products: Product[];
  canAccess: (section: string, action?: string) => boolean;
  showToast: (msg: string, type: 'success' | 'error') => void;
  deleteItem: (table: string, id: string) => void;
}

export default function OrdersManager({
  orders, updateOrders, products, canAccess, showToast, deleteItem
}: OrdersManagerProps) {
"""

for l in search_lines:
    om_content += "  " + l.strip() + "\n"

# Add derived state: sortedOrders
om_content += """
  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());
"""

om_content += "".join(uos_block)
om_content += "".join(seo_block)
om_content += "".join(cno_block)

om_content += """
  return (
    <>
"""

if og_block:
    grid_clean = "".join(og_block).replace("              {activeTab === 'orders' && canAccess('orders') && (", "").replace("              )}", "")
    # Fix the trailing ) } of the grid
    if grid_clean.endswith(")}"):
        grid_clean = grid_clean[:-2]
    om_content += grid_clean

om_content += "".join(oem_block)

om_content += """
    </>
  );
}
"""

with open("resources/js/components/admin/OrdersManager.tsx", "w", encoding="utf-8") as f:
    f.write(om_content)

print("OrdersManager.tsx created successfully!")
