import React, { useState, useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { useInventory } from '../hooks/useInventory';
import { useOrders } from '../hooks/useOrders';
import { useStats } from '../hooks/useStats';
import { useSettings } from '../hooks/useSettings';
import { supabase } from '../config/supabase';
import Logo from '../components/Logo';
import { 
  LogOut, 
  Package, 
  Calendar, 
  AlertTriangle, 
  Heart, 
  Users,
  Home,
  ShoppingCart,
  PackageOpen,
  Settings,
  ChevronDown,
  Search,
  Filter,
  Plus,
  Minus,
  Phone,
  Mail,
  Loader2,
  MapPin,
  Clock,
  User,
  Key,
  X
} from 'lucide-react';

const UserDashboard: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { user, signOut } = useAuth();
  const { items: inventoryItems, categories, loading: inventoryLoading } = useInventory();
  const { orders, loading: ordersLoading } = useOrders();
  const { stats, loading: statsLoading } = useStats();
  const { settings: pantrySettings } = useSettings();
  
  const [activeTab, setActiveTab] = useState('dashboard');
  const [showProfileMenu, setShowProfileMenu] = useState(false);
  const [cart, setCart] = useState<{[key: string]: number}>({});
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [loadingTimeout, setLoadingTimeout] = useState(false);
  const [expandedOrderId, setExpandedOrderId] = useState<string | null>(null);
  const [imageErrors, setImageErrors] = useState<Set<string>>(new Set());
  
  // Account settings states
  const [showAccountSettings, setShowAccountSettings] = useState(false);
  const [editingEmail, setEditingEmail] = useState(false);
  const [newEmail, setNewEmail] = useState('');
  const [editingPassword, setEditingPassword] = useState(false);
  const [oldPassword, setOldPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [accountLoading, setAccountLoading] = useState(false);
  const [accountError, setAccountError] = useState('');

  // Refs for click-outside detection
  const profileMenuRef = useRef<HTMLDivElement>(null);

  // Timeout for loading screen (10 seconds)
  useEffect(() => {
    const timer = setTimeout(() => {
      setLoadingTimeout(true);
    }, 10000);
    
    return () => clearTimeout(timer);
  }, []);

  // Close dropdowns when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (profileMenuRef.current && !profileMenuRef.current.contains(event.target as Node)) {
        setShowProfileMenu(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // Handle return from checkout
  useEffect(() => {
    if (location.state?.orderPlaced) {
      // Clear cart after successful order
      setCart({});
      // Switch to orders tab to show the new order
      setActiveTab('orders');
      // Show success message
      alert(location.state.message || 'Order placed successfully!');
      // Clear the state
      navigate('/user-dashboard', { replace: true, state: {} });
    } else if (location.state?.returnToInventory) {
      // Return to inventory tab if coming back from checkout
      setActiveTab('inventory');
      navigate('/user-dashboard', { replace: true, state: {} });
    }
  }, [location.state, navigate]);

  const handleSignOut = async () => {
    await signOut();
  };

  const handleUpdateEmail = async () => {
    if (!newEmail || !newEmail.includes('@')) {
      setAccountError('Please enter a valid email address');
      return;
    }

    setAccountLoading(true);
    setAccountError('');

    try {
      // Update email in Supabase Auth
      const { error: authError } = await supabase.auth.updateUser({ email: newEmail });
      if (authError) throw authError;

      alert('Email updated successfully! Please check your new email for verification.');
      setEditingEmail(false);
      setNewEmail('');
      
      // Refresh user data
      window.location.reload();
    } catch (err: any) {
      setAccountError(err.message || 'Failed to update email');
    } finally {
      setAccountLoading(false);
    }
  };

  const handleUpdatePassword = async () => {
    if (!oldPassword) {
      setAccountError('Please enter your current password');
      return;
    }

    if (!newPassword || newPassword.length < 6) {
      setAccountError('New password must be at least 6 characters long');
      return;
    }

    if (newPassword !== confirmPassword) {
      setAccountError('New passwords do not match');
      return;
    }

    if (oldPassword === newPassword) {
      setAccountError('New password must be different from current password');
      return;
    }

    setAccountLoading(true);
    setAccountError('');

    try {
      // First, verify the old password by attempting to sign in
      if (!user?.email) {
        throw new Error('User email not found');
      }

      const { error: signInError } = await supabase.auth.signInWithPassword({
        email: user.email,
        password: oldPassword,
      });

      if (signInError) {
        throw new Error('Current password is incorrect');
      }

      // If old password is correct, update to new password
      const { error: updateError } = await supabase.auth.updateUser({ password: newPassword });
      if (updateError) throw updateError;

      alert('Password updated successfully!');
      setEditingPassword(false);
      setOldPassword('');
      setNewPassword('');
      setConfirmPassword('');
    } catch (err: any) {
      setAccountError(err.message || 'Failed to update password');
    } finally {
      setAccountLoading(false);
    }
  };

  const tabs = [
    { id: 'dashboard', name: 'Overview', icon: Home },
    { id: 'inventory', name: 'Shelves', icon: ShoppingCart },
    { id: 'orders', name: 'My Orders', icon: PackageOpen },
    { id: 'resources', name: 'Resources', icon: Heart },
  ];

  const addToCart = (itemId: string) => {
    setCart(prev => ({ ...prev, [itemId]: (prev[itemId] || 0) + 1 }));
  };

  const removeFromCart = (itemId: string) => {
    setCart(prev => {
      const newCart = { ...prev };
      if (newCart[itemId] > 1) {
        newCart[itemId] -= 1;
      } else {
        delete newCart[itemId];
      }
      return newCart;
    });
  };

  const getCartTotal = () => {
    return Object.values(cart).reduce((sum, qty) => sum + qty, 0);
  };

  // Helper to calculate days until expiry
  const getDaysUntilExpiry = (expiryDate?: string) => {
    if (!expiryDate) return null;
    const days = Math.ceil((new Date(expiryDate).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24));
    return days;
  };

  const filteredInventory = inventoryItems.filter(item => {
    const matchesSearch = item.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      item.description?.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesCategory = selectedCategory === 'all' || item.categoryId === selectedCategory;
    return matchesSearch && matchesCategory;
  });


  // Format date nicely
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  };

  // Get time ago
  const getTimeAgo = (dateString?: string) => {
    if (!dateString) return 'Never';
    const date = new Date(dateString);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
    
    if (diffDays === 0) return 'Today';
    if (diffDays === 1) return '1 day ago';
    if (diffDays < 7) return `${diffDays} days ago`;
    if (diffDays < 30) return `${Math.floor(diffDays / 7)} weeks ago`;
    return `${Math.floor(diffDays / 30)} months ago`;
  };

  // Show loading state only if ALL are loading (initial load) and timeout hasn't occurred
  // After initial load or timeout, show dashboard even if some data is still loading
  const isInitialLoad = inventoryLoading && ordersLoading && statsLoading;
  
  if (isInitialLoad && !loadingTimeout) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <Loader2 className="h-12 w-12 animate-spin text-primary-green mx-auto mb-4" />
          <p className="text-secondary-text">Loading dashboard...</p>
          <p className="text-xs text-secondary-text mt-2">This is taking longer than usual...</p>
        </div>
      </div>
    );
  }

  // Show error message if timeout occurred and still loading
  if (loadingTimeout && isInitialLoad) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center max-w-md mx-auto p-6">
          <AlertTriangle className="h-16 w-16 text-warning mx-auto mb-4" />
          <h2 className="text-xl font-semibold text-deep-forest mb-2">Connection Issue</h2>
          <p className="text-secondary-text mb-6">
            We're having trouble loading your dashboard. Please check your internet connection and try again.
          </p>
          <button
            onClick={() => window.location.reload()}
            className="px-6 py-3 bg-btn-primary text-white rounded-lg hover:bg-btn-primary-hover transition-colors font-medium"
          >
            Reload Page
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen">
      {/* Header */}
      <header className="relative z-50 bg-white/90 backdrop-blur border-b border-light-gray shadow-soft">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center py-4">
            <div className="flex items-center space-x-4">
              <Logo size="md" showText={false} />
              <div>
                <h1 className="text-2xl font-bold text-deep-forest tracking-tight">Food Pantry Portal</h1>
                <p className="text-sm text-secondary-text">Welcome back, {user?.fullName || user?.email?.split('@')[0]}!</p>
              </div>
            </div>
            
            {/* Profile Dropdown */}
            <div className="relative">
              <button
                onClick={() => setShowProfileMenu(!showProfileMenu)}
                className="flex items-center space-x-3 focus:outline-none"
              >
                <div className="w-10 h-10 bg-primary-green rounded-full flex items-center justify-center text-white font-semibold">
                  {user?.fullName?.charAt(0).toUpperCase() || user?.email?.charAt(0).toUpperCase()}
                </div>
                <ChevronDown className="h-4 w-4 text-secondary-text" />
              </button>

              {showProfileMenu && (
                <div className="absolute right-0 mt-2 w-56 bg-white rounded-lg shadow-lg py-1 z-50 border border-light-gray">
                  <div className="px-4 py-3 border-b border-light-gray">
                    <p className="text-sm font-medium text-primary-text">{user?.fullName || 'User'}</p>
                    <p className="text-xs text-secondary-text truncate">{user?.email}</p>
                  </div>
                  <button
                    onClick={() => {
                      setShowAccountSettings(true);
                      setShowProfileMenu(false);
                    }}
                    className="w-full text-left px-4 py-2 text-sm text-primary-text hover:bg-card-hover flex items-center"
                  >
                    <Settings className="h-4 w-4 mr-3" />
                    Account Settings
                  </button>
                  <button
                    onClick={handleSignOut}
                    className="w-full text-left px-4 py-2 text-sm text-warning hover:bg-red-50 flex items-center border-t border-light-gray"
                  >
                    <LogOut className="h-4 w-4 mr-3" />
                    Sign Out
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>
      </header>

      {/* Navigation Tabs */}
      <div className="bg-white/80 backdrop-blur border-b border-light-gray">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <nav className="-mb-px flex space-x-8 overflow-x-auto">
            {tabs.map((tab) => {
              const Icon = tab.icon;
              return (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id)}
                  className={`whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm flex items-center transition-colors ${
                    activeTab === tab.id
                      ? 'border-primary-green text-primary-green'
                      : 'border-transparent text-secondary-text hover:text-primary-text hover:border-light-green'
                  }`}
                >
                  <Icon className="h-5 w-5 mr-2" />
                  {tab.name}
                  {tab.id === 'inventory' && getCartTotal() > 0 && (
                    <span className="ml-2 bg-primary-green text-white text-xs rounded-full px-2 py-0.5">
                      {getCartTotal()}
                    </span>
                  )}
                </button>
              );
            })}
          </nav>
        </div>
      </div>

      {/* Main Content */}
      <main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
        <div className="px-4 sm:px-0 space-y-6">
          
          {/* DASHBOARD TAB */}
          {activeTab === 'dashboard' && (
            <div className="space-y-6">
              {/* Quick Stats */}
              <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div className="bg-gradient-to-br from-primary-green to-deep-forest text-white rounded-2xl shadow-card p-6">
                  <Package className="h-8 w-8 mb-3 opacity-80" />
                  <p className="text-green-100 text-sm font-medium">Items Received</p>
                  <p className="text-3xl font-bold mt-1">{stats.itemsReceived || 0}</p>
                </div>

                <div className="bg-gradient-to-br from-stable to-[#4A9FF5] text-white rounded-2xl shadow-card p-6">
                  <Calendar className="h-8 w-8 mb-3 opacity-80" />
                  <p className="text-blue-100 text-sm font-medium">Last Pickup</p>
                  <p className="text-3xl font-bold mt-1">{getTimeAgo(stats.lastPickup || undefined)}</p>
                </div>

                <div className="bg-gradient-to-br from-expiring to-[#FF9800] text-white rounded-2xl shadow-card p-6">
                  <AlertTriangle className="h-8 w-8 mb-3 opacity-80" />
                  <p className="text-orange-100 text-sm font-medium">Total Orders</p>
                  <p className="text-3xl font-bold mt-1">{stats.totalOrders || 0}</p>
                </div>

                <div className="bg-gradient-to-br from-light-green to-fresh text-white rounded-2xl shadow-card p-6">
                  <PackageOpen className="h-8 w-8 mb-3 opacity-80" />
                  <p className="text-green-100 text-sm font-medium">Pending Orders</p>
                  <p className="text-3xl font-bold mt-1">{stats.pendingOrders || 0}</p>
                </div>
              </div>

              {/* Pickup Alerts - Dynamic based on order status */}
              {(() => {
                // Get all ready orders
                const readyOrders = orders.filter(order => 
                  (order.unit === 'ready' || order.unit === 'Ready') && !order.isPurchased
                );
                
                // Get all pending orders
                const pendingOrders = orders.filter(order => 
                  (order.unit === 'pending' || order.unit === 'Pending') && !order.isPurchased
                );
                
                const allActiveOrders = [...readyOrders, ...pendingOrders];
                
                if (allActiveOrders.length === 0) return null; // Don't show if no pending or ready orders
                
                return (
                  <div className="space-y-4">
                    {readyOrders.map((order) => (
                      <div key={order.id} className="glass-card border-l-4 border-primary-green p-6 bg-green-50/60">
                        <div className="flex items-start">
                          <Calendar className="h-6 w-6 text-primary-green mt-0.5 mr-3" />
                          <div className="flex-1">
                            <h3 className="text-lg font-semibold text-deep-forest">
                              Ready for Pickup
                            </h3>
                            <p className="text-primary-text mt-1">
                              {order.priority || 'Pickup time to be determined'}
                            </p>
                            <p className="text-sm text-secondary-text mt-1">
                              {order.quantity} items • Order #{order.id.substring(0, 8)}
                            </p>
                            <button 
                              onClick={() => setActiveTab('orders')}
                              className="mt-3 inline-flex items-center px-4 py-2 bg-btn-primary text-white rounded-lg hover:bg-btn-primary-hover active:bg-btn-primary-active transition-colors text-sm font-medium"
                            >
                              View Order Details
                            </button>
                          </div>
                        </div>
                      </div>
                    ))}
                    
                    {pendingOrders.map((order) => (
                      <div key={order.id} className="glass-card border-l-4 border-gray-400 p-6 bg-gray-50/80">
                        <div className="flex items-start">
                          <Calendar className="h-6 w-6 text-gray-500 mt-0.5 mr-3" />
                          <div className="flex-1">
                            <h3 className="text-lg font-semibold text-gray-700">
                              Order Pending
                            </h3>
                            <p className="text-gray-600 mt-1">
                              {order.priority || 'Pickup time to be determined'}
                            </p>
                            <p className="text-sm text-secondary-text mt-1">
                              {order.quantity} items • Order #{order.id.substring(0, 8)}
                            </p>
                            <button 
                              onClick={() => setActiveTab('orders')}
                              className="mt-3 inline-flex items-center px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 active:bg-gray-800 transition-colors text-sm font-medium"
                            >
                              View Order Details
                            </button>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                );
              })()}

              {/* Current Food Items - Recent Orders */}
              <div className="glass-card hover:shadow-card transition-shadow">
                <div className="px-6 py-5 border-b border-light-gray">
                  <h3 className="text-lg font-semibold text-deep-forest">Recent Orders</h3>
                  <p className="text-sm text-secondary-text mt-1">Your latest orders and their status</p>
                </div>
                <div className="p-6">
                  {orders.length === 0 ? (
                    <div className="text-center py-8">
                      <PackageOpen className="h-12 w-12 text-secondary-text mx-auto mb-3 opacity-50" />
                      <p className="text-secondary-text">No orders yet</p>
                      <button
                        onClick={() => setActiveTab('inventory')}
                        className="mt-4 px-4 py-2 bg-btn-primary text-white rounded-lg hover:bg-btn-primary-hover transition-colors text-sm font-medium"
                      >
                        Browse Inventory
                      </button>
                    </div>
                  ) : (
                    <div className="space-y-3">
                      {orders.slice(0, 3).map((order) => {
                        const status = order.unit || 'pending'; // Status stored in unit field
                        const isReady = status === 'ready';
                        const isPickedUp = order.isPurchased || status === 'picked-up';
                        
                        return (
                          <div 
                            key={order.id} 
                            className={`flex items-center justify-between p-4 border rounded-lg hover:bg-card-hover transition-colors ${
                              isPickedUp ? 'bg-gray-50 border-light-gray' :
                              isReady ? 'bg-green-50 border-fresh' :
                              'bg-blue-50 border-stable'
                            }`}
                          >
                            <div className="flex items-center">
                              <div className={`w-12 h-12 rounded-lg flex items-center justify-center ${
                                isPickedUp ? 'bg-gray-200 text-secondary-text' :
                                isReady ? 'bg-light-green text-primary-green' :
                                'bg-stable/30 text-stable'
                              }`}>
                                <Package className="h-6 w-6" />
                              </div>
                              <div className="ml-4">
                                <p className="text-sm font-semibold text-primary-text">{order.name}</p>
                                <p className="text-xs text-secondary-text">
                                  {order.quantity} items • {formatDate(order.createdAt)}
                                </p>
                              </div>
                            </div>
                            <span className={`px-3 py-1 rounded-full text-xs font-semibold border ${
                              isPickedUp ? 'bg-gray-100 text-secondary-text border-light-gray' :
                              isReady ? 'bg-fresh/20 text-primary-green border-fresh' :
                              'bg-stable/20 text-blue-800 border-stable'
                            }`}>
                              {isPickedUp ? 'Picked Up' : isReady ? 'Ready' : 'Pending'}
                            </span>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </div>
              </div>

              {/* Quick Links */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <button 
                  onClick={() => setActiveTab('inventory')}
                  className="bg-white border-2 border-light-gray rounded-xl p-6 hover:border-primary-green hover:bg-card-hover hover:shadow-md transition-all text-left"
                >
                  <ShoppingCart className="h-8 w-8 text-primary-green mb-3" />
                  <h4 className="font-semibold text-deep-forest">Browse Available Items</h4>
                  <p className="text-sm text-secondary-text mt-1">See what's in stock and place an order</p>
                </button>

                <button 
                  onClick={() => setActiveTab('orders')}
                  className="bg-white border-2 border-light-gray rounded-xl p-6 hover:border-primary-green hover:bg-card-hover hover:shadow-md transition-all text-left"
                >
                  <PackageOpen className="h-8 w-8 text-primary-green mb-3" />
                  <h4 className="font-semibold text-deep-forest">View Order History</h4>
                  <p className="text-sm text-secondary-text mt-1">Track your past and current orders</p>
                </button>
              </div>
            </div>
          )}

          {/* INVENTORY TAB */}
          {activeTab === 'inventory' && (
            <div className="space-y-6">
              {/* Search and Filter Bar */}
              <div className="glass-card p-6">
                <div className="flex flex-col md:flex-row gap-4">
                  <div className="flex-1 relative">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-secondary-text" />
                    <input
                      type="text"
                      placeholder="Search available items..."
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      className="w-full pl-10 pr-4 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text"
                    />
                  </div>
                  <div className="flex items-center gap-2">
                    <Filter className="h-5 w-5 text-secondary-text" />
                    <select
                      value={selectedCategory}
                      onChange={(e) => setSelectedCategory(e.target.value)}
                      className="px-4 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text"
                    >
                      <option value="all">All Categories</option>
                      {categories.map((cat) => (
                        <option key={cat.id} value={cat.id}>{cat.name}</option>
                      ))}
                    </select>
                  </div>
                </div>
              </div>

              {/* Cart Summary */}
              {getCartTotal() > 0 && (
                <div className="bg-gradient-to-r from-soft-yellow to-btn-secondary-hover text-white rounded-2xl shadow-card p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-amber-100 text-sm font-medium">Items in Cart</p>
                      <p className="text-3xl font-bold mt-1">{getCartTotal()} items</p>
                    </div>
                    <button 
                      onClick={() => {
                        const cartItems = Object.entries(cart).map(([itemId, quantity]) => {
                          const item = inventoryItems.find(i => i.id === itemId);
                          return {
                            id: itemId,
                            name: item?.name || 'Unknown Item',
                            quantity,
                            unit: item?.unit,
                            imageUrl: item?.imageUrl,
                            categoryId: item?.categoryId
                          };
                        });
                            navigate('/checkout', { state: { cartItems } });
                      }}
                      className="bg-btn-primary text-white px-6 py-3 rounded-lg font-semibold hover:bg-btn-primary-hover active:bg-btn-primary-active transition-colors shadow-md flex items-center"
                    >
                      Proceed to Checkout
                    </button>
                  </div>
                </div>
              )}

              {/* Inventory Grid */}
              {inventoryLoading ? (
                <div className="text-center py-12">
                  <Loader2 className="h-12 w-12 animate-spin text-primary-green mx-auto" />
                </div>
              ) : filteredInventory.length === 0 ? (
                <div className="text-center py-12 bg-white rounded-xl border border-light-gray">
                  <Package className="h-12 w-12 text-secondary-text mx-auto mb-3 opacity-50" />
                  <p className="text-secondary-text">No items found</p>
                </div>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {filteredInventory.map((item) => {
                    const daysUntilExpiry = getDaysUntilExpiry(item.expiryDate);
                    const categoryName = categories.find(c => c.id === item.categoryId)?.name || 'Uncategorized';
                    
                    return (
                      <div key={item.id} className="glass-card overflow-hidden hover:shadow-card transition-all">
                        <div className="p-6">
                          <div className="flex items-start justify-between mb-4">
                            <div className="w-16 h-16 rounded-lg overflow-hidden bg-gray-100 flex items-center justify-center">
                              {item.imageUrl && !imageErrors.has(item.id) ? (
                                <img 
                                  src={item.imageUrl} 
                                  alt={item.name}
                                  className="w-full h-full object-cover"
                                  onError={() => setImageErrors(prev => new Set(prev).add(item.id))}
                                />
                              ) : (
                                <Package className="h-8 w-8 text-secondary-text" />
                              )}
                            </div>
                            <span className="px-2 py-1 bg-fresh/20 text-primary-green text-xs font-semibold rounded-full border border-fresh">
                              {item.quantity} {item.unit || 'units'}
                            </span>
                          </div>
                          <h4 className="font-semibold text-deep-forest mb-1">{item.name}</h4>
                          <p className="text-xs text-secondary-text mb-1">{categoryName}</p>
                          <p className="text-xs text-secondary-text mb-4">
                            {daysUntilExpiry !== null 
                              ? `Expires in ${daysUntilExpiry} day${daysUntilExpiry !== 1 ? 's' : ''}`
                              : 'No expiry date'
                            }
                          </p>
                          {item.description && (
                            <p className="text-xs text-secondary-text mb-4 line-clamp-2">
                              {item.description}
                            </p>
                          )}
                          
                          {cart[item.id] ? (
                            <div className="flex items-center justify-between bg-card-hover rounded-lg p-2 border border-light-gray">
                              <button
                                onClick={() => removeFromCart(item.id)}
                                className="w-8 h-8 flex items-center justify-center bg-white rounded-lg border border-light-gray hover:bg-warning/10 hover:border-warning transition-colors"
                              >
                                <Minus className="h-4 w-4 text-warning" />
                              </button>
                              <span className="font-semibold text-primary-text">{cart[item.id]}</span>
                              <button
                                onClick={() => addToCart(item.id)}
                                className="w-8 h-8 flex items-center justify-center bg-white rounded-lg border border-light-gray hover:bg-fresh/10 hover:border-fresh transition-colors"
                              >
                                <Plus className="h-4 w-4 text-primary-green" />
                              </button>
                            </div>
                          ) : (
                            <button
                              onClick={() => addToCart(item.id)}
                              className="w-full bg-btn-primary text-white py-2 rounded-lg hover:bg-btn-primary-hover active:bg-btn-primary-active transition-colors font-medium text-sm flex items-center justify-center shadow-sm"
                            >
                              <Plus className="h-4 w-4 mr-2" />
                              Add to Cart
                            </button>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          )}

          {/* MY ORDERS TAB */}
          {activeTab === 'orders' && (
            <div className="space-y-6">
              <div className="glass-card">
                <div className="px-6 py-5 border-b border-light-gray">
                  <h3 className="text-lg font-semibold text-deep-forest">Order History</h3>
                  <p className="text-sm text-secondary-text mt-1">Track your current and past orders</p>
                </div>
                <div className="p-6">
                  {ordersLoading ? (
                    <div className="text-center py-12">
                      <Loader2 className="h-12 w-12 animate-spin text-primary-green mx-auto" />
                    </div>
                  ) : orders.length === 0 ? (
                    <div className="text-center py-12">
                      <PackageOpen className="h-12 w-12 text-secondary-text mx-auto mb-3 opacity-50" />
                      <p className="text-secondary-text mb-4">No orders yet</p>
                      <button
                        onClick={() => setActiveTab('inventory')}
                        className="px-6 py-2 bg-btn-primary text-white rounded-lg hover:bg-btn-primary-hover transition-colors font-medium"
                      >
                        Browse Inventory
                      </button>
                    </div>
                  ) : (
                    <div className="space-y-4">
                      {orders.map((order) => {
                        const status = order.unit || 'pending';
                        const isReady = status === 'ready';
                        const isPickedUp = order.isPurchased || status === 'picked-up';
                        
                        return (
                          <div key={order.id} className="border border-light-gray rounded-xl p-5 hover:shadow-md hover:border-light-green transition-all">
                            <div className="flex items-center justify-between mb-4">
                              <div>
                                <p className="font-semibold text-deep-forest">{order.id.substring(0, 13)}</p>
                                <p className="text-sm text-secondary-text">Ordered on {formatDate(order.createdAt)}</p>
                              </div>
                              <span className={`px-3 py-1 rounded-full text-xs font-semibold border ${
                                isReady 
                                  ? 'bg-fresh/20 text-primary-green border-fresh'
                                  : isPickedUp
                                  ? 'bg-gray-100 text-secondary-text border-light-gray'
                                  : 'bg-soft-yellow/20 text-amber-800 border-soft-yellow'
                              }`}>
                                {isReady && '✓ Ready for Pickup'}
                                {isPickedUp && 'Picked Up'}
                                {!isReady && !isPickedUp && 'Processing'}
                              </span>
                            </div>
                            
                            <div className="grid grid-cols-2 gap-4 mb-4">
                              <div className="bg-card-hover rounded-lg p-3 border border-light-gray">
                                <p className="text-xs text-secondary-text mb-1">Total Items</p>
                                <p className="font-semibold text-primary-text">{order.quantity} items</p>
                              </div>
                              <div className="bg-card-hover rounded-lg p-3 border border-light-gray">
                                <p className="text-xs text-secondary-text mb-1">Pickup Time</p>
                                <p className="font-semibold text-primary-text">{order.priority || 'TBD'}</p>
                              </div>
                            </div>

                            {/* Order Details - Expandable */}
                            {order.notes && (
                              <>
                                <button 
                                  onClick={() => setExpandedOrderId(expandedOrderId === order.id ? null : order.id)}
                                  className="w-full border-2 border-light-gray text-primary-text py-2 rounded-lg hover:bg-card-hover hover:border-primary-green transition-colors font-medium text-sm flex items-center justify-center"
                                >
                                  <Package className="h-4 w-4 mr-2" />
                                  {expandedOrderId === order.id ? 'Hide Items' : 'View Items'}
                                </button>
                                
                                {expandedOrderId === order.id && (
                                  <div className="mt-4 p-4 bg-card-hover rounded-lg border border-light-gray">
                                    <h4 className="font-semibold text-deep-forest mb-2 text-sm">Order Details:</h4>
                                    <p className="text-sm text-primary-text whitespace-pre-wrap">{order.notes}</p>
                                  </div>
                                )}
                              </>
                            )}
                          </div>
                        );
                      })}
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}


          {/* RESOURCES TAB */}
          {activeTab === 'resources' && (
            <div className="space-y-6">
              {/* Pantry Information */}
              {pantrySettings && (
                <div className="glass-card overflow-hidden">
                  <div className="bg-gradient-to-r from-primary-green to-deep-forest px-6 py-5">
                    <h3 className="text-xl font-semibold text-white">{pantrySettings.pantryName}</h3>
                    <p className="text-light-green text-sm mt-1">Your local food pantry information</p>
                  </div>
                  <div className="p-6">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      {/* Contact Information */}
                      <div className="space-y-4">
                        <h4 className="font-semibold text-deep-forest text-lg mb-3 flex items-center">
                          <Phone className="h-5 w-5 mr-2 text-primary-green" />
                          Contact Us
                        </h4>
                        {pantrySettings.contactPhone && (
                          <a 
                            href={`tel:${pantrySettings.contactPhone}`}
                            className="flex items-start p-4 bg-card-hover rounded-lg hover:bg-card-active transition-all border border-light-gray hover:border-primary-green"
                          >
                            <Phone className="h-5 w-5 text-primary-green mr-3 mt-0.5 flex-shrink-0" />
                            <div>
                              <p className="font-medium text-deep-forest">Phone</p>
                              <p className="text-primary-text text-sm mt-0.5">{pantrySettings.contactPhone}</p>
                            </div>
                          </a>
                        )}
                        {pantrySettings.address && (
                          <div className="flex items-start p-4 bg-card-hover rounded-lg border border-light-gray">
                            <MapPin className="h-5 w-5 text-primary-green mr-3 mt-0.5 flex-shrink-0" />
                            <div>
                              <p className="font-medium text-deep-forest">Location</p>
                              <p className="text-primary-text text-sm mt-0.5 whitespace-pre-wrap">{pantrySettings.address}</p>
                            </div>
                          </div>
                        )}
                      </div>

                      {/* Operating Hours & Info */}
                      <div className="space-y-4">
                        <h4 className="font-semibold text-deep-forest text-lg mb-3 flex items-center">
                          <Clock className="h-5 w-5 mr-2 text-primary-green" />
                          Hours & Information
                        </h4>
                        <div className="p-4 bg-card-hover rounded-lg border border-light-gray">
                          <p className="font-medium text-deep-forest mb-2">Operating Hours</p>
                          <p className="text-primary-text text-sm">
                            Monday - Friday: 10:00 AM - 2:00 PM
                          </p>
                          <p className="text-primary-text text-sm mt-1">
                            Saturday: 9:00 AM - 12:00 PM
                          </p>
                          <p className="text-primary-text text-sm mt-1">
                            Sunday: Closed
                          </p>
                        </div>
                        <div className="p-4 bg-card-hover rounded-lg border border-light-gray">
                          <p className="font-medium text-deep-forest mb-2">What to Bring</p>
                          <ul className="text-primary-text text-sm space-y-1">
                            <li>• Valid ID or proof of address</li>
                            <li>• Reusable bags (if available)</li>
                            <li>• Your order confirmation</li>
                          </ul>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {/* Food Safety Tips */}
              <div className="glass-card overflow-hidden">
                <div className="bg-gradient-to-r from-primary-green to-deep-forest px-6 py-5">
                  <h3 className="text-xl font-semibold text-white">Food Safety & Storage Tips</h3>
                  <p className="text-light-green text-sm mt-1">Keep your food fresh and safe</p>
                </div>
                <div className="p-6">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="bg-stable/10 border-2 border-stable rounded-lg p-5">
                      <h4 className="font-semibold text-deep-forest mb-3">Storage Guidelines</h4>
                      <ul className="space-y-2 text-sm text-primary-text">
                        <li>• Refrigerate perishables within 2 hours</li>
                        <li>• Keep refrigerator at 40°F or below</li>
                        <li>• Store raw meat on bottom shelf</li>
                        <li>• Use airtight containers for leftovers</li>
                      </ul>
                    </div>
                    <div className="bg-fresh/10 border-2 border-fresh rounded-lg p-5">
                      <h4 className="font-semibold text-deep-forest mb-3">Reduce Food Waste</h4>
                      <ul className="space-y-2 text-sm text-primary-text">
                        <li>• Freeze bread before it expires</li>
                        <li>• Use wilting vegetables in soups</li>
                        <li>• Label and date all stored items</li>
                        <li>• Plan meals around expiring items</li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>

              {/* Community Resources */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="glass-card p-6 hover:shadow-card transition-shadow">
                  <div className="flex items-center mb-4">
                    <Heart className="h-6 w-6 text-primary-green mr-3" />
                    <h4 className="text-lg font-semibold text-deep-forest">Additional Food Assistance</h4>
                  </div>
                  <div className="space-y-3">
                    <div>
                      <p className="font-medium text-primary-text">Local SNAP Office</p>
                      <a href="tel:5551234567" className="text-primary-green hover:text-deep-forest flex items-center text-sm mt-1 font-medium">
                        <Phone className="h-4 w-4 mr-1" />
                        (555) 123-4567
                      </a>
                    </div>
                    <div>
                      <p className="font-medium text-primary-text">WIC Program</p>
                      <a href="tel:5559876543" className="text-primary-green hover:text-deep-forest flex items-center text-sm mt-1 font-medium">
                        <Phone className="h-4 w-4 mr-1" />
                        (555) 987-6543
                      </a>
                    </div>
                    <div>
                      <p className="font-medium text-primary-text">Meals on Wheels</p>
                      <a href="tel:5554567890" className="text-primary-green hover:text-deep-forest flex items-center text-sm mt-1 font-medium">
                        <Phone className="h-4 w-4 mr-1" />
                        (555) 456-7890
                      </a>
                    </div>
                  </div>
                </div>

                <div className="glass-card p-6 hover:shadow-card transition-shadow">
                  <div className="flex items-center mb-4">
                    <Users className="h-6 w-6 text-stable mr-3" />
                    <h4 className="text-lg font-semibold text-deep-forest">Support Services</h4>
                  </div>
                  <div className="space-y-3">
                    <div>
                      <p className="font-medium text-primary-text">Housing Assistance</p>
                      <a href="tel:5552345678" className="text-primary-green hover:text-deep-forest flex items-center text-sm mt-1 font-medium">
                        <Phone className="h-4 w-4 mr-1" />
                        (555) 234-5678
                      </a>
                    </div>
                    <div>
                      <p className="font-medium text-primary-text">Utility Bill Help</p>
                      <a href="tel:5553456789" className="text-primary-green hover:text-deep-forest flex items-center text-sm mt-1 font-medium">
                        <Phone className="h-4 w-4 mr-1" />
                        (555) 345-6789
                      </a>
                    </div>
                    <div>
                      <p className="font-medium text-primary-text">Job Training</p>
                      <a href="tel:5554567890" className="text-primary-green hover:text-deep-forest flex items-center text-sm mt-1 font-medium">
                        <Phone className="h-4 w-4 mr-1" />
                        (555) 456-7890
                      </a>
                    </div>
                  </div>
                </div>
              </div>
              {/* Emergency Assistance */}
              <div className="bg-gradient-to-r from-warning/10 to-expiring/10 border-2 border-warning rounded-2xl p-6 shadow-soft">
                <div className="flex items-start">
                  <AlertTriangle className="h-6 w-6 text-warning mr-3 flex-shrink-0 mt-1" />
                  <div>
                    <h4 className="text-lg font-semibold text-deep-forest mb-2">Emergency Assistance</h4>
                    <p className="text-primary-text mb-3">
                      If you need immediate help, call <strong>211</strong> for 24/7 assistance connecting you to local resources.
                    </p>
                    <a 
                      href="tel:211" 
                      className="inline-flex items-center px-5 py-2 bg-warning text-white rounded-lg hover:bg-[#D32F2F] active:bg-[#C62828] transition-colors font-semibold shadow-sm"
                    >
                      <Phone className="h-4 w-4 mr-2" />
                      Call 211 Now
                    </a>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </main>

      {/* Account Settings Modal */}
      {showAccountSettings && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <div className="sticky top-0 bg-white border-b border-light-gray px-6 py-4 flex justify-between items-center">
              <h3 className="text-lg font-semibold text-deep-forest">Account Settings</h3>
              <button 
                onClick={() => setShowAccountSettings(false)} 
                className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <X className="h-5 w-5 text-secondary-text" />
              </button>
            </div>

            <div className="p-6 space-y-6">
              {/* Profile Information */}
              <div className="border border-light-gray rounded-lg p-5">
                <h4 className="font-semibold text-deep-forest mb-4 flex items-center">
                  <User className="h-5 w-5 mr-2 text-primary-green" />
                  Profile Information
                </h4>
                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-primary-text mb-2">
                      Full Name
                    </label>
                    <input
                      type="text"
                      value={user?.fullName || ''}
                      className="w-full px-3 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text bg-gray-50"
                      disabled
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-primary-text mb-2 flex items-center">
                      <Mail className="h-4 w-4 mr-1 text-secondary-text" />
                      Email Address
                    </label>
                    {editingEmail ? (
                      <div className="space-y-2">
                        <input
                          type="email"
                          value={newEmail}
                          onChange={(e) => setNewEmail(e.target.value)}
                          className="w-full px-3 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text"
                          placeholder="Enter new email"
                        />
                        <div className="flex gap-2">
                          <button
                            onClick={handleUpdateEmail}
                            disabled={accountLoading}
                            className="px-4 py-2 bg-btn-primary text-white rounded-lg hover:bg-btn-primary-hover transition-colors font-medium text-sm shadow-sm disabled:opacity-50 flex items-center"
                          >
                            {accountLoading ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : null}
                            Save
                          </button>
                          <button
                            onClick={() => {
                              setEditingEmail(false);
                              setNewEmail('');
                              setAccountError('');
                            }}
                            className="px-4 py-2 border border-light-gray text-primary-text rounded-lg hover:bg-card-hover transition-colors font-medium text-sm"
                          >
                            Cancel
                          </button>
                        </div>
                      </div>
                    ) : (
                      <div className="flex items-center gap-3">
                        <input
                          type="email"
                          value={user?.email || ''}
                          className="flex-1 px-3 py-2 border border-light-gray rounded-lg text-primary-text bg-gray-50"
                          disabled
                        />
                        <button
                          onClick={() => {
                            setEditingEmail(true);
                            setNewEmail(user?.email || '');
                          }}
                          className="px-4 py-2 bg-btn-primary text-white rounded-lg hover:bg-btn-primary-hover transition-colors font-medium text-sm shadow-sm"
                        >
                          Change
                        </button>
                      </div>
                    )}
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-primary-text mb-2">
                      Role
                    </label>
                    <div className="px-3 py-2 border border-light-gray rounded-lg bg-gray-50">
                      <span className="px-3 py-1 bg-fresh/20 text-fresh rounded-full text-xs font-semibold border border-fresh">
                        User
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              {/* Security */}
              <div className="border border-light-gray rounded-lg p-5">
                <h4 className="font-semibold text-deep-forest mb-4 flex items-center">
                  <Key className="h-5 w-5 mr-2 text-primary-green" />
                  Security
                </h4>
                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-primary-text mb-2">
                      Password
                    </label>
                    {editingPassword ? (
                      <div className="space-y-3">
                        <div>
                          <label className="block text-xs font-medium text-secondary-text mb-1">Current Password *</label>
                          <input
                            type="password"
                            value={oldPassword}
                            onChange={(e) => setOldPassword(e.target.value)}
                            className="w-full px-3 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text"
                            placeholder="Enter your current password"
                          />
                        </div>
                        <div>
                          <label className="block text-xs font-medium text-secondary-text mb-1">New Password *</label>
                          <input
                            type="password"
                            value={newPassword}
                            onChange={(e) => setNewPassword(e.target.value)}
                            className="w-full px-3 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text"
                            placeholder="New password (min. 6 characters)"
                          />
                        </div>
                        <div>
                          <label className="block text-xs font-medium text-secondary-text mb-1">Confirm New Password *</label>
                          <input
                            type="password"
                            value={confirmPassword}
                            onChange={(e) => setConfirmPassword(e.target.value)}
                            className="w-full px-3 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text"
                            placeholder="Confirm new password"
                          />
                        </div>
                        <div className="flex gap-2 pt-2">
                          <button
                            onClick={handleUpdatePassword}
                            disabled={accountLoading}
                            className="px-4 py-2 bg-btn-primary text-white rounded-lg hover:bg-btn-primary-hover transition-colors font-medium text-sm shadow-sm disabled:opacity-50 flex items-center"
                          >
                            {accountLoading ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : null}
                            Update Password
                          </button>
                          <button
                            onClick={() => {
                              setEditingPassword(false);
                              setOldPassword('');
                              setNewPassword('');
                              setConfirmPassword('');
                              setAccountError('');
                            }}
                            className="px-4 py-2 border border-light-gray text-primary-text rounded-lg hover:bg-card-hover transition-colors font-medium text-sm"
                          >
                            Cancel
                          </button>
                        </div>
                      </div>
                    ) : (
                      <div className="flex items-center gap-3">
                        <input
                          type="password"
                          value="••••••••"
                          className="flex-1 px-3 py-2 border border-light-gray rounded-lg bg-gray-50"
                          disabled
                        />
                        <button
                          onClick={() => setEditingPassword(true)}
                          className="px-4 py-2 bg-btn-primary text-white rounded-lg hover:bg-btn-primary-hover transition-colors font-medium text-sm shadow-sm"
                        >
                          Change
                        </button>
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {/* Error Message */}
              {accountError && (
                <div className="bg-warning/10 border border-warning text-warning px-4 py-3 rounded-lg text-sm">
                  {accountError}
                </div>
              )}

              {/* Action Buttons */}
              <div className="flex gap-3 pt-4">
                <button
                  onClick={() => {
                    setShowAccountSettings(false);
                    setEditingEmail(false);
                    setEditingPassword(false);
                    setNewEmail('');
                    setOldPassword('');
                    setNewPassword('');
                    setConfirmPassword('');
                    setAccountError('');
                  }}
                  className="flex-1 px-4 py-2 bg-btn-primary text-white rounded-lg hover:bg-btn-primary-hover transition-colors font-medium shadow-sm"
                >
                  Close
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default UserDashboard;
