import React, { useEffect, useState, useRef } from 'react';
import { 
  Hotel, 
  Calendar,
  TrendingUp,
  RefreshCw,
  CreditCard,
  ClipboardCheck,
  MessageSquare,
  AlertTriangle,
  Users,
  Sparkles,
} from 'lucide-react';
import reportService, { ReportData } from '../../features/analytics/services/reportService';
import paymentService from '../../features/payments/services/paymentService';
import bookingService from '../../features/bookings/services/bookingService';
import type { Payment } from '../../features/payments/services/paymentService';
import type { Booking } from '../../features/bookings/services/bookingService';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import EmptyState from '../../shared/components/EmptyState';
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 { logger } from '../../shared/utils/logger';
import { getPaymentStatusColor } from '../../shared/utils/paymentUtils';
import { getBookingStatusConfig } from '../../shared/utils/bookingUtils';

const StaffDashboardPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const navigate = useNavigate();
  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 [recentBookings, setRecentBookings] = useState<Booking[]>([]);
  const [loadingPayments, setLoadingPayments] = useState(false);
  const [loadingBookings, setLoadingBookings] = useState(false);
  const paymentsAbortRef = useRef<AbortController | null>(null);
  const bookingsAbortRef = useRef<AbortController | null>(null);
  
  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 (bookingsAbortRef.current) {
      bookingsAbortRef.current.abort();
    }

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

    const fetchBookings = async () => {
      try {
        setLoadingBookings(true);
        const response = await bookingService.getAllBookings({ page: 1, limit: 5 });
        if ((response.status === 'success' || response.success) && response.data?.bookings) {
          setRecentBookings(response.data.bookings);
        } else {
          // Clear data if response is not successful
          setRecentBookings([]);
        }
      } catch (err: unknown) {
        // Handle AbortError silently
        if (err && typeof err === 'object' && 'name' in err && err.name === 'AbortError') {
          return;
        }
        // Clear data when API connection fails
        setRecentBookings([]);
        logger.error('Error fetching bookings', err);
      } finally {
        setLoadingBookings(false);
      }
    };
    fetchBookings();

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

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

  const getPaymentStatusBadge = (status: string) => {
    const colorClasses = getPaymentStatusColor(status);
    const labels: Record<string, string> = {
      completed: '✅ Paid',
      paid: '✅ Paid',
      pending: '⏳ Pending',
      failed: '❌ Failed',
      refunded: '💰 Refunded',
    };
    const label = labels[status] || status.charAt(0).toUpperCase() + status.slice(1);
    return (
      <span className={`px-3 py-1.5 rounded-full text-xs font-semibold border shadow-sm ${colorClasses}`}>
        {label}
      </span>
    );
  };

  const getBookingStatusBadge = (status: string) => {
    const config = getBookingStatusConfig(status);
    return (
      <span className={`px-3 py-1.5 rounded-full text-xs font-semibold border shadow-sm ${config.color}`}>
        {config.text}
      </span>
    );
  };

  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="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4 sm:gap-6 mb-6 sm:mb-8 md:mb-10 animate-fade-in">
        <div className="w-full lg:w-auto">
          <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">
              Staff Dashboard
            </h1>
          </div>
          <p className="text-slate-600 mt-2 sm:mt-3 text-sm sm:text-base md:text-lg font-light">Hotel operations overview and management</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-blue-400 focus:ring-4 focus:ring-blue-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-blue-400 focus:ring-4 focus:ring-blue-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md text-sm sm:text-base"
            />
          </div>
          <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-blue-600 to-blue-700 text-white rounded-xl font-semibold shadow-lg hover:shadow-xl hover:from-blue-700 hover:to-blue-800 transition-all duration-200 flex items-center justify-center gap-2 text-xs sm:text-sm disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <RefreshCw className={`w-3 h-3 sm:w-4 sm:h-4 ${loading ? 'animate-spin' : ''}`} />
            Refresh
          </button>
        </div>
      </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 animate-fade-in" style={{ animationDelay: '0.1s' }}>
        {}
        <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">
          <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 lg:text-3xl 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">
              <TrendingUp className="w-5 h-5 sm:w-6 sm:h-6 md:w-7 md:h-7 text-emerald-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_payments || 0} completed payments
            </span>
          </div>
        </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-blue-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">
            <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 lg:text-3xl 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?.active_bookings || 0} active bookings
            </span>
          </div>
        </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">
            <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 lg:text-3xl 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?.total_rooms || 0} total rooms
            </span>
          </div>
        </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">
            <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">Pending Payments</p>
              <p className="text-lg sm:text-xl md:text-2xl lg:text-3xl font-bold bg-gradient-to-r from-amber-600 to-amber-700 bg-clip-text text-transparent">
                {stats?.pending_payments || 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">
              <CreditCard 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">
              Require attention
            </span>
          </div>
        </div>
      </div>

      {/* Quick Actions */}
      <div className="mb-6 sm:mb-8 md:mb-10 animate-fade-in" style={{ animationDelay: '0.5s' }}>
        <h2 className="text-lg sm:text-xl font-bold text-slate-900 mb-4 flex items-center gap-2">
          <Sparkles className="w-5 h-5 text-amber-500" />
          Quick Actions
        </h2>
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3 sm:gap-4">
          <button
            onClick={() => navigate('/staff/bookings')}
            className="flex flex-col items-center gap-2 p-4 bg-white/90 backdrop-blur-md rounded-xl border border-slate-200 hover:border-blue-300 hover:bg-blue-50 hover:shadow-lg transition-all duration-200"
          >
            <div className="p-3 bg-blue-100 rounded-xl">
              <ClipboardCheck className="w-6 h-6 text-blue-600" />
            </div>
            <span className="text-sm font-medium text-slate-700">Check-In/Out</span>
          </button>
          
          <button
            onClick={() => navigate('/staff/guest-profiles')}
            className="flex flex-col items-center gap-2 p-4 bg-white/90 backdrop-blur-md rounded-xl border border-slate-200 hover:border-purple-300 hover:bg-purple-50 hover:shadow-lg transition-all duration-200"
          >
            <div className="p-3 bg-purple-100 rounded-xl">
              <Users className="w-6 h-6 text-purple-600" />
            </div>
            <span className="text-sm font-medium text-slate-700">Guest Profiles</span>
          </button>
          
          <button
            onClick={() => navigate('/staff/guest-requests')}
            className="flex flex-col items-center gap-2 p-4 bg-white/90 backdrop-blur-md rounded-xl border border-slate-200 hover:border-green-300 hover:bg-green-50 hover:shadow-lg transition-all duration-200"
          >
            <div className="p-3 bg-green-100 rounded-xl">
              <MessageSquare className="w-6 h-6 text-green-600" />
            </div>
            <span className="text-sm font-medium text-slate-700">Guest Requests</span>
          </button>
          
          <button
            onClick={() => navigate('/staff/advanced-rooms')}
            className="flex flex-col items-center gap-2 p-4 bg-white/90 backdrop-blur-md rounded-xl border border-slate-200 hover:border-amber-300 hover:bg-amber-50 hover:shadow-lg transition-all duration-200"
          >
            <div className="p-3 bg-amber-100 rounded-xl">
              <Hotel className="w-6 h-6 text-amber-600" />
            </div>
            <span className="text-sm font-medium text-slate-700">Room Status</span>
          </button>
          
          <button
            onClick={() => navigate('/staff/incidents-complaints')}
            className="flex flex-col items-center gap-2 p-4 bg-white/90 backdrop-blur-md rounded-xl border border-slate-200 hover:border-rose-300 hover:bg-rose-50 hover:shadow-lg transition-all duration-200"
          >
            <div className="p-3 bg-rose-100 rounded-xl">
              <AlertTriangle className="w-6 h-6 text-rose-600" />
            </div>
            <span className="text-sm font-medium text-slate-700">Complaints</span>
          </button>
          
          <button
            onClick={() => navigate('/staff/chats')}
            className="flex flex-col items-center gap-2 p-4 bg-white/90 backdrop-blur-md rounded-xl border border-slate-200 hover:border-cyan-300 hover:bg-cyan-50 hover:shadow-lg transition-all duration-200"
          >
            <div className="p-3 bg-cyan-100 rounded-xl">
              <MessageSquare className="w-6 h-6 text-cyan-600" />
            </div>
            <span className="text-sm font-medium text-slate-700">Live Chat</span>
          </button>
        </div>
      </div>

      {}
      <div className="grid grid-cols-1 lg:grid-cols-2 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">
          <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">
              <Calendar className="w-5 h-5 text-blue-600" />
              Recent Bookings
            </h2>
            <button
              onClick={() => navigate('/staff/bookings')}
              className="text-xs sm:text-sm text-blue-600 hover:text-blue-700 font-semibold hover:underline transition-colors"
            >
              View All →
            </button>
          </div>
          {loadingBookings ? (
            <Loading text="Loading bookings..." />
          ) : recentBookings.length === 0 ? (
            <EmptyState title="No bookings found" description="No recent bookings to display" />
          ) : (
            <div className="space-y-3 sm:space-y-4">
              {recentBookings.map((booking) => (
                <div
                  key={booking.id}
                  className="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-lg transition-all duration-200 cursor-pointer"
                  onClick={() => navigate(`/staff/bookings/${booking.id}`)}
                >
                  <div className="flex items-center justify-between gap-3 sm:gap-4">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 sm:gap-3 mb-2 flex-wrap">
                        <span className="font-bold text-slate-900 text-sm sm:text-base truncate">{booking.booking_number}</span>
                        {getBookingStatusBadge(booking.status || 'pending')}
                      </div>
                      <p className="text-xs sm:text-sm text-slate-600 truncate">
                        {booking.user?.name || 'Guest'} • Room {booking.room?.room_number || 'N/A'}
                      </p>
                      <p className="text-xs text-slate-500 mt-1">
                        {booking.check_in_date && formatDate(booking.check_in_date)} - {booking.check_out_date && formatDate(booking.check_out_date)}
                      </p>
                    </div>
                    <div className="text-right flex-shrink-0">
                      <p className="font-bold text-emerald-600 text-sm sm:text-base">{formatCurrency(booking.total_price || 0)}</p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </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">
          <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" />
              Recent Payments
            </h2>
            <button
              onClick={() => navigate('/staff/payments')}
              className="text-xs sm:text-sm text-blue-600 hover:text-blue-700 font-semibold hover:underline transition-colors"
            >
              View All →
            </button>
          </div>
          {loadingPayments ? (
            <Loading text="Loading payments..." />
          ) : recentPayments.length === 0 ? (
            <EmptyState title="No payments found" description="No recent payments to display" />
          ) : (
            <div className="space-y-3 sm:space-y-4">
              {recentPayments.map((payment) => (
                <div
                  key={payment.id}
                  className="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-lg transition-all duration-200"
                >
                  <div className="flex items-center justify-between gap-3 sm:gap-4">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 sm:gap-3 mb-2 flex-wrap">
                        <span className="font-bold text-slate-900 font-mono text-xs sm:text-sm truncate">
                          {payment.transaction_id || `PAY-${payment.id}`}
                        </span>
                        {getPaymentStatusBadge(payment.payment_status)}
                      </div>
                      <p className="text-xs sm:text-sm text-slate-600 truncate">
                        {payment.booking?.booking_number || 'N/A'} • {payment.payment_method || 'N/A'}
                      </p>
                      <p className="text-xs text-slate-500 mt-1">
                        {payment.payment_date && formatDate(payment.payment_date)}
                      </p>
                    </div>
                    <div className="text-right flex-shrink-0">
                      <p className="font-bold text-emerald-600 text-sm sm:text-base">{formatCurrency(payment.amount || 0)}</p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default StaffDashboardPage;

