"use client"

import type React from "react"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import {
  Package,
  Grid3X3,
  ImageIcon,
  ShoppingBag,
  LogOut,
  Plus,
  Pencil,
  Trash2,
  X,
  Settings,
  Eye,
  Gift,
} from "lucide-react"
import { AdminProvider, useAdmin, type PaymentSettings, type StoreSettings, type BundleDeal } from "@/lib/admin-context"
import type { Product, Category, Banner, Order } from "@/lib/data"

type ActiveSection = "products" | "categories" | "banners" | "deals" | "orders" | "settings"

function AdminDashboardContent() {
  const router = useRouter()
  const {
    isAuthenticated,
    logout,
    products,
    categories,
    banners,
    orders,
    paymentSettings,
    storeSettings,
    bundleDeals,
    updatePaymentSettings,
    updateStoreSettings,
    addProduct,
    updateProduct,
    deleteProduct,
    addCategory,
    updateCategory,
    deleteCategory,
    addBanner,
    updateBanner,
    deleteBanner,
    addBundleDeal,
    updateBundleDeal,
    deleteBundleDeal,
    updateOrderStatus,
  } = useAdmin()

  const [activeSection, setActiveSection] = useState<ActiveSection>("orders")
  const [showModal, setShowModal] = useState(false)
  const [editingItem, setEditingItem] = useState<Product | Category | Banner | BundleDeal | null>(null)
  const [viewingOrder, setViewingOrder] = useState<Order | null>(null)
  const [mounted, setMounted] = useState(false)

  useEffect(() => {
    setMounted(true)
    const authStatus = sessionStorage.getItem("adminAuth")
    if (authStatus !== "true") {
      router.push("/admin/login")
    }
  }, [router])

  const handleLogout = () => {
    logout()
    router.push("/admin/login")
  }

  if (!mounted) {
    return <div className="min-h-screen bg-muted flex items-center justify-center">Loading...</div>
  }

  if (typeof window !== "undefined" && sessionStorage.getItem("adminAuth") !== "true") {
    return <div className="min-h-screen bg-muted flex items-center justify-center">Redirecting...</div>
  }

  const sidebarItems = [
    { id: "orders" as const, label: "Orders", icon: ShoppingBag, count: orders.length },
    { id: "products" as const, label: "Products", icon: Package, count: products.length },
    { id: "categories" as const, label: "Categories", icon: Grid3X3, count: categories.length },
    { id: "banners" as const, label: "Banners", icon: ImageIcon, count: banners.length },
    { id: "deals" as const, label: "Deals & Offers", icon: Gift, count: bundleDeals.length },
    { id: "settings" as const, label: "Settings", icon: Settings, count: 0 },
  ]

  return (
    <div className="min-h-screen bg-muted flex">
      {/* Sidebar */}
      <aside className="w-64 bg-card border-r border-border shrink-0 hidden md:block relative">
        <div className="p-6 border-b border-border">
          <h1 className="text-xl font-bold text-foreground">
            <span className="text-accent">Vimax</span> Admin
          </h1>
          <p className="text-xs text-muted-foreground">Khan Traders Dashboard</p>
        </div>
        <nav className="p-4 space-y-2">
          {sidebarItems.map((item) => (
            <button
              key={item.id}
              onClick={() => setActiveSection(item.id)}
              className={`w-full flex items-center gap-3 px-4 py-3 rounded-lg transition-colors ${
                activeSection === item.id ? "bg-primary text-primary-foreground" : "text-foreground hover:bg-muted"
              }`}
            >
              <item.icon className="w-5 h-5" />
              <span className="flex-1 text-left">{item.label}</span>
              {item.count > 0 && (
                <span
                  className={`text-xs px-2 py-0.5 rounded ${
                    activeSection === item.id ? "bg-primary-foreground/20" : "bg-muted"
                  }`}
                >
                  {item.count}
                </span>
              )}
            </button>
          ))}
        </nav>
        <div className="absolute bottom-0 left-0 w-64 p-4 border-t border-border">
          <button
            onClick={handleLogout}
            className="w-full flex items-center gap-3 px-4 py-3 text-destructive hover:bg-destructive/10 rounded-lg transition-colors"
          >
            <LogOut className="w-5 h-5" />
            <span>Logout</span>
          </button>
        </div>
      </aside>

      {/* Mobile Header */}
      <div className="md:hidden fixed top-0 left-0 right-0 bg-card border-b border-border p-4 z-50">
        <div className="flex items-center justify-between">
          <h1 className="font-bold text-foreground">Admin Panel</h1>
          <button onClick={handleLogout} className="text-destructive">
            <LogOut className="w-5 h-5" />
          </button>
        </div>
        <div className="flex gap-2 mt-3 overflow-x-auto">
          {sidebarItems.map((item) => (
            <button
              key={item.id}
              onClick={() => setActiveSection(item.id)}
              className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm whitespace-nowrap ${
                activeSection === item.id ? "bg-primary text-primary-foreground" : "bg-muted text-foreground"
              }`}
            >
              <item.icon className="w-4 h-4" />
              {item.label}
            </button>
          ))}
        </div>
      </div>

      {/* Main Content */}
      <main className="flex-1 p-6 md:p-8 mt-24 md:mt-0">
        <div className="max-w-6xl mx-auto">
          {/* Header */}
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-2xl font-bold text-foreground capitalize">{activeSection}</h2>
            {activeSection !== "orders" && activeSection !== "settings" && (
              <button
                onClick={() => {
                  setEditingItem(null)
                  setShowModal(true)
                }}
                className="flex items-center gap-2 bg-primary hover:bg-primary/90 text-primary-foreground px-4 py-2 rounded-lg font-medium transition-colors"
              >
                <Plus className="w-5 h-5" />
                Add New
              </button>
            )}
          </div>

          {/* Settings Section */}
          {activeSection === "settings" && (
            <SettingsSection
              paymentSettings={paymentSettings}
              storeSettings={storeSettings}
              updatePaymentSettings={updatePaymentSettings}
              updateStoreSettings={updateStoreSettings}
            />
          )}

          {/* Orders Section */}
          {activeSection === "orders" && (
            <div className="bg-card rounded-xl border border-border overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-muted">
                    <tr>
                      <th className="text-left p-4 text-sm font-medium text-foreground">Order ID</th>
                      <th className="text-left p-4 text-sm font-medium text-foreground">Customer</th>
                      <th className="text-left p-4 text-sm font-medium text-foreground">Payment</th>
                      <th className="text-left p-4 text-sm font-medium text-foreground">Total</th>
                      <th className="text-left p-4 text-sm font-medium text-foreground">Status</th>
                      <th className="text-left p-4 text-sm font-medium text-foreground">Action</th>
                    </tr>
                  </thead>
                  <tbody>
                    {orders.map((order) => (
                      <tr key={order.id} className="border-t border-border">
                        <td className="p-4 font-medium text-foreground">{order.id}</td>
                        <td className="p-4">
                          <div>
                            <p className="text-foreground">{order.customerName}</p>
                            <p className="text-sm text-muted-foreground">{order.phone}</p>
                          </div>
                        </td>
                        <td className="p-4">
                          <span
                            className={`text-xs px-2 py-1 rounded capitalize ${
                              order.paymentMethod === "cod"
                                ? "bg-amber-100 text-amber-700"
                                : order.paymentMethod === "easypaisa"
                                  ? "bg-green-100 text-green-700"
                                  : order.paymentMethod === "jazzcash"
                                    ? "bg-red-100 text-red-700"
                                    : "bg-blue-100 text-blue-700"
                            }`}
                          >
                            {order.paymentMethod?.toUpperCase() || "COD"}
                          </span>
                        </td>
                        <td className="p-4 text-success font-semibold">Rs. {order.total.toLocaleString()}</td>
                        <td className="p-4">
                          <span
                            className={`text-xs px-2 py-1 rounded capitalize ${
                              order.status === "delivered"
                                ? "bg-success/10 text-success"
                                : order.status === "shipped"
                                  ? "bg-primary/10 text-primary"
                                  : order.status === "processing" || order.status === "confirmed"
                                    ? "bg-yellow-100 text-yellow-700"
                                    : order.status === "cancelled"
                                      ? "bg-destructive/10 text-destructive"
                                      : "bg-muted text-muted-foreground"
                            }`}
                          >
                            {order.status}
                          </span>
                        </td>
                        <td className="p-4">
                          <div className="flex items-center gap-2">
                            <button
                              onClick={() => setViewingOrder(order)}
                              className="p-2 text-primary hover:bg-primary/10 rounded-lg transition-colors"
                            >
                              <Eye className="w-4 h-4" />
                            </button>
                            <select
                              value={order.status}
                              onChange={(e) => updateOrderStatus(order.id, e.target.value as Order["status"])}
                              className="px-2 py-1 rounded-lg border border-border bg-background text-foreground text-sm"
                            >
                              <option value="pending">Pending</option>
                              <option value="confirmed">Confirmed</option>
                              <option value="processing">Processing</option>
                              <option value="shipped">Shipped</option>
                              <option value="delivered">Delivered</option>
                              <option value="cancelled">Cancelled</option>
                            </select>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              {orders.length === 0 && <div className="p-8 text-center text-muted-foreground">No orders yet</div>}
            </div>
          )}

          {/* Products Section */}
          {activeSection === "products" && (
            <div className="bg-card rounded-xl border border-border overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-muted">
                    <tr>
                      <th className="text-left p-4 text-sm font-medium text-foreground">Product</th>
                      <th className="text-left p-4 text-sm font-medium text-foreground">Category</th>
                      <th className="text-left p-4 text-sm font-medium text-foreground">MRP</th>
                      <th className="text-left p-4 text-sm font-medium text-foreground">Price</th>
                      <th className="text-left p-4 text-sm font-medium text-foreground">Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    {products.map((product) => (
                      <tr key={product.id} className="border-t border-border">
                        <td className="p-4">
                          <div className="flex items-center gap-3">
                            <img
                              src={product.image || "/placeholder.svg"}
                              alt={product.name}
                              className="w-12 h-12 object-cover rounded-lg"
                            />
                            <span className="font-medium text-foreground line-clamp-1">{product.name}</span>
                          </div>
                        </td>
                        <td className="p-4 text-muted-foreground capitalize">{product.category.replace("-", " ")}</td>
                        <td className="p-4 text-muted-foreground line-through">Rs. {product.mrp}</td>
                        <td className="p-4 text-success font-semibold">Rs. {product.price}</td>
                        <td className="p-4">
                          <div className="flex gap-2">
                            <button
                              onClick={() => {
                                setEditingItem(product)
                                setShowModal(true)
                              }}
                              className="p-2 text-primary hover:bg-primary/10 rounded-lg transition-colors"
                            >
                              <Pencil className="w-4 h-4" />
                            </button>
                            <button
                              onClick={() => deleteProduct(product.id)}
                              className="p-2 text-destructive hover:bg-destructive/10 rounded-lg transition-colors"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* Categories Section */}
          {activeSection === "categories" && (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              {categories.map((category) => (
                <div key={category.id} className="bg-card rounded-xl border border-border p-4">
                  <div className="flex items-center gap-4">
                    <img
                      src={category.image || "/placeholder.svg"}
                      alt={category.name}
                      className="w-16 h-16 object-cover rounded-full"
                    />
                    <div className="flex-1">
                      <h3 className="font-semibold text-foreground">{category.name}</h3>
                      <p className="text-sm text-muted-foreground">{category.slug}</p>
                    </div>
                    <div className="flex gap-2">
                      <button
                        onClick={() => {
                          setEditingItem(category)
                          setShowModal(true)
                        }}
                        className="p-2 text-primary hover:bg-primary/10 rounded-lg transition-colors"
                      >
                        <Pencil className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => deleteCategory(category.id)}
                        className="p-2 text-destructive hover:bg-destructive/10 rounded-lg transition-colors"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Banners Section */}
          {activeSection === "banners" && (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
              {banners.map((banner) => (
                <div key={banner.id} className="bg-card rounded-xl border border-border overflow-hidden">
                  <img
                    src={banner.image || "/placeholder.svg"}
                    alt={banner.title}
                    className="w-full h-40 object-cover"
                  />
                  <div className="p-4">
                    <h3 className="font-semibold text-foreground">{banner.title}</h3>
                    <p className="text-sm text-muted-foreground line-clamp-1">{banner.subtitle}</p>
                    <div className="flex justify-between items-center mt-3">
                      <span className="text-xs bg-primary/10 text-primary px-2 py-1 rounded">{banner.cta}</span>
                      <div className="flex gap-2">
                        <button
                          onClick={() => {
                            setEditingItem(banner)
                            setShowModal(true)
                          }}
                          className="p-2 text-primary hover:bg-primary/10 rounded-lg transition-colors"
                        >
                          <Pencil className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => deleteBanner(banner.id)}
                          className="p-2 text-destructive hover:bg-destructive/10 rounded-lg transition-colors"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}

          {activeSection === "deals" && (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
              {bundleDeals.map((deal) => (
                <div key={deal.id} className="bg-card rounded-xl border border-border p-4">
                  <div className="mb-4">
                    <h3 className="font-semibold text-foreground">{deal.name}</h3>
                    <p className="text-sm text-muted-foreground line-clamp-2">{deal.description}</p>
                  </div>
                  <div className="space-y-2 mb-4">
                    <div className="flex justify-between">
                      <span className="text-sm text-muted-foreground">Products:</span>
                      <span className="text-sm font-medium">{deal.productIds.length} items</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-sm text-muted-foreground">Bundle Price:</span>
                      <span className="text-sm font-medium text-success">Rs. {deal.bundlePrice}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-sm text-muted-foreground">Discount:</span>
                      <span className="text-sm font-medium text-accent">{deal.discountPercent}%</span>
                    </div>
                  </div>
                  <div className="flex gap-2">
                    <button
                      onClick={() => {
                        setEditingItem(deal)
                        setShowModal(true)
                      }}
                      className="flex-1 p-2 text-primary hover:bg-primary/10 rounded-lg transition-colors text-sm"
                    >
                      <Pencil className="w-4 h-4 inline mr-1" />
                      Edit
                    </button>
                    <button
                      onClick={() => deleteBundleDeal(deal.id)}
                      className="flex-1 p-2 text-destructive hover:bg-destructive/10 rounded-lg transition-colors text-sm"
                    >
                      <Trash2 className="w-4 h-4 inline mr-1" />
                      Delete
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}

          {activeSection === "settings" && (
            <SettingsSection
              paymentSettings={paymentSettings}
              storeSettings={storeSettings}
              updatePaymentSettings={updatePaymentSettings}
              updateStoreSettings={updateStoreSettings}
            />
          )}
        </div>
      </main>

      {/* Modal */}
      {showModal && (
        <AdminModal
          section={activeSection}
          item={editingItem}
          categories={categories}
          products={products}
          onClose={() => {
            setShowModal(false)
            setEditingItem(null)
          }}
          onSaveProduct={(data) => {
            if (editingItem && "price" in editingItem) {
              updateProduct(editingItem.id, data)
            } else {
              addProduct(data as Omit<Product, "id" | "slug">)
            }
            setShowModal(false)
            setEditingItem(null)
          }}
          onSaveCategory={(data) => {
            if (editingItem && "slug" in editingItem && !("price" in editingItem)) {
              updateCategory(editingItem.id, data)
            } else {
              addCategory(data as Omit<Category, "id">)
            }
            setShowModal(false)
            setEditingItem(null)
          }}
          onSaveBanner={(data) => {
            if (editingItem && "cta" in editingItem && !("productIds" in editingItem)) {
              updateBanner(editingItem.id, data)
            } else {
              addBanner(data as Omit<Banner, "id">)
            }
            setShowModal(false)
            setEditingItem(null)
          }}
          onSaveDeal={(data) => {
            if (editingItem && "productIds" in editingItem) {
              updateBundleDeal(editingItem.id, data)
            } else {
              addBundleDeal(data as Omit<BundleDeal, "id">)
            }
            setShowModal(false)
            setEditingItem(null)
          }}
        />
      )}

      {/* Order Detail Modal */}
      {viewingOrder && <OrderDetailModal order={viewingOrder} onClose={() => setViewingOrder(null)} />}
    </div>
  )
}

function SettingsSection({
  paymentSettings,
  storeSettings,
  updatePaymentSettings,
  updateStoreSettings,
}: {
  paymentSettings: PaymentSettings
  storeSettings: StoreSettings
  updatePaymentSettings: (settings: Partial<PaymentSettings>) => void
  updateStoreSettings: (settings: Partial<StoreSettings>) => void
}) {
  const [formData, setFormData] = useState(paymentSettings)
  const [storeFormData, setStoreFormData] = useState(storeSettings)
  const [saved, setSaved] = useState<"" | "payment" | "store">("")
  const [activeTab, setActiveTab] = useState<"store" | "payment">("store")

  const handleSavePayment = () => {
    updatePaymentSettings(formData)
    setSaved("payment")
    setTimeout(() => setSaved(""), 2000)
  }

  const handleSaveStore = () => {
    updateStoreSettings(storeFormData)
    setSaved("store")
    setTimeout(() => setSaved(""), 2000)
  }

  return (
    <div className="space-y-6">
      {/* Tab Navigation */}
      <div className="flex gap-4 border-b border-border">
        <button
          onClick={() => setActiveTab("store")}
          className={`pb-3 px-4 font-medium ${activeTab === "store" ? "text-primary border-b-2 border-primary" : "text-muted-foreground"}`}
        >
          Store Settings
        </button>
        <button
          onClick={() => setActiveTab("payment")}
          className={`pb-3 px-4 font-medium ${activeTab === "payment" ? "text-primary border-b-2 border-primary" : "text-muted-foreground"}`}
        >
          Payment Settings
        </button>
      </div>

      {/* Store Settings Tab */}
      {activeTab === "store" && (
        <div className="space-y-6">
          <div className="bg-card rounded-xl border border-border p-6">
            <h3 className="text-lg font-semibold text-foreground mb-4">Store Information</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">Store Name</label>
                <input
                  type="text"
                  value={storeFormData.storeName}
                  onChange={(e) => setStoreFormData({ ...storeFormData, storeName: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">Location Text</label>
                <input
                  type="text"
                  value={storeFormData.locationText}
                  onChange={(e) => setStoreFormData({ ...storeFormData, locationText: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">Contact Email</label>
                <input
                  type="email"
                  value={storeFormData.contactEmail}
                  onChange={(e) => setStoreFormData({ ...storeFormData, contactEmail: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                />
              </div>
            </div>
          </div>

          <div className="bg-card rounded-xl border border-border p-6">
            <h3 className="text-lg font-semibold text-foreground mb-4">Social Links</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">WhatsApp Link</label>
                <input
                  type="text"
                  value={storeFormData.whatsappLink}
                  onChange={(e) => setStoreFormData({ ...storeFormData, whatsappLink: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  placeholder="https://wa.me/..."
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">Facebook Link</label>
                <input
                  type="text"
                  value={storeFormData.facebookLink}
                  onChange={(e) => setStoreFormData({ ...storeFormData, facebookLink: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  placeholder="https://facebook.com/..."
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">TikTok Link</label>
                <input
                  type="text"
                  value={storeFormData.tiktokLink}
                  onChange={(e) => setStoreFormData({ ...storeFormData, tiktokLink: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  placeholder="https://tiktok.com/..."
                />
              </div>
            </div>
          </div>

          <button
            onClick={handleSaveStore}
            className="bg-primary hover:bg-primary/90 text-primary-foreground px-6 py-3 rounded-lg font-semibold transition-colors"
          >
            {saved === "store" ? "Saved!" : "Save Store Settings"}
          </button>
        </div>
      )}

      {/* Payment Settings Tab */}
      {activeTab === "payment" && (
        <div className="space-y-6">
          <div className="bg-card rounded-xl border border-border p-6">
            <h3 className="text-lg font-semibold text-foreground mb-4">Payment Methods</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">EasyPaisa Number</label>
                <input
                  type="text"
                  value={formData.easypaisaNumber}
                  onChange={(e) => setFormData({ ...formData, easypaisaNumber: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  placeholder="03XX-XXXXXXX"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">JazzCash Number</label>
                <input
                  type="text"
                  value={formData.jazzcashNumber}
                  onChange={(e) => setFormData({ ...formData, jazzcashNumber: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  placeholder="03XX-XXXXXXX"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">WhatsApp Number</label>
                <input
                  type="text"
                  value={formData.whatsappNumber}
                  onChange={(e) => setFormData({ ...formData, whatsappNumber: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  placeholder="03XX-XXXXXXX"
                />
              </div>
            </div>
          </div>

          <div className="bg-card rounded-xl border border-border p-6">
            <h3 className="text-lg font-semibold text-foreground mb-4">Bank Transfer Details</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">Bank Name</label>
                <input
                  type="text"
                  value={formData.bankName}
                  onChange={(e) => setFormData({ ...formData, bankName: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  placeholder="e.g., Meezan Bank"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">Account Title</label>
                <input
                  type="text"
                  value={formData.accountTitle}
                  onChange={(e) => setFormData({ ...formData, accountTitle: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  placeholder="Account holder name"
                />
              </div>
              <div className="md:col-span-2">
                <label className="block text-sm font-medium text-foreground mb-1">IBAN / Account Number</label>
                <input
                  type="text"
                  value={formData.accountNumber}
                  onChange={(e) => setFormData({ ...formData, accountNumber: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground font-mono"
                  placeholder="PK36MEZN0001234567890123"
                />
              </div>
            </div>
          </div>

          <button
            onClick={handleSavePayment}
            className="bg-primary hover:bg-primary/90 text-primary-foreground px-6 py-3 rounded-lg font-semibold transition-colors"
          >
            {saved === "payment" ? "Saved!" : "Save Payment Settings"}
          </button>
        </div>
      )}
    </div>
  )
}

function OrderDetailModal({ order, onClose }: { order: Order; onClose: () => void }) {
  const fullAddress = [order.houseNumber, order.street, order.colony, order.city, order.postalCode]
    .filter(Boolean)
    .join(", ")

  return (
    <div className="fixed inset-0 bg-background/80 backdrop-blur-sm z-50 flex items-center justify-center p-4">
      <div className="bg-card rounded-xl border border-border shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between p-4 border-b border-border sticky top-0 bg-card">
          <h3 className="text-lg font-semibold text-foreground">Order Details - {order.id}</h3>
          <button onClick={onClose} className="p-2 hover:bg-muted rounded-lg">
            <X className="w-5 h-5" />
          </button>
        </div>
        <div className="p-6 space-y-6">
          {/* Customer Info */}
          <div>
            <h4 className="font-semibold text-foreground mb-2">Customer Information</h4>
            <div className="bg-muted rounded-lg p-4 space-y-1">
              <p>
                <strong>Name:</strong> {order.customerName}
              </p>
              <p>
                <strong>Phone:</strong> {order.phone}
              </p>
              <p>
                <strong>Address:</strong> {fullAddress || order.address}
              </p>
              {order.additionalNotes && (
                <p>
                  <strong>Notes:</strong> {order.additionalNotes}
                </p>
              )}
            </div>
          </div>

          {/* Order Items */}
          <div>
            <h4 className="font-semibold text-foreground mb-2">Items Ordered</h4>
            <div className="bg-muted rounded-lg p-4 space-y-2">
              {order.items.map((item, idx) => (
                <div key={idx} className="flex justify-between">
                  <span>
                    {item.productName} x {item.quantity}
                  </span>
                  <span className="font-semibold">Rs. {(item.price * item.quantity).toLocaleString()}</span>
                </div>
              ))}
              <div className="border-t border-border pt-2 mt-2 flex justify-between font-bold">
                <span>Total</span>
                <span className="text-success">Rs. {order.total.toLocaleString()}</span>
              </div>
            </div>
          </div>

          {/* Payment & Status */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <h4 className="font-semibold text-foreground mb-2">Payment Method</h4>
              <span
                className={`text-sm px-3 py-1 rounded capitalize ${
                  order.paymentMethod === "cod"
                    ? "bg-amber-100 text-amber-700"
                    : order.paymentMethod === "easypaisa"
                      ? "bg-green-100 text-green-700"
                      : order.paymentMethod === "jazzcash"
                        ? "bg-red-100 text-red-700"
                        : "bg-blue-100 text-blue-700"
                }`}
              >
                {order.paymentMethod?.toUpperCase() || "COD"}
              </span>
            </div>
            <div>
              <h4 className="font-semibold text-foreground mb-2">Order Status</h4>
              <span
                className={`text-sm px-3 py-1 rounded capitalize ${
                  order.status === "delivered"
                    ? "bg-success/10 text-success"
                    : order.status === "shipped"
                      ? "bg-primary/10 text-primary"
                      : order.status === "cancelled"
                        ? "bg-destructive/10 text-destructive"
                        : "bg-muted text-muted-foreground"
                }`}
              >
                {order.status}
              </span>
            </div>
          </div>

          <div>
            <h4 className="font-semibold text-foreground mb-2">Order Date</h4>
            <p>{order.date}</p>
          </div>
        </div>
      </div>
    </div>
  )
}

interface AdminModalProps {
  section: ActiveSection
  item: Product | Category | Banner | BundleDeal | null
  categories: Category[]
  products: Product[]
  onClose: () => void
  onSaveProduct: (data: Partial<Product>) => void
  onSaveCategory: (data: Partial<Category>) => void
  onSaveBanner: (data: Partial<Banner>) => void
  onSaveDeal: (data: Partial<BundleDeal>) => void
}

function AdminModal({
  section,
  item,
  categories,
  products,
  onClose,
  onSaveProduct,
  onSaveCategory,
  onSaveBanner,
  onSaveDeal,
}: AdminModalProps) {
  const [formData, setFormData] = useState<Record<string, string | number | boolean | string[]>>(() => {
    if (item) {
      if ("price" in item) return { ...item, benefits: item.benefits.join("\n") }
      if ("productIds" in item) return { ...item, productIds: item.productIds }
      return { ...item }
    }
    if (section === "products") {
      return {
        name: "",
        image: "",
        mrp: 0,
        discountPercent: 0,
        price: 0,
        category: categories[0]?.slug || "",
        description: "",
        longDescription: "",
        benefits: "",
        directions: "",
        ingredients: "",
        inStock: true,
      }
    }
    if (section === "categories") {
      return { name: "", slug: "", image: "" }
    }
    if (section === "deals") {
      return { name: "", productIds: [], bundlePrice: 0, discountPercent: 0, description: "" }
    }
    return { image: "", title: "", subtitle: "", cta: "Shop Now" }
  })

  useEffect(() => {
    if (section === "products" && formData.mrp && formData.discountPercent !== undefined) {
      const mrp = Number(formData.mrp)
      const discount = Number(formData.discountPercent)
      const salePrice = Math.round(mrp - (mrp * discount) / 100)
      setFormData((prev) => ({ ...prev, price: salePrice }))
    }
  }, [formData.mrp, formData.discountPercent, section])

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (section === "products") {
      const benefits =
        typeof formData.benefits === "string"
          ? formData.benefits.split("\n").filter((b) => b.trim())
          : (formData.benefits as string[])
      onSaveProduct({ ...formData, benefits } as Partial<Product>)
    } else if (section === "categories") {
      onSaveCategory(formData as Partial<Category>)
    } else if (section === "deals") {
      onSaveDeal(formData as Partial<BundleDeal>)
    } else {
      onSaveBanner(formData as Partial<Banner>)
    }
  }

  return (
    <div className="fixed inset-0 bg-background/80 backdrop-blur-sm z-50 flex items-center justify-center p-4">
      <div className="bg-card rounded-xl border border-border shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between p-4 border-b border-border sticky top-0 bg-card">
          <h3 className="text-lg font-semibold text-foreground">
            {item ? "Edit" : "Add"} {section === "deals" ? "Deal" : section.slice(0, -1)}
          </h3>
          <button onClick={onClose} className="p-2 hover:bg-muted rounded-lg">
            <X className="w-5 h-5" />
          </button>
        </div>
        <form onSubmit={handleSubmit} className="p-4 space-y-4">
          {section === "products" && (
            <>
              <div>
                <label className="block text-sm font-medium mb-1 text-foreground">Product Name</label>
                <input
                  type="text"
                  value={formData.name as string}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 text-foreground">Image URL</label>
                <input
                  type="text"
                  value={formData.image as string}
                  onChange={(e) => setFormData({ ...formData, image: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                />
              </div>
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium mb-1 text-foreground">MRP (Rs.)</label>
                  <input
                    type="number"
                    value={formData.mrp as number}
                    onChange={(e) => setFormData({ ...formData, mrp: Number(e.target.value) })}
                    className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                    required
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium mb-1 text-foreground">Discount %</label>
                  <input
                    type="number"
                    value={formData.discountPercent as number}
                    onChange={(e) => setFormData({ ...formData, discountPercent: Number(e.target.value) })}
                    className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium mb-1 text-foreground">Sale Price</label>
                  <input
                    type="number"
                    value={formData.price as number}
                    readOnly
                    className="w-full px-4 py-2 rounded-lg border border-border bg-muted text-foreground"
                  />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 text-foreground">Category</label>
                <select
                  value={formData.category as string}
                  onChange={(e) => setFormData({ ...formData, category: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                >
                  {categories.map((cat) => (
                    <option key={cat.id} value={cat.slug}>
                      {cat.name}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 text-foreground">Short Description</label>
                <textarea
                  value={formData.description as string}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  rows={2}
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 text-foreground">Long Description</label>
                <textarea
                  value={formData.longDescription as string}
                  onChange={(e) => setFormData({ ...formData, longDescription: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  rows={4}
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 text-foreground">Benefits (one per line)</label>
                <textarea
                  value={formData.benefits as string}
                  onChange={(e) => setFormData({ ...formData, benefits: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  rows={4}
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 text-foreground">Directions to Use</label>
                <textarea
                  value={formData.directions as string}
                  onChange={(e) => setFormData({ ...formData, directions: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  rows={2}
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 text-foreground">Ingredients</label>
                <input
                  type="text"
                  value={formData.ingredients as string}
                  onChange={(e) => setFormData({ ...formData, ingredients: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                />
              </div>
              <div className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={formData.inStock as boolean}
                  onChange={(e) => setFormData({ ...formData, inStock: e.target.checked })}
                  className="w-4 h-4"
                />
                <label className="text-sm font-medium text-foreground">In Stock</label>
              </div>
            </>
          )}

          {section === "categories" && (
            <>
              <div>
                <label className="block text-sm font-medium mb-1 text-foreground">Category Name</label>
                <input
                  type="text"
                  value={formData.name as string}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      name: e.target.value,
                      slug: e.target.value
                        .toLowerCase()
                        .replace(/[^a-z0-9]+/g, "-")
                        .replace(/(^-|-$)/g, ""),
                    })
                  }
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 text-foreground">Slug</label>
                <input
                  type="text"
                  value={formData.slug as string}
                  onChange={(e) => setFormData({ ...formData, slug: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 text-foreground">Image URL</label>
                <input
                  type="text"
                  value={formData.image as string}
                  onChange={(e) => setFormData({ ...formData, image: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                />
              </div>
            </>
          )}

          {section === "banners" && (
            <>
              <div>
                <label className="block text-sm font-medium mb-1 text-foreground">Image URL</label>
                <input
                  type="text"
                  value={formData.image as string}
                  onChange={(e) => setFormData({ ...formData, image: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 text-foreground">Title</label>
                <input
                  type="text"
                  value={formData.title as string}
                  onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 text-foreground">Subtitle</label>
                <input
                  type="text"
                  value={formData.subtitle as string}
                  onChange={(e) => setFormData({ ...formData, subtitle: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 text-foreground">Button Text</label>
                <input
                  type="text"
                  value={formData.cta as string}
                  onChange={(e) => setFormData({ ...formData, cta: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                />
              </div>
            </>
          )}

          {section === "deals" && (
            <>
              <div>
                <label className="block text-sm font-medium mb-1 text-foreground">Deal Name</label>
                <input
                  type="text"
                  value={formData.name as string}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 text-foreground">Description</label>
                <textarea
                  value={formData.description as string}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  rows={2}
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 text-foreground">Select Products</label>
                <div className="space-y-2 max-h-48 overflow-y-auto border border-border rounded-lg p-2 bg-background">
                  {products.map((product) => (
                    <label key={product.id} className="flex items-center gap-2 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={(formData.productIds as string[]).includes(product.id)}
                        onChange={(e) => {
                          if (e.target.checked) {
                            setFormData({
                              ...formData,
                              productIds: [...(formData.productIds as string[]), product.id],
                            })
                          } else {
                            setFormData({
                              ...formData,
                              productIds: (formData.productIds as string[]).filter((id) => id !== product.id),
                            })
                          }
                        }}
                        className="w-4 h-4"
                      />
                      <span className="text-sm text-foreground">{product.name}</span>
                    </label>
                  ))}
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium mb-1 text-foreground">Bundle Price (Rs.)</label>
                  <input
                    type="number"
                    value={formData.bundlePrice as number}
                    onChange={(e) => setFormData({ ...formData, bundlePrice: Number(e.target.value) })}
                    className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                    required
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium mb-1 text-foreground">Discount %</label>
                  <input
                    type="number"
                    value={formData.discountPercent as number}
                    onChange={(e) => setFormData({ ...formData, discountPercent: Number(e.target.value) })}
                    className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground"
                  />
                </div>
              </div>
            </>
          )}

          <div className="flex gap-3 pt-4">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 px-4 py-2 rounded-lg border border-border text-foreground hover:bg-muted transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              className="flex-1 px-4 py-2 rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"
            >
              {item ? "Update" : "Create"}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}

export default function AdminDashboardPage() {
  return (
    <AdminProvider>
      <AdminDashboardContent />
    </AdminProvider>
  )
}
