import React, { useState, useEffect, useRef } from 'react';
import { useAuth } from '../contexts/AuthContext';
import { useInventory } from '../hooks/useInventory';
import { useStats } from '../hooks/useStats';
import { useActivity } from '../hooks/useActivity';
import { useAlerts } from '../hooks/useAlerts';
import { useAnalytics } from '../hooks/useAnalytics';
import { usePickups } from '../hooks/usePickups';
import { inventoryAPI, pickupAPI } from '../utils/api';
import { supabase } from '../config/supabase';
import AddItemModal from '../components/modals/AddItemModal';
import EditItemModal from '../components/modals/EditItemModal';
import ConfirmDeleteModal from '../components/modals/ConfirmDeleteModal';
import Logo from '../components/Logo';
import { 
  LogOut, 
  BarChart3, 
  Package, 
  TrendingUp, 
  AlertTriangle,
  Home,
  ChevronDown,
  Plus,
  Download,
  Bell,
  Search,
  Filter,
  Edit,
  Trash2,
  CheckCircle,
  PieChart,
  Upload,
  Loader2,
  User,
  Mail,
  Key,
  X,
  Calendar
} from 'lucide-react';

const TeamDashboard: React.FC = () => {
  const { user, signOut } = useAuth();
  const { items: inventoryItems, categories, loading: inventoryLoading, refetch: refetchInventory } = useInventory();
  const { stats, loading: statsLoading, refetch: refetchStats } = useStats();
  const { activities, loading: activityLoading, refetch: refetchActivity } = useActivity();
  const { alerts: alertsList, loading: alertsLoading, refetch: refetchAlerts } = useAlerts();
  const { analytics, loading: analyticsLoading, refetch: refetchAnalytics } = useAnalytics();
  const { pickups, loading: pickupsLoading, refetch: refetchPickups } = usePickups();
  
  // Track resolved alerts locally
  const [resolvedAlerts, setResolvedAlerts] = useState<Set<string>>(new Set());
  
  const [activeTab, setActiveTab] = useState('overview');
  const [showProfileMenu, setShowProfileMenu] = useState(false);
  
  // Inventory filters
  const [inventorySearchQuery, setInventorySearchQuery] = useState('');
  const [inventoryCategoryFilter, setInventoryCategoryFilter] = useState('all');
  const [inventoryStatusFilter, setInventoryStatusFilter] = useState<'all' | 'good' | 'fresh' | 'expiring' | 'low' | 'expired'>('all');
  const [showInventoryFilterMenu, setShowInventoryFilterMenu] = useState(false);
  
  // Modal states
  const [showAddItemModal, setShowAddItemModal] = useState(false);
  const [showEditItemModal, setShowEditItemModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showAccountSettings, setShowAccountSettings] = useState(false);
  const [selectedItem, setSelectedItem] = useState<any>(null);
  const [deleteLoading, setDeleteLoading] = useState(false);
  
  // Account settings states
  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);
  const inventoryFilterMenuRef = useRef<HTMLDivElement>(null);

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

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

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

  // Refresh all data across tabs
  const refreshAllData = async () => {
    await Promise.all([
      refetchInventory(),
      refetchStats(),
      refetchActivity(),
      refetchAlerts(),
      refetchAnalytics(),
      refetchPickups()
    ]);
  };

  const tabs = [
    { id: 'overview', name: 'Overview', icon: Home },
    { id: 'analytics', name: 'Analytics', icon: BarChart3 },
    { id: 'inventory', name: 'Inventory', icon: Package },
    { id: 'pickups', name: 'Pickups', icon: Calendar },
    { id: 'alerts', name: 'Alerts', icon: AlertTriangle },
  ];

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

  const getTimeAgo = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / (1000 * 60));
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
    
    if (diffMins < 1) return 'Just now';
    if (diffMins < 60) return `${diffMins} min ago`;
    if (diffHours < 24) return `${diffHours} hour${diffHours !== 1 ? 's' : ''} ago`;
    if (diffDays < 7) return `${diffDays} day${diffDays !== 1 ? 's' : ''} ago`;
    return formatDate(dateString);
  };

  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 getItemStatus = (item: any) => {
    const days = getDaysUntilExpiry(item.expiryDate);
    // Check expiry status first (higher priority than low stock)
    if (days !== null && days <= 0) return 'expired';
    if (days !== null && days <= 2) return 'expiring';
    if (days !== null && days <= 7) return 'fresh';
    // Then check low stock
    if (item.isLowStock) return 'low';
    return 'good';
  };

  // Handler functions for modals
  const handleEditItem = (item: any) => {
    setSelectedItem(item);
    setShowEditItemModal(true);
  };

  const handleDeleteItem = (item: any) => {
    setSelectedItem(item);
    setShowDeleteModal(true);
  };

  const confirmDeleteItem = async () => {
    if (!selectedItem) return;
    
    try {
      setDeleteLoading(true);
      await inventoryAPI.delete(selectedItem.id);
      await refreshAllData();
      setShowDeleteModal(false);
      setSelectedItem(null);
    } catch (err: any) {
      alert('Failed to delete item: ' + err.message);
    } finally {
      setDeleteLoading(false);
    }
  };

  const handleResolveAlert = (alertId: string) => {
    // Add alert to resolved set to hide it
    setResolvedAlerts(prev => new Set(prev).add(alertId));
    // Also refetch alerts to get updated list
    refetchAlerts();
  };

  const handleUpdatePickupStatus = async (pickupId: string, newStatus: 'pending' | 'ready' | 'picked-up') => {
    try {
      await pickupAPI.updateStatus(pickupId, newStatus);
      await refetchPickups();
    } catch (err: any) {
      alert('Failed to update pickup status: ' + err.message);
    }
  };

  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 handleExportReport = () => {
    // Create CSV content
    const headers = ['Name', 'Category', 'Quantity', 'Unit', 'Expiry Date', 'Status'];
    const rows = inventoryItems.map(item => {
      const categoryName = categories.find(c => c.id === item.categoryId)?.name || 'Uncategorized';
      const status = getItemStatus(item);
      return [
        item.name,
        categoryName,
        item.quantity,
        item.unit || '',
        item.expiryDate ? new Date(item.expiryDate).toLocaleDateString() : 'N/A',
        status
      ];
    });

    const csvContent = [
      headers.join(','),
      ...rows.map(row => row.map(cell => `"${cell}"`).join(','))
    ].join('\n');

    // Create download link
    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `inventory-report-${new Date().toISOString().split('T')[0]}.csv`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  };

  const handleImportCSV = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.csv';
    input.onchange = async (e: any) => {
      const file = e.target.files?.[0];
      if (!file) return;

      const reader = new FileReader();
      reader.onload = async (event) => {
        try {
          const text = event.target?.result as string;
          const lines = text.split('\n');
          
          // Skip header row
          for (let i = 1; i < lines.length; i++) {
            if (!lines[i].trim()) continue;
            
            const values = lines[i].split(',').map(v => v.replace(/"/g, '').trim());
            const itemData = {
              name: values[0],
              quantity: parseInt(values[2]) || 0,
              unit: values[3],
              expiryDate: values[4] !== 'N/A' ? values[4] : undefined,
            };

            await inventoryAPI.create(itemData);
          }
          
          alert('CSV imported successfully!');
          await refreshAllData();
        } catch (err: any) {
          alert('Failed to import CSV: ' + err.message);
        }
      };
      reader.readAsText(file);
    };
    input.click();
  };

  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">Team Dashboard</h1>
                <p className="text-sm text-secondary-text">Welcome back, {user?.fullName || user?.email?.split('@')[0]}</p>
              </div>
            </div>
            
            {/* Profile Dropdown */}
            <div className="relative" ref={profileMenuRef}>
              <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 || 'Team Member'}</p>
                    <p className="text-xs text-secondary-text truncate">{user?.email}</p>
                    <span className="inline-block mt-1 px-2 py-0.5 bg-stable/20 text-stable text-xs font-semibold rounded-full border border-stable">
                      Team
                    </span>
                  </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"
                  >
                    <User 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;
               const alertCount = tab.id === 'alerts' ? alertsList.filter(alert => !resolvedAlerts.has(alert.id)).length : 0;
              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}
                  {alertCount > 0 && (
                    <span className="ml-2 bg-warning text-white text-xs rounded-full px-2 py-0.5 font-semibold">
                      {alertCount}
                    </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">
          {activeTab === 'overview' && (
            <div className="space-y-6">
              {/* KPI Cards */}
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 max-w-4xl mx-auto">
                <button 
                  onClick={() => setActiveTab('inventory')}
                  className="bg-gradient-to-br from-primary-green to-deep-forest text-white rounded-xl shadow-lg p-6 text-left transition-all duration-300 hover:shadow-2xl hover:scale-105 cursor-pointer"
                >
                  <Package className="h-8 w-8 mb-3 opacity-80" />
                  <p className="text-green-100 text-sm font-medium">Total Items</p>
                  <p className="text-3xl font-bold mt-1">{statsLoading ? '...' : stats.totalItems || 0}</p>
                  <p className="text-xs text-green-100 mt-2">Across {categories.length} categories</p>
                </button>

                <button 
                  onClick={() => setActiveTab('alerts')}
                  className="bg-gradient-to-br from-expiring to-[#FF9800] text-white rounded-xl shadow-lg p-6 text-left transition-all duration-300 hover:shadow-2xl hover:scale-105 cursor-pointer"
                >
                  <AlertTriangle className="h-8 w-8 mb-3 opacity-80" />
                  <p className="text-orange-100 text-sm font-medium">Expiring Soon</p>
                  <p className="text-3xl font-bold mt-1">{statsLoading ? '...' : stats.expiringItems || 0}</p>
                  <p className="text-xs text-orange-100 mt-2">Within 7 days</p>
                </button>

                <button 
                  onClick={() => setActiveTab('alerts')}
                  className="bg-gradient-to-br from-warning to-[#D32F2F] text-white rounded-xl shadow-lg p-6 text-left transition-all duration-300 hover:shadow-2xl hover:scale-105 cursor-pointer"
                >
                  <TrendingUp className="h-8 w-8 mb-3 opacity-80" />
                  <p className="text-red-100 text-sm font-medium">Low Stock</p>
                  <p className="text-3xl font-bold mt-1">{statsLoading ? '...' : stats.lowStockItems || 0}</p>
                  <p className="text-xs text-red-100 mt-2">Need restocking</p>
                </button>
              </div>

              {/* Quick Actions */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <button 
                  onClick={() => setShowAddItemModal(true)}
                  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"
                >
                  <Plus className="h-8 w-8 text-primary-green mb-3" />
                  <h4 className="font-semibold text-deep-forest">Add Item</h4>
                  <p className="text-sm text-secondary-text mt-1">Add new inventory item</p>
                </button>

                <button 
                  onClick={handleExportReport}
                  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"
                >
                  <Download className="h-8 w-8 text-stable mb-3" />
                  <h4 className="font-semibold text-deep-forest">Export Report</h4>
                  <p className="text-sm text-secondary-text mt-1">Download system reports</p>
                </button>

                <button 
                  onClick={() => setActiveTab('alerts')}
                  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"
                >
                  <Bell className="h-8 w-8 text-soft-yellow mb-3" />
                  <h4 className="font-semibold text-deep-forest">View Alerts</h4>
                  <p className="text-sm text-secondary-text mt-1">{alertsList.length} active alerts</p>
                </button>
                  </div>

              {/* Recent Activity */}
              <div className="glass-card">
                <div className="px-6 py-5 border-b border-light-gray">
                  <h3 className="text-lg font-semibold text-deep-forest">Recent Activity</h3>
                  <p className="text-sm text-secondary-text mt-1">Latest system events and user actions</p>
                </div>
                <div className="p-6">
                  {activityLoading ? (
                    <div className="text-center py-12">
                      <Loader2 className="h-12 w-12 animate-spin text-primary-green mx-auto" />
                      </div>
                  ) : activities.length === 0 ? (
                    <div className="text-center py-12">
                      <BarChart3 className="h-12 w-12 text-secondary-text mx-auto mb-3 opacity-50" />
                      <p className="text-secondary-text">No recent activity</p>
                    </div>
                  ) : (
                    <div className="space-y-4">
                      {activities.map((activity) => (
                        <div key={activity.id} className="flex items-center justify-between p-4 bg-card-hover rounded-lg border border-light-gray hover:border-light-green transition-colors">
                          <div className="flex items-center space-x-4">
                            <div className={`w-10 h-10 rounded-full flex items-center justify-center ${
                              activity.type === 'pickup' ? 'bg-fresh/20 text-primary-green' :
                              activity.type === 'order' ? 'bg-stable/20 text-stable' :
                              activity.type === 'restock' ? 'bg-soft-yellow/20 text-amber-700' :
                              'bg-gray-100 text-secondary-text'
                            }`}>
                              {activity.type === 'pickup' && <CheckCircle className="h-5 w-5" />}
                              {activity.type === 'order' && <Package className="h-5 w-5" />}
                              {activity.type === 'restock' && <TrendingUp className="h-5 w-5" />}
                            </div>
                            <div>
                              <p className="text-sm font-medium text-primary-text">
                                <span className="font-semibold">{activity.user?.fullName || 'System'}</span> {
                                  activity.type === 'pickup' ? 'picked up order' :
                                  activity.type === 'order' ? 'placed order' :
                                  activity.type === 'restock' ? activity.description :
                                  activity.description
                                }
                              </p>
                              {activity.metadata?.quantity && (
                                <p className="text-xs text-secondary-text">
                                  {activity.metadata.quantity} {activity.type === 'restock' ? 'units' : 'items'}
                                  {activity.metadata.status && ` • ${activity.metadata.status}`}
                                </p>
                              )}
                  </div>
                </div>
                          <span className="text-xs text-secondary-text">{getTimeAgo(activity.createdAt)}</span>
              </div>
                      ))}
                  </div>
                  )}
                </div>
              </div>
            </div>
          )}

          {activeTab === 'analytics' && (
            <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">Analytics Dashboard</h3>
                  <p className="text-sm text-secondary-text mt-1">Visual insights into pantry operations and impact</p>
                </div>
                <div className="p-6">
                  {analyticsLoading ? (
                    <div className="text-center py-12">
                      <Loader2 className="h-12 w-12 animate-spin text-primary-green mx-auto" />
                      <p className="text-secondary-text mt-4">Loading analytics...</p>
                    </div>
                  ) : (
                    <>
                      {/* Key Metrics */}
                      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                        <div className="bg-card-hover border border-light-gray rounded-lg p-4">
                          <p className="text-sm text-secondary-text">Total Visits</p>
                          <p className="text-2xl font-bold text-primary-green mt-1">{analytics.totalVisits.toLocaleString()}</p>
                          {analytics.trends.visitsChange !== 0 && (
                            <p className={`text-xs mt-1 ${analytics.trends.visitsChange > 0 ? 'text-fresh' : 'text-warning'}`}>
                              {analytics.trends.visitsChange > 0 ? '↑' : '↓'} {Math.abs(analytics.trends.visitsChange)}% from last month
                            </p>
                          )}
                        </div>
                        <div className="bg-card-hover border border-light-gray rounded-lg p-4">
                          <p className="text-sm text-secondary-text">Items Distributed</p>
                          <p className="text-2xl font-bold text-stable mt-1">{analytics.itemsDistributed.toLocaleString()}</p>
                          {analytics.trends.itemsChange !== 0 && (
                            <p className={`text-xs mt-1 ${analytics.trends.itemsChange > 0 ? 'text-stable' : 'text-warning'}`}>
                              {analytics.trends.itemsChange > 0 ? '↑' : '↓'} {Math.abs(analytics.trends.itemsChange)}% from last month
                            </p>
                          )}
                        </div>
                        <div className="bg-card-hover border border-light-gray rounded-lg p-4">
                          <p className="text-sm text-secondary-text">Waste Reduction</p>
                          <p className="text-2xl font-bold text-expiring mt-1">{analytics.wasteReduction}%</p>
                          {analytics.trends.wasteChange !== 0 && (
                            <p className={`text-xs mt-1 ${analytics.trends.wasteChange > 0 ? 'text-fresh' : 'text-warning'}`}>
                              {analytics.trends.wasteChange > 0 ? '↑' : '↓'} {Math.abs(analytics.trends.wasteChange)}% improvement
                            </p>
                          )}
                        </div>
                      </div>

                      {/* Charts */}
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        {/* Category Distribution Chart */}
                        <div className="bg-stable/10 border-2 border-stable rounded-xl p-6">
                          <div className="flex items-center justify-between mb-4">
                            <h4 className="font-semibold text-deep-forest">Distribution by Category</h4>
                            <PieChart className="h-5 w-5 text-stable" />
                          </div>
                          <div className="space-y-3">
                            {analytics.categoryDistribution.length === 0 ? (
                              <p className="text-center text-secondary-text py-8">No data available</p>
                            ) : (
                              analytics.categoryDistribution.slice(0, 5).map((cat, idx) => {
                                const total = analytics.categoryDistribution.reduce((sum, c) => sum + c.quantity, 0);
                                const percentage = total > 0 ? Math.round((cat.quantity / total) * 100) : 0;
                                const colors = ['bg-primary-green', 'bg-stable', 'bg-expiring', 'bg-soft-yellow', 'bg-gray-400'];
                                return (
                                  <div key={cat.name} className="space-y-1">
                                    <div className="flex justify-between text-sm">
                                      <span className="text-primary-text font-medium">{cat.name}</span>
                                      <span className="text-secondary-text">{cat.quantity} items ({percentage}%)</span>
                                    </div>
                                    <div className="w-full bg-gray-200 rounded-full h-2">
                                      <div 
                                        className={`${colors[idx % colors.length]} h-2 rounded-full transition-all`}
                                        style={{ width: `${percentage}%` }}
                                      ></div>
                                    </div>
                                  </div>
                                );
                              })
                            )}
                          </div>
                        </div>

                        {/* Monthly Trends Chart */}
                        <div className="bg-fresh/10 border-2 border-fresh rounded-xl p-6">
                          <div className="flex items-center justify-between mb-4">
                            <h4 className="font-semibold text-deep-forest">Monthly Visit Trends</h4>
                            <TrendingUp className="h-5 w-5 text-primary-green" />
                          </div>
                          <div className="h-48">
                            {analytics.monthlyTrends.length === 0 ? (
                              <p className="text-center text-secondary-text py-16">No data available</p>
                            ) : (
                              <div className="flex items-end justify-around h-full space-x-2">
                                {analytics.monthlyTrends.map((trend, idx) => {
                                  const maxCount = Math.max(...analytics.monthlyTrends.map(t => t.count), 1);
                                  const heightPercent = (trend.count / maxCount) * 100;
                                  return (
                                    <div key={idx} className="flex flex-col items-center flex-1">
                                      <div className="w-full flex flex-col justify-end h-40">
                                        <div 
                                          className="bg-primary-green rounded-t-lg w-full hover:bg-primary-green/80 transition-all cursor-pointer relative group"
                                          style={{ height: `${heightPercent}%`, minHeight: trend.count > 0 ? '8px' : '0' }}
                                          title={`${trend.month}: ${trend.count} visits`}
                                        >
                                          <span className="absolute -top-6 left-1/2 transform -translate-x-1/2 text-xs font-semibold text-primary-green opacity-0 group-hover:opacity-100 transition-opacity">
                                            {trend.count}
                                          </span>
                                        </div>
                                      </div>
                                      <p className="text-xs text-secondary-text mt-2">{trend.month}</p>
                                    </div>
                                  );
                                })}
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    </>
                  )}
                </div>
              </div>
            </div>
          )}

          {activeTab === 'inventory' && (
            <div className="space-y-6">
              <div className="glass-card">
                <div className="px-6 py-5 border-b border-light-gray flex justify-between items-center">
                  <div>
                    <h3 className="text-lg font-semibold text-deep-forest">Inventory Management</h3>
                    <p className="text-sm text-secondary-text mt-1">Core management of all pantry stock</p>
                  </div>
                  <div className="flex gap-2">
                    <button 
                      onClick={handleImportCSV}
                      className="inline-flex items-center px-4 py-2 border-2 border-light-gray text-primary-text rounded-lg hover:bg-card-hover hover:border-primary-green transition-colors font-medium text-sm"
                    >
                      <Upload className="h-4 w-4 mr-2" />
                      Import CSV
                    </button>
                    <button 
                      onClick={() => setShowAddItemModal(true)}
                      className="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 font-medium text-sm shadow-sm"
                    >
                      <Plus className="h-4 w-4 mr-2" />
                      Add Item
                    </button>
                  </div>
                </div>
                <div className="p-6">
                  {/* Search and Filter Bar */}
                  <div className="mb-6 flex flex-col md:flex-row gap-3">
                    <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 items by name, ID, or description..."
                        value={inventorySearchQuery}
                        onChange={(e) => setInventorySearchQuery(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>
                    <select
                      value={inventoryCategoryFilter}
                      onChange={(e) => setInventoryCategoryFilter(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 className="relative" ref={inventoryFilterMenuRef}>
                      <button 
                        onClick={() => setShowInventoryFilterMenu(!showInventoryFilterMenu)}
                        className="px-4 py-2 border-2 border-light-gray rounded-lg hover:border-primary-green hover:bg-card-hover transition-colors flex items-center gap-2"
                      >
                        <Filter className="h-5 w-5 text-secondary-text" />
                        <span className="text-sm text-primary-text">
                          {inventoryStatusFilter === 'all' ? 'All Status' : 
                           inventoryStatusFilter === 'good' ? 'Good' :
                           inventoryStatusFilter === 'fresh' ? 'Fresh' :
                           inventoryStatusFilter === 'expiring' ? 'Expiring' :
                           inventoryStatusFilter === 'low' ? 'Low Stock' : 'Expired'}
                        </span>
                      </button>
                      {showInventoryFilterMenu && (
                        <div className="absolute right-0 mt-2 w-40 bg-white rounded-lg shadow-lg py-1 z-50 border border-light-gray">
                          {['all', 'good', 'fresh', 'expiring', 'low', 'expired'].map((status) => (
                            <button
                              key={status}
                              onClick={() => { 
                                setInventoryStatusFilter(status as any); 
                                setShowInventoryFilterMenu(false); 
                              }}
                              className={`w-full text-left px-4 py-2 text-sm hover:bg-card-hover ${
                                inventoryStatusFilter === status ? 'bg-card-hover text-primary-green font-medium' : 'text-primary-text'
                              }`}
                            >
                              {status === 'all' ? 'All Status' : status.charAt(0).toUpperCase() + status.slice(1)}
                            </button>
                          ))}
                        </div>
                      )}
                    </div>
                  </div>
                  {inventoryLoading ? (
                    <div className="text-center py-12">
                      <Loader2 className="h-12 w-12 animate-spin text-primary-green mx-auto" />
                    </div>
                  ) : inventoryItems.length === 0 ? (
                    <div className="text-center py-12">
                      <Package className="h-12 w-12 text-secondary-text mx-auto mb-3 opacity-50" />
                      <p className="text-secondary-text">No inventory items</p>
                    </div>
                  ) : (
                    <div className="space-y-3">
                      {inventoryItems.filter((item) => {
                        // Search filter
                        const matchesSearch = item.name.toLowerCase().includes(inventorySearchQuery.toLowerCase()) ||
                          item.description?.toLowerCase().includes(inventorySearchQuery.toLowerCase()) ||
                          item.id.toLowerCase().includes(inventorySearchQuery.toLowerCase());
                        
                        // Category filter
                        const matchesCategory = inventoryCategoryFilter === 'all' || item.categoryId === inventoryCategoryFilter;
                        
                        // Status filter
                        const status = getItemStatus(item);
                        const matchesStatus = inventoryStatusFilter === 'all' || status === inventoryStatusFilter;
                        
                        return matchesSearch && matchesCategory && matchesStatus;
                      }).map((item) => {
                        const status = getItemStatus(item);
                        const daysUntilExpiry = getDaysUntilExpiry(item.expiryDate);
                        const categoryName = categories.find(c => c.id === item.categoryId)?.name || 'Uncategorized';
                        
                        return (
                          <div key={item.id} className="flex items-center justify-between p-4 bg-card-hover border border-light-gray rounded-xl hover:border-light-green transition-colors">
                            <div className="flex items-center space-x-4">
                              <div className={`w-12 h-12 rounded-lg flex items-center justify-center overflow-hidden ${
                                status === 'fresh' ? 'bg-fresh/20' :
                                status === 'expiring' ? 'bg-expiring/20' :
                                status === 'low' || status === 'expired' ? 'bg-warning/20' :
                                'bg-stable/20'
                              }`}>
                                {item.imageUrl ? (
                                  <img 
                                    src={item.imageUrl} 
                                    alt={item.name}
                                    className="w-full h-full object-cover"
                                    onError={(e) => {
                                      // Fallback to emoji if image fails to load
                                      e.currentTarget.style.display = 'none';
                                      e.currentTarget.parentElement!.innerHTML = '📦';
                                      e.currentTarget.parentElement!.classList.add('text-2xl');
                                    }}
                                  />
                                ) : (
                                  <span className="text-2xl">📦</span>
                                )}
                              </div>
                              <div>
                                <p className="font-semibold text-primary-text">{item.name}</p>
                                <div className="flex items-center gap-2 mt-1">
                                  <p className="text-xs text-secondary-text">{categoryName}</p>
                                  <span className="text-xs text-secondary-text">•</span>
                                  <p className="text-xs font-mono text-secondary-text">ID: {item.id.substring(0, 8)}</p>
                                </div>
                              </div>
                            </div>
                            <div className="flex items-center gap-6">
                              <div className="text-center">
                                <p className="text-xs text-secondary-text">Quantity</p>
                                <p className="text-sm font-semibold text-primary-text">{item.quantity} {item.unit || 'units'}</p>
                              </div>
                              <div className="text-center">
                                <p className="text-xs text-secondary-text">Expires</p>
                                <p className="text-sm font-semibold text-primary-text">
                                  {daysUntilExpiry !== null ? `${daysUntilExpiry}d` : 'N/A'}
                                </p>
                              </div>
                              <span className={`px-3 py-1 rounded-full text-xs font-semibold border ${
                                status === 'fresh' ? 'bg-fresh/20 text-primary-green border-fresh' :
                                status === 'expiring' ? 'bg-expiring/20 text-orange-800 border-expiring' :
                                status === 'low' || status === 'expired' ? 'bg-warning/20 text-warning border-warning' :
                                'bg-stable/20 text-stable border-stable'
                              }`}>
                                {status === 'fresh' && 'Fresh'}
                                {status === 'expiring' && 'Expiring'}
                                {status === 'low' && 'Low Stock'}
                                {status === 'expired' && 'Expired'}
                                {status === 'good' && 'Good'}
                              </span>
                              <div className="flex gap-2">
                                <button 
                                  onClick={() => handleEditItem(item)}
                                  className="p-2 hover:bg-stable/10 rounded-lg transition-colors"
                                  title="Edit item"
                                >
                                  <Edit className="h-4 w-4 text-stable" />
                                </button>
                                <button 
                                  onClick={() => handleDeleteItem(item)}
                                  className="p-2 hover:bg-warning/10 rounded-lg transition-colors"
                                  title="Delete item"
                                >
                                  <Trash2 className="h-4 w-4 text-warning" />
                                </button>
                              </div>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}

          {activeTab === 'pickups' && (
            <div className="space-y-6">
              <div className="bg-white rounded-xl shadow-sm border border-light-gray">
                <div className="px-6 py-5 border-b border-light-gray">
                  <h3 className="text-lg font-semibold text-deep-forest">Upcoming Pickups</h3>
                  <p className="text-sm text-secondary-text mt-1">Manage scheduled pickups and update their status</p>
                </div>
                <div className="p-6">
                  {pickupsLoading ? (
                    <div className="text-center py-12">
                      <Loader2 className="h-12 w-12 animate-spin text-primary-green mx-auto" />
                    </div>
                  ) : pickups.length === 0 ? (
                    <div className="text-center py-12">
                      <Calendar className="h-12 w-12 text-secondary-text mx-auto mb-3 opacity-50" />
                      <p className="text-secondary-text">No upcoming pickups</p>
                    </div>
                  ) : (
                    <div className="space-y-4">
                      {pickups.map((pickup) => (
                        <div key={pickup.id} className="glass-card border border-light-gray rounded-xl p-6 hover:shadow-card hover:border-light-green transition-all">
                          <div className="flex items-start justify-between mb-4">
                            <div className="flex-1">
                              <div className="flex items-center space-x-3 mb-2">
                                <div className="w-10 h-10 bg-primary-green rounded-full flex items-center justify-center text-white font-semibold">
                                  {pickup.userFullName?.charAt(0).toUpperCase() || pickup.userEmail?.charAt(0).toUpperCase() || 'U'}
                                </div>
                                <div>
                                  <h4 className="font-semibold text-deep-forest">{pickup.userFullName || pickup.userEmail || 'User'}</h4>
                                  <p className="text-sm text-secondary-text">{pickup.userEmail}</p>
                                </div>
                              </div>
                              <div className="flex items-center space-x-4 text-sm text-secondary-text">
                                <div className="flex items-center">
                                  <Calendar className="h-4 w-4 mr-1" />
                                  <span>{pickup.pickupTime}</span>
                                </div>
                                <div className="flex items-center">
                                  <Package className="h-4 w-4 mr-1" />
                                  <span>{pickup.quantity} items</span>
                                </div>
                              </div>
                            </div>
                            <span className={`px-3 py-1 rounded-full text-xs font-semibold border ${
                              pickup.status === 'ready' ? 'bg-fresh/20 text-primary-green border-fresh' :
                              pickup.status === 'picked-up' ? 'bg-gray-100 text-secondary-text border-light-gray' :
                              'bg-soft-yellow/20 text-amber-800 border-soft-yellow'
                            }`}>
                              {pickup.status === 'ready' && 'Ready for Pickup'}
                              {pickup.status === 'picked-up' && 'Completed'}
                              {pickup.status === 'pending' && 'Pending'}
                            </span>
                          </div>
                          
                          <div className="mb-4">
                            <h5 className="font-medium text-primary-text mb-1">Order Details</h5>
                            <p className="text-sm text-secondary-text">{pickup.name}</p>
                            {pickup.notes && (
                              <p className="text-sm text-secondary-text mt-1 bg-card-hover p-2 rounded border">
                                {pickup.notes}
                              </p>
                            )}
                          </div>

                          <div className="flex gap-2">
                            {pickup.status === 'pending' && (
                              <button 
                                onClick={() => handleUpdatePickupStatus(pickup.id, 'ready')}
                                className="px-4 py-2 bg-btn-primary text-white rounded-lg hover:bg-btn-primary-hover transition-colors font-medium text-sm flex items-center"
                              >
                                <CheckCircle className="h-4 w-4 mr-2" />
                                Mark Ready
                              </button>
                            )}
                            {pickup.status === 'ready' && (
                              <button 
                                onClick={() => handleUpdatePickupStatus(pickup.id, 'picked-up')}
                                className="px-4 py-2 bg-fresh text-white rounded-lg hover:bg-fresh/90 transition-colors font-medium text-sm flex items-center"
                              >
                                <CheckCircle className="h-4 w-4 mr-2" />
                                Mark Picked Up
                              </button>
                            )}
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}

          {activeTab === 'alerts' && (
            <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">System Alerts</h3>
                  <p className="text-sm text-secondary-text mt-1">View and resolve warnings and notifications</p>
                </div>
                <div className="p-6">
                  {alertsLoading ? (
                    <div className="text-center py-12">
                      <Loader2 className="h-12 w-12 animate-spin text-primary-green mx-auto" />
                    </div>
                  ) : alertsList.length === 0 ? (
                  <div className="text-center py-12">
                      <CheckCircle className="h-12 w-12 text-fresh mx-auto mb-3" />
                      <p className="text-deep-forest font-medium">All Clear!</p>
                      <p className="text-secondary-text mt-1">No alerts at this time</p>
                    </div>
                   ) : (
                     <div className="space-y-4">
                       {alertsList.filter(alert => !resolvedAlerts.has(alert.id)).map((alert) => {
                        // Determine color based on alert type and priority
                        const isExpiredType = alert.type === 'expired';
                        const isExpiringType = alert.type === 'expiring';
                        const isLowStockType = alert.type === 'low-stock';
                        
                        return (
                        <div key={alert.id} className={`border-l-4 rounded-lg p-5 ${
                          isExpiredType ? 'bg-red-50 border-red-600' :
                          isExpiringType ? 'bg-orange-50 border-orange-500' :
                          isLowStockType ? 'bg-yellow-50 border-yellow-500' :
                          alert.priority === 'critical' ? 'bg-red-50 border-red-600' :
                          alert.priority === 'high' ? 'bg-orange-50 border-orange-500' :
                          'bg-yellow-50 border-yellow-500'
                        }`}>
                          <div className="flex items-start justify-between">
                            <div className="flex items-start space-x-3">
                              <AlertTriangle className={`h-6 w-6 mt-0.5 ${
                                isExpiredType ? 'text-red-600' :
                                isExpiringType ? 'text-orange-500' :
                                isLowStockType ? 'text-yellow-600' :
                                alert.priority === 'critical' ? 'text-red-600' :
                                alert.priority === 'high' ? 'text-orange-500' :
                                'text-yellow-600'
                              }`} />
                              <div className="flex-1">
                                <h4 className="font-semibold text-deep-forest">{alert.title || alert.message}</h4>
                                <p className="text-sm text-secondary-text mt-1">
                                  {alert.message}
                                </p>
                                {alert.itemId && (
                                  <div className="mt-2 flex flex-wrap gap-3 text-xs">
                                    <span className="bg-white px-2 py-1 rounded border border-light-gray">
                                      <span className="text-secondary-text">ID:</span> <span className="font-mono text-primary-text">{alert.itemId.substring(0, 8)}</span>
                                    </span>
                                    {alert.category && (
                                      <span className="bg-white px-2 py-1 rounded border border-light-gray">
                                        <span className="text-secondary-text">Category:</span> <span className="text-primary-text">{alert.category}</span>
                                      </span>
                                    )}
                                    {alert.expiryDate && (
                                      <span className="bg-white px-2 py-1 rounded border border-light-gray">
                                        <span className="text-secondary-text">Expires:</span> <span className="text-primary-text">{new Date(alert.expiryDate).toLocaleDateString()}</span>
                                      </span>
                                    )}
                                  </div>
                                )}
                                {alert.count && (
                                  <p className="text-xs text-secondary-text mt-2">
                                    {alert.count} item{alert.count > 1 ? 's' : ''} affected
                                  </p>
                                )}
                              </div>
                             </div>
                             <div className="flex gap-2">
                               <button 
                                 onClick={() => handleResolveAlert(alert.id)}
                                 className="px-4 py-2 bg-btn-primary text-white rounded-lg hover:bg-btn-primary-hover transition-colors font-medium text-sm flex items-center"
                               >
                                 <CheckCircle className="h-4 w-4 mr-2" />
                                 Resolve
                               </button>
                             </div>
                          </div>
                        </div>
                      );
                      })}
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}
        </div>
      </main>

      {/* Modals */}
      <AddItemModal
        isOpen={showAddItemModal}
        onClose={() => setShowAddItemModal(false)}
        onSuccess={refreshAllData}
        categories={categories}
      />

      <EditItemModal
        isOpen={showEditItemModal}
        onClose={() => {
          setShowEditItemModal(false);
          setSelectedItem(null);
        }}
        onSuccess={refreshAllData}
        item={selectedItem}
        categories={categories}
      />

      <ConfirmDeleteModal
        isOpen={showDeleteModal}
        onClose={() => {
          setShowDeleteModal(false);
          setSelectedItem(null);
        }}
        onConfirm={confirmDeleteItem}
        title="Delete Item"
        message={selectedItem ? `Are you sure you want to delete "${selectedItem.name}"?` : ''}
        loading={deleteLoading}
      />

      {/* 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-stable/20 text-stable rounded-full text-xs font-semibold border border-stable">
                        Team
                      </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 TeamDashboard;
