import React, { useEffect, useState, useRef } from 'react';
import { 
  BarChart3, 
  Users, 
  Hotel, 
  Calendar,
  TrendingUp,
  RefreshCw,
  CreditCard,
  LogOut,
  Monitor,
  Smartphone,
  Tablet,
} from 'lucide-react';
import reportService, { ReportData } from '../../features/analytics/services/reportService';
import paymentService from '../../features/payments/services/paymentService';
import type { Payment } from '../../features/payments/services/paymentService';
import sessionService, { UserSession } from '../../features/auth/services/sessionService';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import EmptyState from '../../shared/components/EmptyState';
import CurrencyIcon from '../../shared/components/CurrencyIcon';
import { formatDate } from '../../shared/utils/format';
import { useFormatCurrency } from '../../features/payments/hooks/useFormatCurrency';
import { useAsync } from '../../shared/hooks/useAsync';
import { useNavigate } from 'react-router-dom';
import useAuthStore from '../../store/useAuthStore';
import { logger } from '../../shared/utils/logger';
import { getPaymentStatusColor, getPaymentMethodLabel } from '../../shared/utils/paymentUtils';

const DashboardPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const navigate = useNavigate();
  const { logout } = useAuthStore();
  const [dateRange, setDateRange] = useState({
    from: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
    to: new Date().toISOString().split('T')[0],
  });
  const [recentPayments, setRecentPayments] = useState<Payment[]>([]);
  const [loadingPayments, setLoadingPayments] = useState(false);
  const [sessions, setSessions] = useState<UserSession[]>([]);
  const [loadingSessions, setLoadingSessions] = useState(false);
  const paymentsAbortRef = useRef<AbortController | null>(null);
  const sessionsAbortRef = useRef<AbortController | null>(null);
  
  const handleLogout = async () => {
    try {
      await logout();
      // Logout function will redirect to homepage
    } catch (error) {
      logger.error('Logout error', error);
    }
  };

  const fetchDashboardData = async () => {
    const response = await reportService.getReports({
      from: dateRange.from,
      to: dateRange.to,
    });
    return response.data;
  };

  const { data: stats, loading, error, execute } = useAsync<ReportData>(
    fetchDashboardData,
    {
      immediate: true,
      onError: (error: unknown) => {
        const errorMessage = error instanceof Error ? error.message : 'Unable to load dashboard data';
        toast.error(errorMessage);
      }
    }
  );

  useEffect(() => {
    execute();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dateRange]); 

  useEffect(() => {
    // Cancel previous request if exists
    if (paymentsAbortRef.current) {
      paymentsAbortRef.current.abort();
    }

    // Create new abort controller
    paymentsAbortRef.current = new AbortController();

    const fetchPayments = async () => {
      try {
        setLoadingPayments(true);
        const response = await paymentService.getPayments({ page: 1, limit: 5 });
        if (response.success && response.data?.payments) {
          setRecentPayments(response.data.payments);
        } else {
          // Clear data if response is not successful
          setRecentPayments([]);
        }
      } catch (err: unknown) {
        // Handle AbortError silently
        if (err && typeof err === 'object' && 'name' in err && err.name === 'AbortError') {
          return;
        }
        // Clear data when API connection fails
        setRecentPayments([]);
        logger.error('Error fetching payments', err);
      } finally {
        setLoadingPayments(false);
      }
    };
    fetchPayments();

    // Cleanup: abort request on unmount
    return () => {
      if (paymentsAbortRef.current) {
        paymentsAbortRef.current.abort();
      }
    };
  }, []);

  useEffect(() => {
    // Cancel previous request if exists
    if (sessionsAbortRef.current) {
      sessionsAbortRef.current.abort();
    }

    // Create new abort controller
    sessionsAbortRef.current = new AbortController();

    const fetchSessions = async () => {
      try {
        setLoadingSessions(true);
        const response = await sessionService.getMySessions();
        if (response.success && response.data?.sessions) {
          setSessions(response.data.sessions || []);
        } else {
          // Clear data if response is not successful
          setSessions([]);
        }
      } catch (err: unknown) {
        // Handle AbortError silently
        if (err && typeof err === 'object' && 'name' in err && err.name === 'AbortError') {
          return;
        }
        // Clear data when API connection fails
        setSessions([]);
        logger.error('Error fetching sessions', err);
      } finally {
        setLoadingSessions(false);
      }
    };
    fetchSessions();

    // Cleanup: abort request on unmount
    return () => {
      if (sessionsAbortRef.current) {
        sessionsAbortRef.current.abort();
      }
    };
  }, []);

  const handleRefresh = () => {
    execute();
  };

  const getDeviceIcon = (userAgent?: string) => {
    if (!userAgent) return <Monitor className="w-4 h-4 text-slate-600" />;
    if (userAgent.includes('Mobile')) return <Smartphone className="w-4 h-4 text-blue-600" />;
    if (userAgent.includes('Tablet')) return <Tablet className="w-4 h-4 text-purple-600" />;
    return <Monitor className="w-4 h-4 text-slate-600" />;
  };

  const getDeviceName = (userAgent?: string) => {
    if (!userAgent) return 'Unknown Device';
    if (userAgent.includes('Chrome')) return 'Chrome';
    if (userAgent.includes('Firefox')) return 'Firefox';
    if (userAgent.includes('Safari')) return 'Safari';
    if (userAgent.includes('Edge')) return 'Edge';
    if (userAgent.includes('Mobile')) return 'Mobile Device';
    if (userAgent.includes('Tablet')) return 'Tablet';
    return 'Web Browser';
  };

  if (loading) {
    return <Loading fullScreen text="Loading dashboard..." />;
  }

  if (error || !stats) {
    return (
      <div className="space-y-6">
        <EmptyState
          title="Unable to Load Dashboard"
          description={error?.message || 'Something went wrong. Please try again.'}
          action={{
            label: 'Retry',
            onClick: handleRefresh
          }}
        />
      </div>
    );
  }

  return (
    <div className="space-y-3 sm:space-y-4 md:space-y-6 lg:space-y-8 bg-gradient-to-br from-slate-50 via-white to-slate-50 min-h-screen max-w-full overflow-x-hidden">
      {}
      <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4 sm:gap-6 animate-fade-in">
        <div className="w-full lg:w-auto">
          <div className="flex items-center gap-2 sm:gap-3 mb-2">
            <div className="h-1 w-12 sm:w-16 bg-gradient-to-r from-amber-400 to-amber-600 rounded-full"></div>
            <h1 className="text-xl sm:text-2xl md:text-2xl font-bold bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 bg-clip-text text-transparent tracking-tight">
              Dashboard
            </h1>
          </div>
          <p className="text-slate-600 mt-2 sm:mt-3 text-xs sm:text-sm md:text-sm font-light">Hotel operations overview and analytics</p>
        </div>
        
        {}
        <div className="flex flex-col sm:flex-row gap-3 w-full lg:w-auto">
          <div className="flex flex-col xs:flex-row gap-2 sm:gap-3 w-full sm:w-auto">
            <input
              type="date"
              value={dateRange.from}
              onChange={(e) => setDateRange({ ...dateRange, from: e.target.value })}
              className="flex-1 sm:flex-none px-3 sm:px-4 py-2 sm:py-2.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md text-sm sm:text-base"
            />
            <span className="hidden xs:inline-flex items-center text-slate-500 font-medium">to</span>
            <input
              type="date"
              value={dateRange.to}
              onChange={(e) => setDateRange({ ...dateRange, to: e.target.value })}
              className="flex-1 sm:flex-none px-3 sm:px-4 py-2 sm:py-2.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md text-sm sm:text-base"
            />
          </div>
          <div className="flex gap-2 sm:gap-3 items-center w-full sm:w-auto">
            <button
              onClick={handleRefresh}
              disabled={loading}
              className="flex-1 sm:flex-none px-4 sm:px-6 py-2 sm:py-2.5 bg-gradient-to-r from-amber-500 to-amber-600 text-white rounded-xl font-semibold hover:from-amber-600 hover:to-amber-700 transition-all duration-200 shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 text-xs sm:text-sm"
            >
              <RefreshCw className={`w-3 h-3 sm:w-4 sm:h-4 ${loading ? 'animate-spin' : ''}`} />
              Refresh
            </button>
            <button
              onClick={handleLogout}
              className="flex-1 sm:flex-none px-4 sm:px-6 py-2 sm:py-2.5 bg-gradient-to-r from-rose-500 to-rose-600 text-white rounded-xl font-semibold hover:from-rose-600 hover:to-rose-700 transition-all duration-200 shadow-lg hover:shadow-xl flex items-center justify-center gap-2 text-xs sm:text-sm"
              title="Logout"
            >
              <LogOut className="w-3 h-3 sm:w-4 sm:h-4" />
              <span className="hidden sm:inline">Logout</span>
            </button>
          </div>
        </div>
      </div>

      {}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-5 md:gap-6">
        {}
        <div className="bg-white/80 backdrop-blur-sm rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 border-l-4 border-l-emerald-500 animate-slide-up hover:shadow-2xl transition-all duration-300" style={{ animationDelay: '0.1s' }}>
          <div className="flex items-center justify-between">
            <div className="flex-1 min-w-0 pr-2">
              <p className="text-slate-500 text-xs font-semibold uppercase tracking-wider mb-1 sm:mb-2">Total Revenue</p>
              <p className="text-lg sm:text-xl md:text-2xl font-bold bg-gradient-to-r from-emerald-600 to-emerald-700 bg-clip-text text-transparent truncate">
                {formatCurrency(stats?.total_revenue || 0)}
              </p>
            </div>
            <div className="bg-gradient-to-br from-emerald-100 to-emerald-200 p-3 sm:p-4 rounded-xl sm:rounded-2xl shadow-lg flex-shrink-0">
              <CurrencyIcon className="text-emerald-600" size={20} />
            </div>
          </div>
          <div className="flex items-center mt-4 sm:mt-5 pt-3 sm:pt-4 border-t border-slate-100">
            <TrendingUp className="w-3 h-3 sm:w-4 sm:h-4 text-emerald-500 mr-1 sm:mr-2 flex-shrink-0" />
            <span className="text-emerald-600 font-semibold text-xs sm:text-sm">Active</span>
            <span className="text-slate-500 ml-1 sm:ml-2 text-xs sm:text-sm truncate">All time revenue</span>
          </div>
        </div>

        {}
        <div className="bg-white/80 backdrop-blur-sm rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 border-l-4 border-l-blue-500 animate-slide-up hover:shadow-2xl transition-all duration-300" style={{ animationDelay: '0.2s' }}>
          <div className="flex items-center justify-between">
            <div className="flex-1 min-w-0 pr-2">
              <p className="text-slate-500 text-xs font-semibold uppercase tracking-wider mb-1 sm:mb-2">Total Bookings</p>
              <p className="text-lg sm:text-xl md:text-2xl font-bold bg-gradient-to-r from-blue-600 to-blue-700 bg-clip-text text-transparent">
                {stats?.total_bookings || 0}
              </p>
            </div>
            <div className="bg-gradient-to-br from-blue-100 to-blue-200 p-3 sm:p-4 rounded-xl sm:rounded-2xl shadow-lg flex-shrink-0">
              <Calendar className="w-5 h-5 sm:w-6 sm:h-6 md:w-7 md:h-7 text-blue-600" />
            </div>
          </div>
          <div className="flex items-center mt-4 sm:mt-5 pt-3 sm:pt-4 border-t border-slate-100">
            <span className="text-slate-500 text-xs sm:text-sm truncate">
              {stats.total_bookings > 0 ? 'Total bookings recorded' : 'No bookings yet'}
            </span>
          </div>
        </div>

        {}
        <div className="bg-white/80 backdrop-blur-sm rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 border-l-4 border-l-purple-500 animate-slide-up hover:shadow-2xl transition-all duration-300" style={{ animationDelay: '0.3s' }}>
          <div className="flex items-center justify-between">
            <div className="flex-1 min-w-0 pr-2">
              <p className="text-slate-500 text-xs font-semibold uppercase tracking-wider mb-1 sm:mb-2">Available Rooms</p>
              <p className="text-lg sm:text-xl md:text-2xl font-bold bg-gradient-to-r from-purple-600 to-purple-700 bg-clip-text text-transparent">
                {stats?.available_rooms || 0}
              </p>
            </div>
            <div className="bg-gradient-to-br from-purple-100 to-purple-200 p-3 sm:p-4 rounded-xl sm:rounded-2xl shadow-lg flex-shrink-0">
              <Hotel className="w-5 h-5 sm:w-6 sm:h-6 md:w-7 md:h-7 text-purple-600" />
            </div>
          </div>
          <div className="flex items-center mt-4 sm:mt-5 pt-3 sm:pt-4 border-t border-slate-100">
            <span className="text-slate-500 text-xs sm:text-sm truncate">
              {stats?.occupied_rooms || 0} rooms in use
            </span>
          </div>
        </div>

        {}
        <div className="bg-white/80 backdrop-blur-sm rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 border-l-4 border-l-amber-500 animate-slide-up hover:shadow-2xl transition-all duration-300" style={{ animationDelay: '0.4s' }}>
          <div className="flex items-center justify-between">
            <div className="flex-1 min-w-0 pr-2">
              <p className="text-slate-500 text-xs font-semibold uppercase tracking-wider mb-1 sm:mb-2">Customers</p>
              <p className="text-lg sm:text-xl md:text-2xl font-bold bg-gradient-to-r from-amber-600 to-amber-700 bg-clip-text text-transparent">
                {stats?.total_customers || 0}
              </p>
            </div>
            <div className="bg-gradient-to-br from-amber-100 to-amber-200 p-3 sm:p-4 rounded-xl sm:rounded-2xl shadow-lg flex-shrink-0">
              <Users className="w-5 h-5 sm:w-6 sm:h-6 md:w-7 md:h-7 text-amber-600" />
            </div>
          </div>
          <div className="flex items-center mt-4 sm:mt-5 pt-3 sm:pt-4 border-t border-slate-100">
            <span className="text-slate-500 text-xs sm:text-sm truncate">
              Unique customers with bookings
            </span>
          </div>
        </div>
      </div>

      {}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-5 md:gap-6">
        {}
        <div className="bg-white/80 backdrop-blur-sm rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 animate-fade-in">
          <div className="flex items-center justify-between mb-4 sm:mb-5 md:mb-6 pb-3 sm:pb-4 border-b border-slate-200">
            <h2 className="text-sm sm:text-base md:text-base font-bold text-slate-900">Daily Revenue</h2>
            <div className="p-2 sm:p-3 bg-gradient-to-br from-blue-100 to-blue-200 rounded-lg sm:rounded-xl shadow-md flex-shrink-0">
              <BarChart3 className="w-4 h-4 sm:w-5 sm:h-5 text-blue-600" />
            </div>
          </div>
          {stats?.revenue_by_date && stats.revenue_by_date.length > 0 ? (
            <div className="space-y-2 sm:space-y-3">
              {stats.revenue_by_date.slice(0, 7).map((item, index) => {
                const maxRevenue = Math.max(...stats.revenue_by_date!.map(r => r.revenue));
                return (
                  <div key={index} className="flex items-center py-1.5 sm:py-2">
                    <span className="text-xs sm:text-sm text-slate-600 w-16 sm:w-20 md:w-24 font-medium flex-shrink-0">
                      {formatDate(item.date, 'short')}
                    </span>
                    <div className="flex-1 mx-2 sm:mx-3 md:mx-4 min-w-0">
                      <div className="bg-slate-200 rounded-full h-4 sm:h-5 overflow-hidden shadow-inner">
                        <div
                          className="bg-gradient-to-r from-emerald-500 to-emerald-600 h-4 sm:h-5 rounded-full transition-all shadow-md"
                          style={{
                            width: `${Math.min((item.revenue / (maxRevenue || 1)) * 100, 100)}%`,
                          }}
                        />
                      </div>
                    </div>
                    <span className="text-xs sm:text-sm font-bold text-slate-900 w-20 sm:w-28 md:w-32 text-right bg-gradient-to-r from-emerald-600 to-emerald-700 bg-clip-text text-transparent flex-shrink-0">
                      {formatCurrency(item.revenue)}
                    </span>
                  </div>
                );
              })}
            </div>
          ) : (
            <EmptyState
              title="No Revenue Data"
              description="No revenue data available for the selected date range"
            />
          )}
        </div>

        {}
        <div className="bg-white/80 backdrop-blur-sm rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 animate-fade-in" style={{ animationDelay: '0.2s' }}>
          <div className="flex items-center justify-between mb-4 sm:mb-5 md:mb-6 pb-3 sm:pb-4 border-b border-slate-200">
            <h2 className="text-sm sm:text-base md:text-base font-bold text-slate-900">Booking Status</h2>
          </div>
          {stats?.bookings_by_status && Object.keys(stats.bookings_by_status).length > 0 ? (
            <div className="space-y-3 sm:space-y-4">
              {Object.entries(stats.bookings_by_status)
                .filter(([_, count]) => count > 0)
                .map(([status, count]) => {
                  const statusColors: Record<string, string> = {
                    pending: 'bg-amber-500',
                    confirmed: 'bg-blue-500',
                    checked_in: 'bg-emerald-500',
                    checked_out: 'bg-slate-500',
                    cancelled: 'bg-rose-500',
                  };
                  const statusLabels: Record<string, string> = {
                    pending: 'Pending confirmation',
                    confirmed: 'Confirmed',
                    checked_in: 'Checked in',
                    checked_out: 'Checked out',
                    cancelled: '❌ Canceled',
                  };
                  return (
                    <div key={status} className="flex items-center justify-between p-2.5 sm:p-3 bg-gradient-to-r from-slate-50 to-white rounded-lg sm:rounded-xl hover:shadow-md transition-all duration-200 border border-slate-100">
                      <div className="flex items-center gap-2 sm:gap-3 min-w-0 flex-1">
                        <div className={`w-3 h-3 sm:w-4 sm:h-4 rounded-full shadow-md flex-shrink-0 ${statusColors[status] || 'bg-slate-500'}`} />
                        <span className="text-xs sm:text-sm md:text-base text-slate-700 font-medium truncate">{statusLabels[status] || status}</span>
                      </div>
                      <span className="font-bold text-slate-900 text-sm sm:text-base flex-shrink-0 ml-2">{count}</span>
                    </div>
                  );
                })}
            </div>
          ) : (
            <EmptyState
              title="No Booking Data"
              description="No booking status data available"
            />
          )}
        </div>
      </div>

      {}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-5 md:gap-6">
        {}
        <div className="bg-white/80 backdrop-blur-sm rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 animate-fade-in">
          <div className="flex items-center justify-between mb-4 sm:mb-5 md:mb-6 pb-3 sm:pb-4 border-b border-slate-200">
            <h2 className="text-sm sm:text-base md:text-base font-bold text-slate-900">Top Booked Rooms</h2>
            <div className="p-2 bg-gradient-to-br from-amber-100 to-amber-200 rounded-lg sm:rounded-xl flex-shrink-0">
              <Hotel className="w-4 h-4 sm:w-5 sm:h-5 text-amber-600" />
            </div>
          </div>
          {stats?.top_rooms && stats.top_rooms.length > 0 ? (
            <div className="space-y-2 sm:space-y-3">
              {stats.top_rooms.map((room, index) => (
                <div key={room.room_id} className="flex items-center justify-between p-3 sm:p-4 bg-gradient-to-r from-slate-50 to-white rounded-lg sm:rounded-xl hover:from-amber-50 hover:to-yellow-50 transition-all duration-300 border border-slate-200 hover:border-amber-300 hover:shadow-lg">
                  <div className="flex items-center gap-2 sm:gap-3 md:gap-4 min-w-0 flex-1">
                    <span className="flex items-center justify-center w-10 h-10 sm:w-12 sm:h-12 bg-gradient-to-br from-amber-500 to-amber-600 text-white rounded-lg sm:rounded-xl font-bold shadow-lg shadow-amber-500/40 text-base sm:text-lg flex-shrink-0">
                      {index + 1}
                    </span>
                    <div className="min-w-0 flex-1">
                      <p className="font-semibold text-slate-900 text-sm sm:text-base truncate">Room {room.room_number}</p>
                      <p className="text-xs sm:text-sm text-slate-500">{room.bookings} booking{room.bookings !== 1 ? 's' : ''}</p>
                    </div>
                  </div>
                  <span className="font-bold text-emerald-600 bg-gradient-to-r from-emerald-600 to-emerald-700 bg-clip-text text-transparent text-sm sm:text-base flex-shrink-0 ml-2">
                    {formatCurrency(room.revenue)}
                  </span>
                </div>
              ))}
            </div>
          ) : (
            <EmptyState
              title="No Room Data"
              description="No room booking data available for the selected date range"
            />
          )}
        </div>

        {}
        <div className="bg-white/80 backdrop-blur-sm rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 animate-fade-in" style={{ animationDelay: '0.2s' }}>
          <div className="flex items-center justify-between mb-4 sm:mb-5 md:mb-6 pb-3 sm:pb-4 border-b border-slate-200">
            <h2 className="text-sm sm:text-base md:text-base font-bold text-slate-900">Services Used</h2>
            <div className="p-2 bg-gradient-to-br from-purple-100 to-purple-200 rounded-lg sm:rounded-xl flex-shrink-0">
              <BarChart3 className="w-4 h-4 sm:w-5 sm:h-5 text-purple-600" />
            </div>
          </div>
          {stats?.service_usage && stats.service_usage.length > 0 ? (
            <div className="space-y-2 sm:space-y-3">
              {stats.service_usage.map((service) => (
                <div key={service.service_id} className="flex items-center justify-between p-3 sm:p-4 bg-gradient-to-r from-slate-50 to-white rounded-lg sm:rounded-xl hover:from-purple-50 hover:to-indigo-50 transition-all duration-300 border border-slate-200 hover:border-purple-300 hover:shadow-lg">
                  <div className="min-w-0 flex-1 pr-2">
                    <p className="font-semibold text-slate-900 text-sm sm:text-base truncate">{service.service_name}</p>
                    <p className="text-xs sm:text-sm text-slate-500">{service.usage_count} time{service.usage_count !== 1 ? 's' : ''} used</p>
                  </div>
                  <span className="font-bold text-purple-600 bg-gradient-to-r from-purple-600 to-purple-700 bg-clip-text text-transparent text-sm sm:text-base flex-shrink-0">
                    {formatCurrency(service.total_revenue)}
                  </span>
                </div>
              ))}
            </div>
          ) : (
            <EmptyState
              title="No Service Data"
              description="No service usage data available for the selected date range"
            />
          )}
        </div>

        {}
        <div className="bg-white/80 backdrop-blur-sm rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 animate-fade-in" style={{ animationDelay: '0.3s' }}>
          <div className="flex items-center justify-between mb-4 sm:mb-5 md:mb-6 pb-3 sm:pb-4 border-b border-slate-200">
            <h2 className="text-sm sm:text-base md:text-base font-bold text-slate-900">Recent Payments</h2>
            <button
              onClick={() => navigate('/admin/payments')}
              className="text-xs sm:text-sm text-amber-600 hover:text-amber-700 font-semibold hover:underline transition-colors flex-shrink-0 ml-2"
            >
              View All →
            </button>
          </div>
          {loadingPayments ? (
            <div className="flex items-center justify-center py-8">
              <Loading text="Loading payments..." />
            </div>
          ) : recentPayments && recentPayments.length > 0 ? (
            <div className="space-y-2 sm:space-y-3">
              {recentPayments.map((payment) => (
                <div 
                  key={payment.id}
                  className="flex items-center justify-between p-3 sm:p-4 bg-gradient-to-r from-slate-50 to-white rounded-lg sm:rounded-xl hover:from-amber-50 hover:to-yellow-50 border border-slate-200 hover:border-amber-300 hover:shadow-lg cursor-pointer transition-all duration-200"
                  onClick={() => navigate(`/admin/payments`)}
                >
                  <div className="flex items-center space-x-2 sm:space-x-3 md:space-x-4 flex-1 min-w-0">
                    <div className="p-2 sm:p-3 bg-gradient-to-br from-blue-100 to-blue-200 rounded-lg sm:rounded-xl shadow-md flex-shrink-0">
                      <CreditCard className="w-4 h-4 sm:w-5 sm:h-5 text-blue-600" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-bold text-slate-900 truncate text-xs sm:text-sm md:text-base">
                        {formatCurrency(payment.amount)}
                      </p>
                      <div className="flex items-center gap-1 sm:gap-2 mt-1 flex-wrap">
                        <p className="text-xs sm:text-sm text-slate-600 font-medium">
                          {getPaymentMethodLabel(payment.payment_method)}
                        </p>
                        {payment.payment_date && (
                          <span className="text-xs text-slate-400">
                            • {formatDate(payment.payment_date, 'short')}
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                  <span className={`px-2 sm:px-3 py-1 sm:py-1.5 text-xs font-semibold rounded-full border shadow-sm flex-shrink-0 ml-2 ${getPaymentStatusColor(payment.payment_status)}`}>
                    {payment.payment_status.charAt(0).toUpperCase() + payment.payment_status.slice(1)}
                  </span>
                </div>
              ))}
            </div>
          ) : (
            <EmptyState
              title="No Recent Payments"
              description="Recent payment transactions will appear here"
              action={{
                label: 'View All Payments',
                onClick: () => navigate('/admin/payments')
              }}
            />
          )}
        </div>

        {}
        <div className="bg-white/80 backdrop-blur-sm rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 animate-fade-in" style={{ animationDelay: '0.4s' }}>
          <div className="flex items-center justify-between mb-4 sm:mb-5 md:mb-6 pb-3 sm:pb-4 border-b border-slate-200">
            <h2 className="text-sm sm:text-base md:text-base font-bold text-slate-900">Active Sessions</h2>
            <div className="p-2 bg-gradient-to-br from-indigo-100 to-indigo-200 rounded-lg sm:rounded-xl flex-shrink-0">
              <Monitor className="w-4 h-4 sm:w-5 sm:h-5 text-indigo-600" />
            </div>
          </div>
          {loadingSessions ? (
            <div className="flex items-center justify-center py-8">
              <Loading text="Loading sessions..." />
            </div>
          ) : sessions && sessions.length > 0 ? (
            <div className="space-y-2 sm:space-y-3">
              {sessions.slice(0, 3).map((session) => (
                <div 
                  key={session.id}
                  className="flex items-center justify-between p-3 sm:p-4 bg-gradient-to-r from-slate-50 to-white rounded-lg sm:rounded-xl hover:from-indigo-50 hover:to-purple-50 border border-slate-200 hover:border-indigo-300 hover:shadow-lg transition-all duration-200"
                >
                  <div className="flex items-center space-x-2 sm:space-x-3 md:space-x-4 flex-1 min-w-0">
                    <div className="p-2 sm:p-3 bg-gradient-to-br from-indigo-100 to-indigo-200 rounded-lg sm:rounded-xl shadow-md flex-shrink-0">
                      {getDeviceIcon(session.user_agent)}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-semibold text-slate-900 text-xs sm:text-sm md:text-base truncate">
                        {getDeviceName(session.user_agent)}
                      </p>
                      <div className="flex items-center gap-1 sm:gap-2 mt-1 flex-wrap">
                        <p className="text-xs sm:text-sm text-slate-600">
                          {session.ip_address || 'Unknown IP'}
                        </p>
                        {session.last_activity && (
                          <span className="text-xs text-slate-400">
                            • {formatDate(session.last_activity, 'short')}
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              ))}
              {sessions.length > 3 && (
                <div className="text-center pt-2">
                  <span className="text-xs sm:text-sm text-amber-600 font-semibold">
                    +{sessions.length - 3} more session{sessions.length - 3 !== 1 ? 's' : ''}
                  </span>
                </div>
              )}
            </div>
          ) : (
            <EmptyState
              title="No Active Sessions"
              description="Your active sessions will appear here"
            />
          )}
        </div>
      </div>
    </div>
  );
};

export default DashboardPage;
