import React, { useState, useEffect } from 'react';
import { 
  TrendingUp, 
  Hotel, 
  Calendar,
  Activity,
  TrendingDown,
  CreditCard,
} from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import dashboardService, { CustomerDashboardStats } from '../../services/api/dashboardService';
import { paymentService } from '../../services/api';
import type { Payment } from '../../services/api/paymentService';
import { toast } from 'react-toastify';
import { formatDate, formatRelativeTime } from '../../utils/format';
import { useFormatCurrency } from '../../hooks/useFormatCurrency';
import { Loading, EmptyState } from '../../components/common';
import CurrencyIcon from '../../components/common/CurrencyIcon';
import { useAsync } from '../../hooks/useAsync';

const DashboardPage: React.FC = () => {
  const navigate = useNavigate();
  const { formatCurrency } = useFormatCurrency();
  const [recentPayments, setRecentPayments] = useState<Payment[]>([]);
  const [loadingPayments, setLoadingPayments] = 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: any) => {
        toast.error(error.message || 'Unable to load dashboard data');
      }
    }
  );

  useEffect(() => {
    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);
        }
      } catch (err: any) {
        console.error('Error fetching payments:', err);
      } finally {
        setLoadingPayments(false);
      }
    };
    fetchPayments();
  }, []);

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

  const getPaymentStatusColor = (status: string) => {
    switch (status) {
      case 'completed':
        return 'bg-green-100 text-green-800';
      case 'pending':
        return 'bg-yellow-100 text-yellow-800';
      case 'failed':
        return 'bg-red-100 text-red-800';
      case 'refunded':
        return 'bg-gray-100 text-gray-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  const getPaymentMethodLabel = (method: string) => {
    switch (method) {
      case 'stripe':
      case 'credit_card':
        return 'Card';
      case 'paypal':
        return 'PayPal';
      case 'bank_transfer':
        return 'Bank Transfer';
      case 'cash':
        return 'Cash';
      default:
        return method;
    }
  };

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

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

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="mb-10 animate-fade-in">
        <h1 className="enterprise-section-title mb-2">
          Dashboard
        </h1>
        <p className="enterprise-section-subtitle">
          Overview of your activity and bookings
        </p>
      </div>

      {}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-10">
        {}
        <div className="enterprise-stat-card border-l-4 border-blue-500 animate-slide-up" style={{ animationDelay: '0.1s' }}>
          <div className="flex items-center justify-between mb-4">
            <div className="p-3 bg-blue-100 rounded-lg">
              <Calendar className="w-6 h-6 text-blue-600" />
            </div>
            {stats.booking_change_percentage !== 0 && (
              <span className={`text-sm font-medium flex items-center gap-1 ${
                stats.booking_change_percentage > 0 ? 'text-green-600' : 'text-red-600'
              }`}>
                {stats.booking_change_percentage > 0 ? (
                  <TrendingUp className="w-4 h-4" />
                ) : (
                  <TrendingDown className="w-4 h-4" />
                )}
                {Math.abs(stats.booking_change_percentage).toFixed(1)}%
              </span>
            )}
          </div>
          <h3 className="text-gray-500 text-sm font-medium mb-1">
            Total Bookings
          </h3>
          <p className="text-3xl font-bold text-gray-800">
            {stats.total_bookings}
          </p>
        </div>

        {}
        <div className="enterprise-stat-card border-l-4 border-green-500 animate-slide-up" style={{ animationDelay: '0.2s' }}>
          <div className="flex items-center justify-between mb-4">
            <div className="p-3 bg-green-100 rounded-lg">
              <CurrencyIcon className="text-green-600" size={24} />
            </div>
            {stats.spending_change_percentage !== 0 && (
              <span className={`text-sm font-medium flex items-center gap-1 ${
                stats.spending_change_percentage > 0 ? 'text-green-600' : 'text-red-600'
              }`}>
                {stats.spending_change_percentage > 0 ? (
                  <TrendingUp className="w-4 h-4" />
                ) : (
                  <TrendingDown className="w-4 h-4" />
                )}
                {Math.abs(stats.spending_change_percentage).toFixed(1)}%
              </span>
            )}
          </div>
          <h3 className="text-gray-500 text-sm font-medium mb-1">
            Total Spending
          </h3>
          <p className="text-3xl font-bold text-gray-800">
            {formatCurrency(stats.total_spending)}
          </p>
        </div>

        {}
        <div className="enterprise-stat-card border-l-4 border-purple-500 animate-slide-up" style={{ animationDelay: '0.3s' }}>
          <div className="flex items-center justify-between mb-4">
            <div className="p-3 bg-purple-100 rounded-lg">
              <Hotel className="w-6 h-6 text-purple-600" />
            </div>
            {stats.currently_staying > 0 && (
              <span className="text-sm text-green-600 font-medium">
                Active
              </span>
            )}
          </div>
          <h3 className="text-gray-500 text-sm font-medium mb-1">
            Currently Staying
          </h3>
          <p className="text-3xl font-bold text-gray-800">
            {stats.currently_staying}
          </p>
        </div>

        {}
        <div className="enterprise-stat-card border-l-4 border-orange-500 animate-slide-up" style={{ animationDelay: '0.4s' }}>
          <div className="flex items-center justify-between mb-4">
            <div className="p-3 bg-orange-100 rounded-lg">
              <TrendingUp className="w-6 h-6 text-orange-600" />
            </div>
          </div>
          <h3 className="text-gray-500 text-sm font-medium mb-1">
            Upcoming Bookings
          </h3>
          <p className="text-3xl font-bold text-gray-800">
            {stats.upcoming_bookings.length}
          </p>
        </div>
      </div>

      {}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {}
        <div className="enterprise-card p-6 animate-fade-in">
          <h2 className="text-xl font-bold text-gray-900 mb-6 pb-3 border-b border-gray-200">
            Recent Activity
          </h2>
          {stats.recent_activity && stats.recent_activity.length > 0 ? (
            <div className="space-y-4">
              {stats.recent_activity.map((activity, index) => (
                <div 
                  key={activity.booking_id || index}
                  className="flex items-center space-x-4 pb-4 border-b border-gray-200 last:border-0 hover:bg-gray-50 -mx-2 px-2 py-1 rounded cursor-pointer transition-colors"
                  onClick={() => navigate(`/bookings/${activity.booking_id}`)}
                >
                  <div className="p-2 bg-blue-100 rounded-lg">
                    <Activity className="w-5 h-5 text-blue-600" />
                  </div>
                  <div className="flex-1">
                    <p className="font-medium text-gray-800">
                      {activity.action}
                    </p>
                    <p className="text-sm text-gray-500">
                      {activity.room?.room_number || activity.booking_number}
                    </p>
                  </div>
                  <span className="text-sm text-gray-400">
                    {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="enterprise-card p-6 animate-fade-in" style={{ animationDelay: '0.2s' }}>
          <h2 className="text-xl font-bold text-gray-900 mb-6 pb-3 border-b border-gray-200">
            Upcoming Bookings
          </h2>
          {stats.upcoming_bookings && stats.upcoming_bookings.length > 0 ? (
            <div className="space-y-4">
              {stats.upcoming_bookings.map((booking) => (
                <div 
                  key={booking.id}
                  className="flex items-center justify-between pb-4 border-b border-gray-200 last:border-0 hover:bg-gray-50 -mx-2 px-2 py-1 rounded cursor-pointer transition-colors"
                  onClick={() => navigate(`/bookings/${booking.id}`)}
                >
                  <div>
                    <p className="font-medium text-gray-800">
                      Room {booking.room?.room_number || 'N/A'}
                    </p>
                    <p className="text-sm text-gray-500">
                      {formatDate(booking.check_in_date, 'medium')}
                    </p>
                    <p className="text-xs text-gray-400 mt-1">
                      {formatCurrency(booking.total_price)}
                    </p>
                  </div>
                  <span className={`enterprise-badge ${
                    booking.status === 'confirmed' 
                      ? 'bg-green-100 text-green-800 shadow-sm shadow-green-500/20' 
                      : booking.status === 'pending'
                      ? 'bg-yellow-100 text-yellow-800 shadow-sm shadow-yellow-500/20'
                      : 'bg-gray-100 text-gray-800 shadow-sm'
                  }`}>
                    {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="enterprise-card p-6 animate-fade-in" style={{ animationDelay: '0.3s' }}>
          <div className="flex items-center justify-between mb-6 pb-3 border-b border-gray-200">
            <h2 className="text-xl font-bold text-gray-900">
              Payment History
            </h2>
            <button
              onClick={() => navigate('/bookings')}
              className="text-sm text-blue-600 hover:text-blue-700 font-medium"
            >
              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-4">
              {recentPayments.map((payment) => (
                <div 
                  key={payment.id}
                  className="flex items-center justify-between pb-4 border-b border-gray-200 last:border-0 hover:bg-gray-50 -mx-2 px-2 py-1 rounded cursor-pointer transition-colors"
                  onClick={() => navigate(`/bookings/${payment.booking_id}`)}
                >
                  <div className="flex items-center space-x-3 flex-1">
                    <div className="p-2 bg-blue-100 rounded-lg">
                      <CreditCard className="w-5 h-5 text-blue-600" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-medium text-gray-800 truncate">
                        {formatCurrency(payment.amount)}
                      </p>
                      <div className="flex items-center gap-2 mt-1">
                        <p className="text-sm text-gray-500">
                          {getPaymentMethodLabel(payment.payment_method)}
                        </p>
                        {payment.payment_date && (
                          <span className="text-xs text-gray-400">
                            • {formatDate(payment.payment_date, 'short')}
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                  <span className={`enterprise-badge text-xs ${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>
    </div>
  );
};

export default DashboardPage;
