'use client'

import { useState, useEffect, useCallback } from 'react'
import ProtectedRoute from '@/components/ProtectedRoute'
import Modal from '@/components/Modal'
import LoadingSpinner from '@/components/LoadingSpinner'
import Link from 'next/link'
import { toast } from 'react-hot-toast'
import {
  Package,
  Plus,
  Search,
  Warehouse,
  TrendingDown,
  TrendingUp,
  AlertTriangle,
  ArrowLeft,
  Box,
  CheckCircle2,
  XCircle,
  Edit,
  Trash2,
  Loader2,
  DollarSign,
  Tag
} from 'lucide-react'
import { productsAPI, Product, CreateProductData, UpdateProductData, ProductFilters, categoriesAPI } from '@/lib/api/products'

function InventoryContent() {
  // State Management
  const [products, setProducts] = useState<Product[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  
  // Pagination
  const [currentPage, setCurrentPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [total, setTotal] = useState(0)
  const pageSize = 10

  // Filters
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedCategory, setSelectedCategory] = useState('all')
  const [selectedBrand, setSelectedBrand] = useState('all')

  // Modals
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [showEditModal, setShowEditModal] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [selectedProduct, setSelectedProduct] = useState<Product | null>(null)

  // Form Data
  const [formData, setFormData] = useState<CreateProductData>({
    sku: '',
    name: '',
    nameAr: '',
    description: '',
    categoryId: '',
    brand: '',
    model: '',
    trackBy: 'QUANTITY',
    costPrice: 0,
    sellingPrice: 0,
    minStock: 0,
    maxStock: 100
  })
  const [formErrors, setFormErrors] = useState<Record<string, string>>({})
  const [submitting, setSubmitting] = useState(false)

  // Categories for dropdown
  const [categories, setCategories] = useState<any[]>([])
  const [loadingCategories, setLoadingCategories] = useState(false)

  // Fetch Categories for dropdown
  useEffect(() => {
    const fetchCategories = async () => {
      setLoadingCategories(true)
      try {
        const data = await categoriesAPI.getAll()
        setCategories(data)
      } catch (err) {
        console.error('Failed to load categories:', err)
      } finally {
        setLoadingCategories(false)
      }
    }
    fetchCategories()
  }, [])

  // Fetch Products (with debouncing for search)
  const fetchProducts = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const filters: ProductFilters = {
        page: currentPage,
        pageSize,
      }
      
      if (searchTerm) filters.search = searchTerm
      if (selectedCategory !== 'all') filters.categoryId = selectedCategory
      if (selectedBrand !== 'all') filters.brand = selectedBrand

      const data = await productsAPI.getAll(filters)
      setProducts(data.products)
      setTotal(data.total)
      setTotalPages(data.totalPages)
    } catch (err: any) {
      setError(err.response?.data?.message || 'Failed to load products')
      toast.error('Failed to load products')
    } finally {
      setLoading(false)
    }
  }, [currentPage, searchTerm, selectedCategory, selectedBrand])

  // Debounced search
  useEffect(() => {
    const debounce = setTimeout(() => {
      setCurrentPage(1)
      fetchProducts()
    }, 500)
    return () => clearTimeout(debounce)
  }, [searchTerm])

  // Fetch on filter/page change
  useEffect(() => {
    fetchProducts()
  }, [currentPage, selectedCategory, selectedBrand])

  // Form Validation
  const validateForm = (): boolean => {
    const errors: Record<string, string> = {}
    
    if (!formData.sku || formData.sku.trim().length < 2) {
      errors.sku = 'SKU must be at least 2 characters'
    }
    
    if (!formData.name || formData.name.trim().length < 2) {
      errors.name = 'Name must be at least 2 characters'
    }
    
    if (!formData.categoryId) {
      errors.categoryId = 'Category is required'
    }
    
    if (!formData.costPrice || formData.costPrice <= 0) {
      errors.costPrice = 'Cost price must be greater than 0'
    }
    
    if (!formData.sellingPrice || formData.sellingPrice <= 0) {
      errors.sellingPrice = 'Selling price must be greater than 0'
    }

    setFormErrors(errors)
    return Object.keys(errors).length === 0
  }

  // Create Product
  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!validateForm()) {
      toast.error('Please fix form errors')
      return
    }

    setSubmitting(true)
    try {
      await productsAPI.create(formData)
      toast.success('Product created successfully!')
      setShowCreateModal(false)
      resetForm()
      fetchProducts()
    } catch (err: any) {
      const message = err.response?.data?.message || 'Failed to create product'
      toast.error(message)
      if (err.response?.data?.errors) {
        setFormErrors(err.response.data.errors)
      }
    } finally {
      setSubmitting(false)
    }
  }

  // Edit Product
  const handleEdit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!selectedProduct || !validateForm()) {
      toast.error('Please fix form errors')
      return
    }

    setSubmitting(true)
    try {
      await productsAPI.update(selectedProduct.id, formData as UpdateProductData)
      toast.success('Product updated successfully!')
      setShowEditModal(false)
      resetForm()
      fetchProducts()
    } catch (err: any) {
      const message = err.response?.data?.message || 'Failed to update product'
      toast.error(message)
    } finally {
      setSubmitting(false)
    }
  }

  // Delete Product
  const handleDelete = async () => {
    if (!selectedProduct) return

    setSubmitting(true)
    try {
      await productsAPI.delete(selectedProduct.id)
      toast.success('Product deleted successfully!')
      setShowDeleteDialog(false)
      setSelectedProduct(null)
      fetchProducts()
    } catch (err: any) {
      const message = err.response?.data?.message || 'Failed to delete product'
      toast.error(message)
    } finally {
      setSubmitting(false)
    }
  }

  // Utility Functions
  const resetForm = () => {
    setFormData({
      sku: '',
      name: '',
      nameAr: '',
      description: '',
      categoryId: '',
      brand: '',
      model: '',
      trackBy: 'QUANTITY',
      costPrice: 0,
      sellingPrice: 0,
      minStock: 0,
      maxStock: 100
    })
    setFormErrors({})
    setSelectedProduct(null)
  }

  const openEditModal = (product: Product) => {
    setSelectedProduct(product)
    setFormData({
      sku: product.sku,
      name: product.name,
      nameAr: product.nameAr,
      description: product.description,
      categoryId: product.categoryId,
      brand: product.brand,
      model: product.model,
      trackBy: product.trackBy,
      costPrice: product.costPrice,
      sellingPrice: product.sellingPrice,
      minStock: product.minStock,
      maxStock: product.maxStock
    })
    setShowEditModal(true)
  }

  const openDeleteDialog = (product: Product) => {
    setSelectedProduct(product)
    setShowDeleteDialog(true)
  }

  const getStockStatus = (product: Product) => {
    const stock = product.totalStock || 0
    if (stock === 0) {
      return { label: 'Out of Stock', color: 'bg-red-100 text-red-700', icon: XCircle }
    }
    if (stock < product.minStock) {
      return { label: 'Low Stock', color: 'bg-orange-100 text-orange-700', icon: AlertTriangle }
    }
    if (product.maxStock && stock > product.maxStock) {
      return { label: 'Overstock', color: 'bg-purple-100 text-purple-700', icon: TrendingUp }
    }
    return { label: 'In Stock', color: 'bg-green-100 text-green-700', icon: CheckCircle2 }
  }

  // Calculate stats
  const totalValue = products.reduce((sum, p) => sum + ((p.totalStock || 0) * p.sellingPrice), 0)
  const lowStockCount = products.filter(p => (p.totalStock || 0) < p.minStock).length
  const outOfStockCount = products.filter(p => (p.totalStock || 0) === 0).length

  // Render Form Fields Component
  const FormFields = ({ isEdit = false }: { isEdit?: boolean }) => (
    <div className="space-y-4">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* SKU */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            SKU <span className="text-red-500">*</span>
          </label>
          <input
            type="text"
            value={formData.sku}
            onChange={(e) => setFormData({ ...formData, sku: e.target.value })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
            placeholder="PROD-001"
          />
          {formErrors.sku && <p className="text-red-500 text-xs mt-1">{formErrors.sku}</p>}
        </div>

        {/* Category */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Category <span className="text-red-500">*</span>
          </label>
          <select
            value={formData.categoryId}
            onChange={(e) => setFormData({ ...formData, categoryId: e.target.value })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
            disabled={loadingCategories}
          >
            <option value="">Select Category</option>
            {categories.map(cat => (
              <option key={cat.id} value={cat.id}>{cat.name}</option>
            ))}
          </select>
          {formErrors.categoryId && <p className="text-red-500 text-xs mt-1">{formErrors.categoryId}</p>}
        </div>
      </div>

      {/* Name */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          Product Name <span className="text-red-500">*</span>
        </label>
        <input
          type="text"
          value={formData.name}
          onChange={(e) => setFormData({ ...formData, name: e.target.value })}
          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
          placeholder="Enter product name"
        />
        {formErrors.name && <p className="text-red-500 text-xs mt-1">{formErrors.name}</p>}
      </div>

      {/* Arabic Name */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          Arabic Name - الاسم بالعربية
        </label>
        <input
          type="text"
          value={formData.nameAr || ''}
          onChange={(e) => setFormData({ ...formData, nameAr: e.target.value })}
          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
          placeholder="أدخل الاسم بالعربية"
          dir="rtl"
        />
      </div>

      {/* Description */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          Description
        </label>
        <textarea
          value={formData.description || ''}
          onChange={(e) => setFormData({ ...formData, description: e.target.value })}
          rows={3}
          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
          placeholder="Product description"
        />
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Brand */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Brand
          </label>
          <input
            type="text"
            value={formData.brand || ''}
            onChange={(e) => setFormData({ ...formData, brand: e.target.value })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
            placeholder="Brand name"
          />
        </div>

        {/* Model */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Model
          </label>
          <input
            type="text"
            value={formData.model || ''}
            onChange={(e) => setFormData({ ...formData, model: e.target.value })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
            placeholder="Model number"
          />
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Cost Price */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Cost Price (SAR) <span className="text-red-500">*</span>
          </label>
          <input
            type="number"
            min="0"
            step="0.01"
            value={formData.costPrice}
            onChange={(e) => setFormData({ ...formData, costPrice: parseFloat(e.target.value) })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
            placeholder="0.00"
          />
          {formErrors.costPrice && <p className="text-red-500 text-xs mt-1">{formErrors.costPrice}</p>}
        </div>

        {/* Selling Price */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Selling Price (SAR) <span className="text-red-500">*</span>
          </label>
          <input
            type="number"
            min="0"
            step="0.01"
            value={formData.sellingPrice}
            onChange={(e) => setFormData({ ...formData, sellingPrice: parseFloat(e.target.value) })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
            placeholder="0.00"
          />
          {formErrors.sellingPrice && <p className="text-red-500 text-xs mt-1">{formErrors.sellingPrice}</p>}
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Min Stock */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Minimum Stock
          </label>
          <input
            type="number"
            min="0"
            value={formData.minStock || 0}
            onChange={(e) => setFormData({ ...formData, minStock: parseInt(e.target.value) })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
          />
        </div>

        {/* Max Stock */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Maximum Stock
          </label>
          <input
            type="number"
            min="0"
            value={formData.maxStock || ''}
            onChange={(e) => setFormData({ ...formData, maxStock: parseInt(e.target.value) })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
          />
        </div>
      </div>

      {/* Profit Margin Display */}
      {formData.costPrice > 0 && formData.sellingPrice > 0 && (
        <div className="bg-green-50 border border-green-200 rounded-lg p-4">
          <div className="flex items-center justify-between">
            <span className="text-sm font-medium text-green-900">Profit Margin:</span>
            <span className="text-lg font-bold text-green-900">
              {(((formData.sellingPrice - formData.costPrice) / formData.costPrice) * 100).toFixed(2)}%
            </span>
          </div>
          <p className="text-xs text-green-700 mt-1">
            Profit per unit: {(formData.sellingPrice - formData.costPrice).toFixed(2)} SAR
          </p>
        </div>
      )}

      {/* Form Actions */}
      <div className="flex items-center justify-end gap-3 pt-4 border-t">
        <button
          type="button"
          onClick={() => {
            isEdit ? setShowEditModal(false) : setShowCreateModal(false)
            resetForm()
          }}
          className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
          disabled={submitting}
        >
          Cancel
        </button>
        <button
          type="submit"
          className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          disabled={submitting}
        >
          {submitting ? (
            <>
              <Loader2 className="h-4 w-4 animate-spin" />
              {isEdit ? 'Updating...' : 'Creating...'}
            </>
          ) : (
            <>
              {isEdit ? 'Update Product' : 'Create Product'}
            </>
          )}
        </button>
      </div>
    </div>
  )

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <Link
                href="/dashboard"
                className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <ArrowLeft className="h-5 w-5 text-gray-600" />
              </Link>
              <div className="flex items-center gap-3">
                <div className="bg-purple-100 p-2 rounded-lg">
                  <Package className="h-6 w-6 text-purple-600" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-gray-900">المخزون والأصول</h1>
                  <p className="text-sm text-gray-600">Inventory & Assets Management</p>
                </div>
              </div>
            </div>

            <div className="flex items-center gap-3">
              <button
                onClick={() => {
                  resetForm()
                  setShowCreateModal(true)
                }}
                className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
              >
                <Plus className="h-4 w-4" />
                Add Product
              </button>
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <div className="bg-white rounded-xl shadow-sm p-6 border border-gray-200">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Total Products</p>
                <p className="text-3xl font-bold text-gray-900 mt-1">{total}</p>
              </div>
              <div className="bg-blue-100 p-3 rounded-lg">
                <Box className="h-8 w-8 text-blue-600" />
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl shadow-sm p-6 border border-gray-200">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Inventory Value</p>
                <p className="text-3xl font-bold text-gray-900 mt-1">
                  {(totalValue / 1000).toFixed(0)}K
                </p>
                <p className="text-xs text-gray-600 mt-1">SAR</p>
              </div>
              <div className="bg-green-100 p-3 rounded-lg">
                <DollarSign className="h-8 w-8 text-green-600" />
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl shadow-sm p-6 border border-gray-200">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Low Stock</p>
                <p className="text-3xl font-bold text-gray-900 mt-1">{lowStockCount}</p>
                <p className="text-xs text-orange-600 mt-1">Need reorder</p>
              </div>
              <div className="bg-orange-100 p-3 rounded-lg">
                <AlertTriangle className="h-8 w-8 text-orange-600" />
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl shadow-sm p-6 border border-gray-200">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Out of Stock</p>
                <p className="text-3xl font-bold text-gray-900 mt-1">{outOfStockCount}</p>
                <p className="text-xs text-red-600 mt-1">Critical</p>
              </div>
              <div className="bg-red-100 p-3 rounded-lg">
                <TrendingDown className="h-8 w-8 text-red-600" />
              </div>
            </div>
          </div>
        </div>

        {/* Filters and Search */}
        <div className="bg-white rounded-xl shadow-sm p-6 border border-gray-200 mb-6">
          <div className="flex flex-col md:flex-row gap-4">
            {/* Search */}
            <div className="flex-1 relative">
              <Search className="absolute right-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400" />
              <input
                type="text"
                placeholder="Search products (name, SKU, description...)"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full pr-10 pl-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
              />
            </div>

            {/* Category Filter */}
            <select
              value={selectedCategory}
              onChange={(e) => setSelectedCategory(e.target.value)}
              className="px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
            >
              <option value="all">All Categories</option>
              {categories.map(cat => (
                <option key={cat.id} value={cat.id}>{cat.name}</option>
              ))}
            </select>

            {/* Brand Filter */}
            <select
              value={selectedBrand}
              onChange={(e) => setSelectedBrand(e.target.value)}
              className="px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
            >
              <option value="all">All Brands</option>
              {/* Extract unique brands from products */}
              {Array.from(new Set(products.map(p => p.brand).filter(Boolean))).map(brand => (
                <option key={brand} value={brand}>{brand}</option>
              ))}
            </select>
          </div>
        </div>

        {/* Products Table */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
          {loading ? (
            <div className="p-12">
              <LoadingSpinner size="lg" message="Loading products..." />
            </div>
          ) : error ? (
            <div className="p-12 text-center">
              <p className="text-red-600 mb-4">{error}</p>
              <button
                onClick={fetchProducts}
                className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700"
              >
                Retry
              </button>
            </div>
          ) : products.length === 0 ? (
            <div className="p-12 text-center">
              <Package className="h-12 w-12 text-gray-400 mx-auto mb-4" />
              <p className="text-gray-600 mb-4">No products found</p>
              <button
                onClick={() => setShowCreateModal(true)}
                className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700"
              >
                Create First Product
              </button>
            </div>
          ) : (
            <>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50 border-b border-gray-200">
                    <tr>
                      <th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">SKU</th>
                      <th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Product</th>
                      <th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Category</th>
                      <th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Stock</th>
                      <th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Price</th>
                      <th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Status</th>
                      <th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200">
                    {products.map((product) => {
                      const status = getStockStatus(product)
                      const StatusIcon = status.icon
                      return (
                        <tr key={product.id} className="hover:bg-gray-50 transition-colors">
                          <td className="px-6 py-4">
                            <span className="text-sm font-mono text-gray-900">{product.sku}</span>
                          </td>
                          <td className="px-6 py-4">
                            <div className="flex items-center gap-3">
                              <div className="h-10 w-10 rounded-lg bg-purple-100 flex items-center justify-center">
                                <Package className="h-5 w-5 text-purple-600" />
                              </div>
                              <div>
                                <p className="font-semibold text-gray-900">{product.name}</p>
                                {product.nameAr && <p className="text-sm text-gray-600">{product.nameAr}</p>}
                              </div>
                            </div>
                          </td>
                          <td className="px-6 py-4">
                            <div className="flex items-center gap-2">
                              <Tag className="h-4 w-4 text-gray-400" />
                              <span className="text-sm text-gray-900">
                                {product.category?.name || 'N/A'}
                              </span>
                            </div>
                          </td>
                          <td className="px-6 py-4">
                            <div>
                              <p className="text-sm font-semibold text-gray-900">
                                {product.totalStock || 0} units
                              </p>
                              <p className="text-xs text-gray-500">Min: {product.minStock}</p>
                            </div>
                          </td>
                          <td className="px-6 py-4">
                            <div>
                              <span className="text-sm font-semibold text-gray-900">
                                {product.sellingPrice} SAR
                              </span>
                              <p className="text-xs text-gray-500">Cost: {product.costPrice} SAR</p>
                            </div>
                          </td>
                          <td className="px-6 py-4">
                            <span className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-medium ${status.color}`}>
                              <StatusIcon className="h-3 w-3" />
                              {status.label}
                            </span>
                          </td>
                          <td className="px-6 py-4">
                            <div className="flex items-center gap-2">
                              <button 
                                onClick={() => openEditModal(product)}
                                className="p-2 hover:bg-green-50 text-green-600 rounded-lg transition-colors"
                                title="Edit"
                              >
                                <Edit className="h-4 w-4" />
                              </button>
                              <button 
                                onClick={() => openDeleteDialog(product)}
                                className="p-2 hover:bg-red-50 text-red-600 rounded-lg transition-colors"
                                title="Delete"
                              >
                                <Trash2 className="h-4 w-4" />
                              </button>
                            </div>
                          </td>
                        </tr>
                      )
                    })}
                  </tbody>
                </table>
              </div>

              {/* Pagination */}
              <div className="px-6 py-4 border-t border-gray-200 flex items-center justify-between">
                <p className="text-sm text-gray-600">
                  Showing <span className="font-semibold">{((currentPage - 1) * pageSize) + 1}</span> to{' '}
                  <span className="font-semibold">{Math.min(currentPage * pageSize, total)}</span> of{' '}
                  <span className="font-semibold">{total}</span> products
                </p>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => setCurrentPage(currentPage - 1)}
                    disabled={currentPage === 1}
                    className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    Previous
                  </button>
                  {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                    const page = i + 1
                    return (
                      <button
                        key={page}
                        onClick={() => setCurrentPage(page)}
                        className={`px-4 py-2 rounded-lg transition-colors ${
                          currentPage === page
                            ? 'bg-purple-600 text-white'
                            : 'border border-gray-300 text-gray-700 hover:bg-gray-50'
                        }`}
                      >
                        {page}
                      </button>
                    )
                  })}
                  {totalPages > 5 && <span className="px-2">...</span>}
                  <button
                    onClick={() => setCurrentPage(currentPage + 1)}
                    disabled={currentPage === totalPages}
                    className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    Next
                  </button>
                </div>
              </div>
            </>
          )}
        </div>
      </main>

      {/* Create Modal */}
      <Modal
        isOpen={showCreateModal}
        onClose={() => {
          setShowCreateModal(false)
          resetForm()
        }}
        title="Create New Product"
        size="xl"
      >
        <form onSubmit={handleCreate}>
          <FormFields />
        </form>
      </Modal>

      {/* Edit Modal */}
      <Modal
        isOpen={showEditModal}
        onClose={() => {
          setShowEditModal(false)
          resetForm()
        }}
        title="Edit Product"
        size="xl"
      >
        <form onSubmit={handleEdit}>
          <FormFields isEdit />
        </form>
      </Modal>

      {/* Delete Confirmation Dialog */}
      {showDeleteDialog && selectedProduct && (
        <div className="fixed inset-0 z-50 overflow-y-auto">
          <div className="fixed inset-0 bg-black bg-opacity-50" onClick={() => setShowDeleteDialog(false)} />
          <div className="flex min-h-screen items-center justify-center p-4">
            <div className="relative bg-white rounded-xl shadow-2xl p-6 max-w-md w-full">
              <div className="flex items-center gap-4 mb-4">
                <div className="bg-red-100 p-3 rounded-full">
                  <Trash2 className="h-6 w-6 text-red-600" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-gray-900">Delete Product</h3>
                  <p className="text-sm text-gray-600">This action cannot be undone</p>
                </div>
              </div>
              <p className="text-gray-700 mb-6">
                Are you sure you want to delete <span className="font-semibold">{selectedProduct.name}</span>?
              </p>
              <div className="flex items-center justify-end gap-3">
                <button
                  onClick={() => {
                    setShowDeleteDialog(false)
                    setSelectedProduct(null)
                  }}
                  className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                  disabled={submitting}
                >
                  Cancel
                </button>
                <button
                  onClick={handleDelete}
                  className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50"
                  disabled={submitting}
                >
                  {submitting ? (
                    <>
                      <Loader2 className="h-4 w-4 animate-spin" />
                      Deleting...
                    </>
                  ) : (
                    'Delete Product'
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default function InventoryPage() {
  return (
    <ProtectedRoute>
      <InventoryContent />
    </ProtectedRoute>
  )
}
