import React, { useState, useEffect, useRef } from 'react';
import { 
  TrendingUp, 
  Hotel, 
  Calendar,
  Activity,
  TrendingDown,
  CreditCard,
  Monitor,
  Smartphone,
  Tablet,
  Award,
  Star,
} from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import dashboardService, { CustomerDashboardStats } from '../../features/analytics/services/dashboardService';
import paymentService from '../../features/payments/services/paymentService';
import loyaltyService from '../../features/loyalty/services/loyaltyService';
import type { Payment } from '../../features/payments/services/paymentService';
import sessionService, { UserSession } from '../../features/auth/services/sessionService';
import { toast } from 'react-toastify';
import { formatDate, formatRelativeTime } from '../../shared/utils/format';
import { useFormatCurrency } from '../../features/payments/hooks/useFormatCurrency';
import Loading from '../../shared/components/Loading';
import EmptyState from '../../shared/components/EmptyState';
import CurrencyIcon from '../../shared/components/CurrencyIcon';
import { useAsync } from '../../shared/hooks/useAsync';
import { getPaymentStatusColor, getPaymentMethodLabel } from '../../shared/utils/paymentUtils';
import { logger } from '../../shared/utils/logger';

interface LoyaltyInfo {
  available_points: number;
  tier_name: string;
  lifetime_points: number;
  next_tier_points_needed: number | null;
}

const DashboardPage: React.FC = () => {
  const navigate = useNavigate();
  const { formatCurrency } = useFormatCurrency();
  const [recentPayments, setRecentPayments] = useState<Payment[]>([]);
  const [loadingPayments, setLoadingPayments] = useState(false);
  const [sessions, setSessions] = useState<UserSession[]>([]);
  const [loadingSessions, setLoadingSessions] = useState(false);
  const [loyaltyInfo, setLoyaltyInfo] = useState<LoyaltyInfo | null>(null);
  const [_loadingLoyalty, setLoadingLoyalty] = useState(false);
  
  const fetchDashboardData = async (): Promise<CustomerDashboardStats> => {
    const response = await dashboardService.getCustomerDashboardStats();
    return response.data;
  };

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

  const paymentsAbortControllerRef = useRef<AbortController | null>(null);

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

    // Create new abort controller
    paymentsAbortControllerRef.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) {
        const isAbortError = (e: unknown): boolean => {
          if (typeof e === 'object' && e !== null) {
            const error = e as { name?: string; code?: string };
            return error.name === 'AbortError' || error.code === 'ERR_CANCELED';
          }
          return false;
        };
        if (!isAbortError(err)) {
          // Clear data when API connection fails
          setRecentPayments([]);
          logger.error('Error fetching payments', err);
        }
      } finally {
        setLoadingPayments(false);
      }
    };
    
    fetchPayments();

    return () => {
      if (paymentsAbortControllerRef.current) {
        paymentsAbortControllerRef.current.abort();
      }
    };
  }, []);

  const sessionsAbortControllerRef = useRef<AbortController | null>(null);

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

    // Create new abort controller
    sessionsAbortControllerRef.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) {
        const isAbortError = (e: unknown): boolean => {
          if (typeof e === 'object' && e !== null) {
            const error = e as { name?: string; code?: string };
            return error.name === 'AbortError' || error.code === 'ERR_CANCELED';
          }
          return false;
        };
        if (!isAbortError(err)) {
          // Clear data when API connection fails
          setSessions([]);
          logger.error('Error fetching sessions', err);
        }
      } finally {
        setLoadingSessions(false);
      }
    };
    
    fetchSessions();

    return () => {
      if (sessionsAbortControllerRef.current) {
        sessionsAbortControllerRef.current.abort();
      }
    };
  }, []);

  // Fetch loyalty info
  const loyaltyAbortControllerRef = useRef<AbortController | null>(null);
  
  useEffect(() => {
    if (loyaltyAbortControllerRef.current) {
      loyaltyAbortControllerRef.current.abort();
    }
    
    loyaltyAbortControllerRef.current = new AbortController();
    
    const fetchLoyalty = async () => {
      try {
        setLoadingLoyalty(true);
        const response = await loyaltyService.getMyLoyalty();
        if (response.status === 'success' && response.data) {
          setLoyaltyInfo({
            available_points: response.data.available_points || 0,
            tier_name: response.data.tier?.name || 'Bronze',
            lifetime_points: response.data.lifetime_points || 0,
            next_tier_points_needed: response.data.next_tier_points_needed,
          });
        }
      } catch (err: unknown) {
        const isAbortError = (e: unknown): boolean => {
          if (typeof e === 'object' && e !== null) {
            const error = e as { name?: string; code?: string };
            return error.name === 'AbortError' || error.code === 'ERR_CANCELED';
          }
          return false;
        };
        if (!isAbortError(err)) {
          // Loyalty is optional, don't show error
          logger.debug('Loyalty info not available', err);
        }
      } finally {
        setLoadingLoyalty(false);
      }
    };
    
    fetchLoyalty();
    
    return () => {
      if (loyaltyAbortControllerRef.current) {
        loyaltyAbortControllerRef.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';
    // Try to extract browser/device info
    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="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-50 px-3 sm:px-4 md:px-6 lg:px-8 py-6 sm:py-8 md:py-10">
        <EmptyState
          title="Unable to Load Dashboard"
          description={error?.message || 'Something went wrong. Please try again.'}
          action={{
            label: 'Retry',
            onClick: handleRefresh
          }}
        />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-50 px-3 sm:px-4 md:px-6 lg:px-8 py-6 sm:py-8 md:py-10">
      <div className="mb-6 sm:mb-8 md:mb-10 animate-fade-in">
        <div className="flex items-center gap-2 sm:gap-3 mb-2 sm:mb-3">
          <div className="h-1 w-12 sm:w-16 md:w-20 bg-gradient-to-r from-blue-400 via-indigo-500 to-purple-600 rounded-full"></div>
          <h1 className="text-2xl sm:text-3xl md:text-4xl 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-sm sm:text-base md:text-lg font-light">
          Overview of your activity and bookings
        </p>
      </div>

      {}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-5 md:gap-6 mb-6 sm:mb-8 md:mb-10">
        {}
        <div className="bg-white/90 backdrop-blur-md 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 hover:scale-[1.02] transition-all duration-300" style={{ animationDelay: '0.1s' }}>
          <div className="flex items-center justify-between mb-3 sm:mb-4">
            <div className="p-2 sm:p-3 md:p-4 bg-gradient-to-br from-blue-100 to-blue-200 rounded-lg sm:rounded-xl shadow-lg">
              <Calendar className="w-5 h-5 sm:w-6 sm:h-6 md:w-7 md:h-7 text-blue-600" />
            </div>
            {stats.booking_change_percentage !== 0 && (
              <span className={`text-xs sm:text-sm font-semibold flex items-center gap-1 px-2 py-1 rounded-full ${
                stats.booking_change_percentage > 0 
                  ? 'text-emerald-700 bg-emerald-50 border border-emerald-200' 
                  : 'text-rose-700 bg-rose-50 border border-rose-200'
              }`}>
                {stats.booking_change_percentage > 0 ? (
                  <TrendingUp className="w-3 h-3 sm:w-4 sm:h-4" />
                ) : (
                  <TrendingDown className="w-3 h-3 sm:w-4 sm:h-4" />
                )}
                {Math.abs(stats.booking_change_percentage).toFixed(1)}%
              </span>
            )}
          </div>
          <h3 className="text-slate-500 text-xs sm:text-sm font-semibold uppercase tracking-wider mb-1 sm:mb-2">
            Total Bookings
          </h3>
          <p className="text-2xl sm:text-3xl md:text-4xl font-bold bg-gradient-to-r from-blue-600 to-blue-700 bg-clip-text text-transparent">
            {stats.total_bookings}
          </p>
        </div>

        {}
        <div className="bg-white/90 backdrop-blur-md 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 hover:scale-[1.02] transition-all duration-300" style={{ animationDelay: '0.2s' }}>
          <div className="flex items-center justify-between mb-3 sm:mb-4">
            <div className="p-2 sm:p-3 md:p-4 bg-gradient-to-br from-emerald-100 to-emerald-200 rounded-lg sm:rounded-xl shadow-lg">
              <CurrencyIcon className="text-emerald-600" size={24} />
            </div>
            {stats.spending_change_percentage !== 0 && (
              <span className={`text-xs sm:text-sm font-semibold flex items-center gap-1 px-2 py-1 rounded-full ${
                stats.spending_change_percentage > 0 
                  ? 'text-emerald-700 bg-emerald-50 border border-emerald-200' 
                  : 'text-rose-700 bg-rose-50 border border-rose-200'
              }`}>
                {stats.spending_change_percentage > 0 ? (
                  <TrendingUp className="w-3 h-3 sm:w-4 sm:h-4" />
                ) : (
                  <TrendingDown className="w-3 h-3 sm:w-4 sm:h-4" />
                )}
                {Math.abs(stats.spending_change_percentage).toFixed(1)}%
              </span>
            )}
          </div>
          <h3 className="text-slate-500 text-xs sm:text-sm font-semibold uppercase tracking-wider mb-1 sm:mb-2">
            Total Spending
          </h3>
          <p className="text-xl sm:text-2xl md:text-3xl font-bold bg-gradient-to-r from-emerald-600 to-emerald-700 bg-clip-text text-transparent truncate">
            {formatCurrency(stats.total_spending)}
          </p>
        </div>

        {}
        <div className="bg-white/90 backdrop-blur-md 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 hover:scale-[1.02] transition-all duration-300" style={{ animationDelay: '0.3s' }}>
          <div className="flex items-center justify-between mb-3 sm:mb-4">
            <div className="p-2 sm:p-3 md:p-4 bg-gradient-to-br from-purple-100 to-purple-200 rounded-lg sm:rounded-xl shadow-lg">
              <Hotel className="w-5 h-5 sm:w-6 sm:h-6 md:w-7 md:h-7 text-purple-600" />
            </div>
            {stats.currently_staying > 0 && (
              <span className="text-xs sm:text-sm text-emerald-700 font-semibold px-2 py-1 bg-emerald-50 border border-emerald-200 rounded-full">
                Active
              </span>
            )}
          </div>
          <h3 className="text-slate-500 text-xs sm:text-sm font-semibold uppercase tracking-wider mb-1 sm:mb-2">
            Currently Staying
          </h3>
          <p className="text-2xl sm:text-3xl md:text-4xl font-bold bg-gradient-to-r from-purple-600 to-purple-700 bg-clip-text text-transparent">
            {stats.currently_staying}
          </p>
        </div>

        {}
        <div className="bg-white/90 backdrop-blur-md 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 hover:scale-[1.02] transition-all duration-300" style={{ animationDelay: '0.4s' }}>
          <div className="flex items-center justify-between mb-3 sm:mb-4">
            <div className="p-2 sm:p-3 md:p-4 bg-gradient-to-br from-amber-100 to-amber-200 rounded-lg sm:rounded-xl shadow-lg">
              <TrendingUp className="w-5 h-5 sm:w-6 sm:h-6 md:w-7 md:h-7 text-amber-600" />
            </div>
          </div>
          <h3 className="text-slate-500 text-xs sm:text-sm font-semibold uppercase tracking-wider mb-1 sm:mb-2">
            Upcoming Bookings
          </h3>
          <p className="text-2xl sm:text-3xl md:text-4xl font-bold bg-gradient-to-r from-amber-600 to-amber-700 bg-clip-text text-transparent">
            {stats.upcoming_bookings.length}
          </p>
        </div>
      </div>

      {/* Loyalty Points Card */}
      {loyaltyInfo && (
        <div 
          className="bg-gradient-to-r from-amber-500 via-yellow-500 to-amber-500 rounded-xl sm:rounded-2xl shadow-xl p-4 sm:p-5 md:p-6 mb-6 sm:mb-8 md:mb-10 animate-fade-in cursor-pointer hover:shadow-2xl transition-all duration-300"
          onClick={() => navigate('/loyalty')}
        >
          <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
            <div className="flex items-center gap-4">
              <div className="p-3 sm:p-4 bg-white/20 backdrop-blur-sm rounded-xl sm:rounded-2xl">
                <Award className="w-8 h-8 sm:w-10 sm:h-10 text-white" />
              </div>
              <div>
                <div className="flex items-center gap-2 mb-1">
                  <Star className="w-4 h-4 text-white" />
                  <span className="text-white/80 text-sm font-medium uppercase tracking-wider">{loyaltyInfo.tier_name} Member</span>
                </div>
                <p className="text-3xl sm:text-4xl font-bold text-white">
                  {loyaltyInfo.available_points.toLocaleString()} <span className="text-lg sm:text-xl font-medium">points</span>
                </p>
              </div>
            </div>
            <div className="text-left sm:text-right">
              <p className="text-white/80 text-sm">Lifetime Points: {loyaltyInfo.lifetime_points.toLocaleString()}</p>
              {loyaltyInfo.next_tier_points_needed && loyaltyInfo.next_tier_points_needed > 0 && (
                <p className="text-white/90 text-sm font-medium mt-1">
                  {loyaltyInfo.next_tier_points_needed.toLocaleString()} points to next tier
                </p>
              )}
              <p className="text-white text-xs mt-2 hover:underline">View Rewards →</p>
            </div>
          </div>
        </div>
      )}

      {}
      <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-4 gap-4 sm:gap-5 md:gap-6">
        {}
        <div className="bg-white/90 backdrop-blur-md rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 animate-fade-in hover:shadow-2xl transition-all duration-300">
          <h2 className="text-lg sm:text-xl md:text-2xl font-bold text-slate-900 mb-4 sm:mb-5 md:mb-6 pb-3 sm:pb-4 border-b border-slate-200 flex items-center gap-2">
            <Activity className="w-5 h-5 text-blue-600" />
            Recent Activity
          </h2>
          {stats.recent_activity && stats.recent_activity.length > 0 ? (
            <div className="space-y-3 sm:space-y-4">
              {stats.recent_activity.map((activity, index) => (
                <div 
                  key={activity.booking_id || index}
                  className="flex items-center space-x-3 sm:space-x-4 p-3 sm:p-4 bg-gradient-to-r from-slate-50 to-white rounded-lg sm:rounded-xl border border-slate-200 hover:from-blue-50 hover:to-indigo-50 hover:border-blue-300 hover:shadow-md cursor-pointer transition-all duration-200"
                  onClick={() => navigate(`/bookings/${activity.booking_id}`)}
                >
                  <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">
                    <Activity 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-semibold text-slate-900 text-sm sm:text-base truncate">
                      {activity.action}
                    </p>
                    <p className="text-xs sm:text-sm text-slate-600 truncate">
                      {activity.room?.room_number || activity.booking_number}
                    </p>
                  </div>
                  <span className="text-xs sm:text-sm text-slate-400 flex-shrink-0">
                    {formatRelativeTime(new Date(activity.created_at))}
                  </span>
                </div>
              ))}
            </div>
          ) : (
            <EmptyState
              title="No Recent Activity"
              description="Your recent bookings and activities will appear here"
              action={{
                label: 'View All Bookings',
                onClick: () => navigate('/bookings')
              }}
            />
          )}
        </div>

        {}
        <div className="bg-white/90 backdrop-blur-md rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 animate-fade-in hover:shadow-2xl transition-all duration-300" style={{ animationDelay: '0.2s' }}>
          <h2 className="text-lg sm:text-xl md:text-2xl font-bold text-slate-900 mb-4 sm:mb-5 md:mb-6 pb-3 sm:pb-4 border-b border-slate-200 flex items-center gap-2">
            <Calendar className="w-5 h-5 text-purple-600" />
            Upcoming Bookings
          </h2>
          {stats.upcoming_bookings && stats.upcoming_bookings.length > 0 ? (
            <div className="space-y-3 sm:space-y-4">
              {stats.upcoming_bookings.map((booking) => (
                <div 
                  key={booking.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 border border-slate-200 hover:from-purple-50 hover:to-indigo-50 hover:border-purple-300 hover:shadow-md cursor-pointer transition-all duration-200"
                  onClick={() => navigate(`/bookings/${booking.id}`)}
                >
                  <div className="flex-1 min-w-0">
                    <p className="font-semibold text-slate-900 text-sm sm:text-base truncate">
                      Room {booking.room?.room_number || 'N/A'}
                    </p>
                    <p className="text-xs sm:text-sm text-slate-600 mt-1">
                      {formatDate(booking.check_in_date, 'medium')}
                    </p>
                    <p className="text-xs text-slate-500 mt-1 font-medium">
                      {formatCurrency(booking.total_price)}
                    </p>
                  </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 ${
                    booking.status === 'confirmed' 
                      ? 'bg-gradient-to-r from-emerald-50 to-green-50 text-emerald-800 border-emerald-200' 
                      : booking.status === 'pending'
                      ? 'bg-gradient-to-r from-amber-50 to-yellow-50 text-amber-800 border-amber-200'
                      : 'bg-gradient-to-r from-slate-50 to-gray-50 text-slate-700 border-slate-200'
                  }`}>
                    {booking.status.charAt(0).toUpperCase() + booking.status.slice(1).replace('_', ' ')}
                  </span>
                </div>
              ))}
            </div>
          ) : (
            <EmptyState
              title="No Upcoming Bookings"
              description="You don't have any upcoming bookings yet"
              action={{
                label: 'Browse Rooms',
                onClick: () => navigate('/rooms')
              }}
            />
          )}
        </div>

        {}
        <div className="bg-white/90 backdrop-blur-md rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 animate-fade-in hover:shadow-2xl transition-all duration-300" 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-lg sm:text-xl md:text-2xl font-bold text-slate-900 flex items-center gap-2">
              <CreditCard className="w-5 h-5 text-emerald-600" />
              Payment History
            </h2>
            <button
              onClick={() => navigate('/bookings')}
              className="text-xs sm:text-sm text-blue-600 hover:text-blue-700 font-semibold hover:underline transition-colors"
            >
              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-3 sm:space-y-4">
              {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 border border-slate-200 hover:from-emerald-50 hover:to-green-50 hover:border-emerald-300 hover:shadow-md cursor-pointer transition-all duration-200"
                  onClick={() => navigate(`/bookings/${payment.booking_id}`)}
                >
                  <div className="flex items-center space-x-3 sm: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-sm sm: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 Payment History"
              description="Your payment history will appear here"
              action={{
                label: 'View Bookings',
                onClick: () => navigate('/bookings')
              }}
            />
          )}
        </div>

        {}
        <div className="bg-white/90 backdrop-blur-md rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 animate-fade-in hover:shadow-2xl transition-all duration-300" 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-lg sm:text-xl md:text-2xl font-bold text-slate-900 flex items-center gap-2">
              <Monitor className="w-5 h-5 text-indigo-600" />
              Active Sessions
            </h2>
            <button
              onClick={() => navigate('/sessions')}
              className="text-xs sm:text-sm text-blue-600 hover:text-blue-700 font-semibold hover:underline transition-colors"
            >
              Manage →
            </button>
          </div>
          {loadingSessions ? (
            <div className="flex items-center justify-center py-8">
              <Loading text="Loading sessions..." />
            </div>
          ) : sessions && sessions.length > 0 ? (
            <div className="space-y-3 sm:space-y-4">
              {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 border border-slate-200 hover:from-indigo-50 hover:to-purple-50 hover:border-indigo-300 hover:shadow-md transition-all duration-200"
                >
                  <div className="flex items-center space-x-3 sm: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-sm sm: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">
                            • {formatRelativeTime(new Date(session.last_activity))}
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              ))}
              {sessions.length > 3 && (
                <button
                  onClick={() => navigate('/sessions')}
                  className="w-full text-xs sm:text-sm text-blue-600 hover:text-blue-700 font-semibold hover:underline transition-colors pt-2"
                >
                  View all {sessions.length} sessions →
                </button>
              )}
            </div>
          ) : (
            <EmptyState
              title="No Active Sessions"
              description="Your active sessions will appear here"
              action={{
                label: 'View Session Management',
                onClick: () => navigate('/sessions')
              }}
            />
          )}
        </div>
      </div>
    </div>
  );
};

export default DashboardPage;
