'use client';

import DashboardLayout from '@/app/dashboard/layout';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Download,
  Filter,
  Pencil,
  Search,
  Trash2,
  Upload,
  ChevronLeft,
  ChevronRight,
  Info,
  Plus
} from 'lucide-react';
import { useState, useRef, useEffect } from 'react';
import { Popover, PopoverContent, PopoverTrigger, PopoverClose } from '@/components/ui/popover';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { cn, currency, getEffectiveDiscountedPrice } from '@/lib/utils';
import { useGlobalContext } from '@/context/Provider';
import DeleteDialog from '@/components/ui/deleteModal';
import { useRouter } from 'next/navigation';
import apis from '@/utils/apis';

export default function GroceryPage() {
  const { userInfo, Toast } = useGlobalContext();
  const rawType = userInfo?.restaurant_id?.type || 'grocery';
  const typeLabel = rawType === 'food' ? 'Grocery' : rawType.charAt(0).toUpperCase() + rawType.slice(1);
  const router = useRouter();
  const [groceries, setGroceries] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [categories, setCategories] = useState<any[]>([]);
  const [pagination, setPagination] = useState({
    total: 0,
    page: 1,
    limit: 20,
    totalPages: 0
  });

  const [searchQuery, setSearchQuery] = useState('');
  const [selectedFilter, setSelectedFilter] = useState<string | null>(null);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [deletingGrocery, setDeletingGrocery] = useState<any>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const [uploadedData, setUploadedData] = useState<any[]>([]);
  const [csvToken, setCsvToken] = useState<string | null>(null);
  const [totalUploaded, setTotalUploaded] = useState(0);
  const [isReviewing, setIsReviewing] = useState(false);
  const [isImporting, setIsImporting] = useState(false);
  const [togglingId, setTogglingId] = useState<string | null>(null);



  const fetchGroceries = async (page: number, search: string, categoryId?: string | null) => {
    setLoading(true);
    try {
      let query = `page=${page}&limit=${pagination.limit}${search ? `&search=${search}` : ''}`;
      if (categoryId) {
        query += `&category_id=${categoryId}`;
      }
      const res = await apis.Item.list(query);
      if (res?.success) {
        setGroceries(res.data);
        setPagination(res.pagination);
      }
    } catch (error: any) {
      Toast.error(error || 'Error fetching groceries');
    } finally {
      setLoading(false);
    }
  };

  const fetchCategories = async () => {
    try {
      const storeId = userInfo?.restaurant_id?._id;
      let query = `pagination=0&type=${rawType}`;
      if (storeId) query += `&store_id=${storeId}`;
      const res = await apis.category.list(query);
      if (res?.data) {
        setCategories(res.data);
      }
    } catch (error: any) {
      console.error('Error fetching categories:', error);
    }
  };

  useEffect(() => {
    if (userInfo?.restaurant_id?._id) {
      fetchCategories();
    }
  }, [userInfo?.restaurant_id?._id]);

  useEffect(() => {
    const timer = setTimeout(() => {
      fetchGroceries(1, searchQuery, selectedFilter);
      if (pagination.page !== 1) {
        setPagination(prev => ({ ...prev, page: 1 }));
      }
    }, 500);
    return () => clearTimeout(timer);
  }, [searchQuery, selectedFilter]);

  const handlePageChange = (newPage: number) => {
    if (newPage >= 1 && newPage <= pagination.totalPages) {
      setPagination(prev => ({ ...prev, page: newPage }));
      fetchGroceries(newPage, searchQuery, selectedFilter);
    }
  };

  const handleCSVUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      if (file.type !== 'text/csv' && !file.name.endsWith('.csv')) {
        Toast.error('Please upload a valid CSV file');
        if (fileInputRef.current) fileInputRef.current.value = '';
        return;
      }

      try {
        Toast.success(`Uploading ${file.name}...`);
        const res = await apis.Common.csvUpload(file);

        if (res?.data) {
          setUploadedData(res.data);
          setCsvToken(res.token);
          setTotalUploaded(res.total);
          setIsReviewing(true);
          Toast.success(res.message || 'CSV read successfully');
        } else {
          Toast.error('Failed to read CSV data');
        }
      } catch (error: any) {
        Toast.error(error || 'Error uploading CSV');
      } finally {
        if (fileInputRef.current) fileInputRef.current.value = '';
      }
    }
  };

  const handleFinalImport = async () => {
    if (!csvToken) return;
    setIsImporting(true);
    try {
      const res = await apis.Common.importCSV(csvToken);
      Toast.success(res?.message || 'Items imported successfully');
      setIsReviewing(false);
      setUploadedData([]);
      setCsvToken(null);
      fetchGroceries(1, searchQuery);
    } catch (error: any) {
      Toast.error(error || 'Error importing items');
    } finally {
      setIsImporting(false);
    }
  };

  const cancelReview = () => {
    setIsReviewing(false);
    setUploadedData([]);
    setCsvToken(null);
  };

  const handleDownloadSample = () => {
    const csvUrl = process.env.NEXT_PUBLIC_GROCERY_SAMPLE_CSV_URL;
    if (csvUrl) {
      window.open(csvUrl, '_blank');
    } else {
      Toast.error('Sample CSV URL not configured');
    }
  };

  const handleEdit = (id: string) => {
    router.push(`/grocery/edit/${id}`);
  };

  const handleDelete = (grocery: any) => {
    setDeletingGrocery(grocery);
    setShowDeleteModal(true);
  };

  const confirmDelete = async () => {
    if (!deletingGrocery) return;
    try {
      await apis.Item.delete?.(deletingGrocery._id);
      Toast.success(`${typeLabel} item deleted successfully`);
      fetchGroceries(pagination.page, searchQuery);
    } catch (error: any) {
      Toast.error(error || `Error deleting ${typeLabel.toLowerCase()} item`);
    } finally {
      setShowDeleteModal(false);
      setDeletingGrocery(null);
    }
  };

  const handleToggleAvailability = async (item: any) => {
    if (togglingId) return;
    setTogglingId(item._id);

    const currentStatus = (item?.availability_status === 'hidden' || item?.is_hidden === true || item?.is_hidden === 'true')
      ? 'hidden'
      : (item?.availability_status === 'out_of_stock' || item?.availability_status === 'in_stock')
      ? item.availability_status
      : item?.is_available === false
      ? 'out_of_stock'
      : 'in_stock';
    const nextIsAvailable = currentStatus !== 'in_stock';
    const nextStatus = nextIsAvailable ? 'in_stock' : 'out_of_stock';

    try {
      const res = await apis.Item.available(item._id, nextIsAvailable);
      if (res?.success || (res?.message && !res?.error)) {
        Toast.success(res?.message || `"${item.name}" availability updated to ${nextIsAvailable ? 'In Stock' : 'Out of Stock'}`);
        setGroceries(prev => prev.map(g => g._id === item._id ? {
          ...g,
          is_available: nextIsAvailable,
          availability_status: nextStatus,
          is_hidden: false,
        } : g));
        fetchGroceries(pagination.page, searchQuery, selectedFilter);
      } else {
        Toast.error(res?.message || 'Failed to update availability');
      }
    } catch (error: any) {
      Toast.error(error?.message || error || 'Error updating availability');
    } finally {
      setTogglingId(null);
    }
  };

  const toggleFilter = (categoryId: string) => {
    setSelectedFilter(prev => prev === categoryId ? null : categoryId);
  };

  return (
    <DashboardLayout>
      <main className="flex-1 bg-gray-50 p-6 overflow-hidden flex flex-col min-h-0">
        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
          <h1 className="text-2xl font-bold text-[#1C1D22]">{typeLabel}</h1>
          <div className="flex flex-wrap gap-3 w-full sm:w-auto">
            <Button variant="theme" className="h-11 flex-1 sm:w-44" onClick={handleDownloadSample}>
              <Download className="w-4 h-4 mr-2" />
              Download Sample
            </Button>
            <input
              type="file"
              ref={fileInputRef}
              onChange={handleCSVUpload}
              accept=".csv"
              className="hidden"
            />
            <Button
              variant="outline"
              className="h-11 flex-1 sm:w-44 bg-white border-gray-200"
              onClick={() => fileInputRef.current?.click()}
            >
              <Upload className="w-4 h-4 mr-2 text-gray-500" />
              CSV Upload
            </Button>
            <Button
              variant="theme"
              className="h-11 flex-1 sm:w-44 font-semibold"
              onClick={() => router.push('/grocery/add')}
            >
              <Plus className="w-4 h-4 mr-2" />
              Add {typeLabel}
            </Button>
          </div>
        </div>

        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 flex flex-col flex-1 min-h-0">
          {/* Header Actions */}
          <div className="p-4 border-b border-gray-100 flex flex-col sm:flex-row gap-4 items-stretch sm:items-center">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <Input
                placeholder={`Search ${typeLabel.toLowerCase()} item`}
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10 h-10 w-full border-gray-100 bg-[#F9FAFB] rounded-lg focus:ring-0"
              />
            </div>

            <Popover>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  className="h-10 border-gray-200 w-full sm:w-auto"
                >
                  <Filter className="w-4 h-4 mr-2 text-gray-500" />
                  Filters
                </Button>
              </PopoverTrigger>
              <PopoverContent align="end" className="w-[calc(100vw-2rem)] sm:w-80 p-5 rounded-2xl shadow-xl border-none bg-white">
                <div className="flex justify-between items-center mb-4">
                  <h3 className="font-bold text-lg">Filters</h3>
                  <PopoverClose asChild>
                    <button
                      onClick={() => {
                        setSelectedFilter(null);
                        setPagination(prev => ({ ...prev, page: 1 }));
                        fetchGroceries(1, searchQuery, null);
                      }}
                      className="text-[var(--primary-brand)] text-sm font-semibold hover:underline"
                    >
                      Reset
                    </button>
                  </PopoverClose>
                </div>

                <div className="mb-6">
                  <h4 className="font-semibold mb-3">Categories</h4>
                  <div className="flex flex-wrap gap-2 max-h-[200px] overflow-y-auto pr-2 custom-scrollbar">
                    {categories && categories.length > 0 ? (
                      categories.map((cat, index) => {
                        const name = typeof cat === 'string' ? cat : (cat.category_name || cat.name || 'Unnamed');
                        const id = typeof cat === 'string' ? cat : (cat._id || `cat-${index}`);

                        return (
                          <button
                            key={id}
                            onClick={() => toggleFilter(id)}
                            className={cn(
                              "px-4 py-2 rounded-lg border text-sm transition-all",
                              selectedFilter === id
                                ? "bg-[var(--primary-brand)] border-[var(--primary-brand)] text-white"
                                : "bg-white border-gray-100 text-gray-600 hover:border-gray-200"
                            )}
                          >
                            {name}
                          </button>
                        );
                      })
                    ) : (
                      <div className="text-sm text-gray-400 py-2">No categories found</div>
                    )}
                  </div>
                </div>

                <PopoverClose asChild>
                  <Button
                    variant="theme"
                    className="w-full h-11 rounded-xl hover:opacity-90 text-white font-semibold shadow-sm"
                    onClick={() => {
                      setPagination(prev => ({ ...prev, page: 1 }));
                      fetchGroceries(1, searchQuery, selectedFilter);
                    }}
                  >
                    Show Results
                  </Button>
                </PopoverClose>
              </PopoverContent>
            </Popover>
          </div>

          {/* Table */}
          <div className="flex-1 overflow-auto">
            <Table>
              <TableHeader className="!bg-[#F9FAFB]">
                <TableRow className="border-none">
                  <TableHead className="font-semibold !text-gray-600">Sr. no.</TableHead>
                  <TableHead className="font-semibold !text-gray-600">Name</TableHead>
                  <TableHead className="font-semibold !text-gray-600">Category</TableHead>
                  <TableHead className="font-semibold !text-gray-600">Stock</TableHead>
                  <TableHead className="font-semibold !text-gray-600">Quantity</TableHead>
                  <TableHead className="font-semibold !text-gray-600">Price</TableHead>
                  <TableHead className="font-semibold !text-gray-600">Availability</TableHead>
                  <TableHead className="font-semibold !text-gray-600 text-center">Action</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
                    <TableCell colSpan={8} className="h-40 text-center text-gray-400">
                      Loading {typeLabel.toLowerCase()} items...
                    </TableCell>
                  </TableRow>
                ) : groceries.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={8} className="h-40 text-center text-gray-400">
                      No {typeLabel.toLowerCase()} items found
                    </TableCell>
                  </TableRow>
                ) : (
                  groceries.map((item, index) => (
                    <TableRow key={item._id} className="border-gray-50 hover:bg-gray-50/50">
                      <TableCell className="!text-gray-600">{(pagination.page - 1) * pagination.limit + index + 1}</TableCell>
                      <TableCell>
                        <div className="flex items-center gap-3">
                          <div className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center border border-gray-200 overflow-hidden">
                            {item.imageUrl ? (
                              <img src={`${apis.BUCKET_ROOT}${item.imageUrl}`} alt={item.name} className="w-full h-full object-cover" />
                            ) : (
                              <Upload className="w-5 h-5 text-gray-400" />
                            )}
                          </div>
                          <div className="flex items-center gap-1.5">
                            <span className="font-medium text-[#1C1D22]">{item.name}</span>
                            {item.barcode_url && item.barcode_url !== 'null' && item.barcode_url !== 'undefined' && item.barcode_url.trim() !== '' && (
                              <Button
                                variant="ghost"
                                size="icon"
                                className="h-6 w-6 rounded-md hover:bg-gray-100 border border-gray-100 flex items-center justify-center shrink-0"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  window.open(item.barcode_url, '_blank');
                                }}
                                title="Download Barcode"
                              >
                                <Download className="w-3.5 h-3.5 text-gray-500" />
                              </Button>
                            )}
                          </div>
                        </div>
                      </TableCell>
                      <TableCell className="!text-gray-600">{item.category?.category_name || item.category_id?.category_name || 'N/A'}</TableCell>
                      <TableCell className="!text-gray-600">{item.stock}</TableCell>
                      <TableCell className="!text-gray-600">{item.quantity} {item.unit}</TableCell>
                      <TableCell className="font-semibold !text-[#1C1D22]">
                        {(() => {
                          const discPrice = getEffectiveDiscountedPrice(item);
                          return discPrice !== null ? (
                            <div className="flex items-center gap-1.5 flex-wrap">
                              <span className="font-semibold text-[#1C1D22]">{currency}{discPrice}</span>
                              <span className="text-xs text-gray-400 line-through">{currency}{item.price}</span>
                            </div>
                          ) : (
                            <span>{currency}{item.price}</span>
                          );
                        })()}
                      </TableCell>
                      <TableCell className="!text-gray-600">
                        {(() => {
                          const currentStatus = (item?.availability_status === 'hidden' || item?.is_hidden === true || item?.is_hidden === 'true')
                            ? 'hidden'
                            : (item?.availability_status === 'out_of_stock' || item?.availability_status === 'in_stock')
                            ? item.availability_status
                            : item?.is_available === false
                            ? 'out_of_stock'
                            : 'in_stock';
                          const isInStock = currentStatus === 'in_stock';
                          const isHidden = currentStatus === 'hidden';
                          const isToggling = togglingId === item._id;

                          return (
                            <div className="flex items-center gap-2.5">
                              <button
                                type="button"
                                disabled={isToggling}
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleToggleAvailability(item);
                                }}
                                className={cn(
                                  "relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-[var(--primary-brand,#FF5200)] focus:ring-offset-1 disabled:opacity-50",
                                  isInStock ? "bg-emerald-500" : "bg-gray-300"
                                )}
                                title={isInStock ? "Click to set Out of Stock" : "Click to set In Stock"}
                              >
                                <span
                                  className={cn(
                                    "pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out",
                                    isInStock ? "translate-x-5" : "translate-x-0"
                                  )}
                                />
                              </button>
                              <span
                                className={cn(
                                  "text-xs font-semibold px-2.5 py-0.5 rounded-full border cursor-pointer select-none transition-all",
                                  isInStock
                                    ? "bg-emerald-50 text-emerald-700 border-emerald-200 hover:bg-emerald-100"
                                    : isHidden
                                    ? "bg-gray-100 text-gray-600 border-gray-200 hover:bg-gray-200"
                                    : "bg-red-50 text-red-700 border-red-200 hover:bg-red-100"
                                )}
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleToggleAvailability(item);
                                }}
                              >
                                {isInStock ? 'In Stock' : isHidden ? 'Hidden' : 'Out of Stock'}
                              </span>
                            </div>
                          );
                        })()}
                      </TableCell>
                      <TableCell>
                        <div className="flex justify-center gap-2">
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8 rounded-lg border border-gray-200 hover:bg-gray-100"
                            onClick={() => handleEdit(item._id)}
                          >
                            <Pencil className="w-4 h-4 text-gray-500" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8 rounded-lg border border-gray-200 hover:bg-red-50 hover:border-red-200"
                            onClick={() => handleDelete(item)}
                          >
                            <Trash2 className="w-4 h-4 text-red-500" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>

          {/* Pagination */}
          <div className="p-4 border-t border-gray-100 flex items-center justify-center gap-2">
            <Button
              variant="ghost"
              size="icon"
              className="w-8 h-8 rounded-full"
              disabled={pagination.page <= 1}
              onClick={() => handlePageChange(pagination.page - 1)}
            >
              <ChevronLeft className="w-4 h-4" />
            </Button>
            <div className="flex gap-1">
              {(() => {
                const totalPages = pagination.totalPages;
                const currentPage = pagination.page;
                let pages: (number | string)[] = [];

                if (totalPages <= 7) {
                  pages = Array.from({ length: totalPages }, (_, i) => i + 1);
                } else {
                  if (currentPage <= 4) {
                    pages = [1, 2, 3, 4, 5, '...', totalPages];
                  } else if (currentPage >= totalPages - 3) {
                    pages = [1, '...', totalPages - 4, totalPages - 3, totalPages - 2, totalPages - 1, totalPages];
                  } else {
                    pages = [1, '...', currentPage - 1, currentPage, currentPage + 1, '...', totalPages];
                  }
                }

                return pages.map((page, index) => {
                  if (page === '...') {
                    return (
                      <span key={`dots-${index}`} className="flex items-center px-1 text-gray-400">
                        ...
                      </span>
                    );
                  }
                  return (
                    <button
                      key={page}
                      onClick={() => handlePageChange(page as number)}
                      className={cn(
                        "w-8 h-8 rounded-full text-sm font-medium transition-all",
                        currentPage === page ? "bg-[var(--primary-brand)] text-white" : "hover:bg-gray-100 text-gray-600"
                      )}
                    >
                      {page}
                    </button>
                  );
                });
              })()}
            </div>
            <Button
              variant="ghost"
              size="icon"
              className="w-8 h-8 rounded-full"
              disabled={pagination.page >= pagination.totalPages}
              onClick={() => handlePageChange(pagination.page + 1)}
            >
              <ChevronRight className="w-4 h-4" />
            </Button>
          </div>
        </div>

        <Dialog open={isReviewing} onOpenChange={setIsReviewing}>
          <DialogContent className="w-[95vw] sm:max-w-5xl max-h-[90vh] flex flex-col p-4 sm:p-8 rounded-2xl sm:rounded-3xl border-none shadow-2xl">
            <DialogHeader className="mb-2">
              <DialogTitle className="text-xl sm:text-2xl font-bold text-[#1C1D22]">Review Uploaded Items</DialogTitle>
            </DialogHeader>

            <div className="bg-blue-50 border border-blue-100 p-3 sm:p-4 rounded-xl sm:rounded-2xl mb-2 flex items-center gap-3">
              <Info className="w-5 h-5 text-blue-500 shrink-0" />
              <p className="text-xs sm:text-sm text-blue-700 leading-relaxed">
                <span className="font-bold">Note:</span> Showing the first 15 items for preview. All <span className="font-bold text-blue-800">{totalUploaded} items</span> will be imported once you confirm.
              </p>
            </div>

            <div className="flex-1 overflow-auto my-2 sm:my-4 border border-gray-100 rounded-xl sm:rounded-2xl bg-white">
              <div className="min-w-[600px]">
                <Table>
                  <TableHeader className="!bg-[#F9FAFB] sticky top-0 z-10">
                    <TableRow className="border-none">
                      <TableHead className="font-semibold !text-gray-600">Sr. no.</TableHead>
                      <TableHead className="font-semibold !text-gray-600">Name</TableHead>
                      <TableHead className="font-semibold !text-gray-600">Category</TableHead>
                      <TableHead className="font-semibold !text-gray-600">Stock</TableHead>
                      <TableHead className="font-semibold !text-gray-600">Quantity</TableHead>
                      <TableHead className="font-semibold !text-gray-600">Price</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {uploadedData.slice(0, 15).map((item, index) => (
                      <TableRow key={index} className="border-gray-50 hover:bg-gray-50/50">
                        <TableCell className="!text-gray-600">{index + 1}</TableCell>
                        <TableCell>
                          <span className="font-medium text-[#1C1D22]">{item.name}</span>
                        </TableCell>
                        <TableCell className="!text-gray-600">{item.category}</TableCell>
                        <TableCell className="!text-gray-600">{item.stock}</TableCell>
                        <TableCell className="!text-gray-600">{item.quantity} {item.unit}</TableCell>
                        <TableCell className="font-semibold !text-[#1C1D22]">
                          {(() => {
                            const discPrice = getEffectiveDiscountedPrice(item);
                            return discPrice !== null ? (
                              <div className="flex items-center gap-1.5 flex-wrap">
                                <span className="font-semibold text-[#1C1D22]">{currency}{discPrice}</span>
                                <span className="text-xs text-gray-400 line-through">{currency}{item.price}</span>
                              </div>
                            ) : (
                              <span>{currency}{item.price}</span>
                            );
                          })()}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </div>

            <DialogFooter className="flex flex-col sm:flex-row justify-between items-center gap-4 mt-4 pt-4 border-t border-gray-100">
              <div className="text-sm sm:text-base font-semibold text-gray-500 bg-gray-50 px-4 py-2 rounded-xl w-full sm:w-auto text-center">
                Total: <span className="text-[#1C1D22]">{totalUploaded}</span> items
              </div>
              <div className="flex gap-3 w-full sm:w-auto">
                <Button
                  variant="outline"
                  className="flex-1 sm:flex-none h-11 px-4 sm:px-8 rounded-xl border-gray-200 font-semibold"
                  onClick={cancelReview}
                >
                  Cancel
                </Button>
                <Button
                  variant="theme"
                  className="flex-1 sm:flex-none h-11 px-4 sm:px-8 rounded-xl font-semibold shadow-lg shadow-orange-100"
                  onClick={handleFinalImport}
                  disabled={isImporting}
                >
                  {isImporting ? 'Importing...' : 'Import all'}
                </Button>
              </div>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        <DeleteDialog
          isOpen={showDeleteModal}
          onClose={() => setShowDeleteModal(false)}
          handleDelete={confirmDelete}
          title={`Delete ${typeLabel} Item`}
          description={`Are you sure you want to delete "${deletingGrocery?.name}"? This action cannot be undone.`}
        />


      </main>
    </DashboardLayout>
  );
}
