import React, { useEffect, useState } from 'react';
import { 
  BarChart3, 
  Hotel, 
  Calendar,
  TrendingUp,
  RefreshCw,
  CreditCard,
  Users,
  CheckCircle
} from 'lucide-react';
import { reportService, ReportData, paymentService, bookingService } from '../../services/api';
import type { Payment } from '../../services/api/paymentService';
import type { Booking } from '../../services/api/bookingService';
import { toast } from 'react-toastify';
import { Loading, EmptyState } from '../../components/common';
import CurrencyIcon from '../../components/common/CurrencyIcon';
import { formatDate } from '../../utils/format';
import { useFormatCurrency } from '../../hooks/useFormatCurrency';
import { useAsync } from '../../hooks/useAsync';
import { useNavigate } from 'react-router-dom';

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 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: any) => {
        toast.error(error.message || 'Unable to load dashboard data');
      }
    }
  );

  useEffect(() => {
    execute();
  }, [dateRange]); 

  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();
  }, []);

  useEffect(() => {
    const fetchBookings = async () => {
      try {
        setLoadingBookings(true);
        const response = await bookingService.getAllBookings({ page: 1, limit: 5 });
        if (response.status === 'success' && response.data?.bookings) {
          setRecentBookings(response.data.bookings);
        }
      } catch (err: any) {
        console.error('Error fetching bookings:', err);
      } finally {
        setLoadingBookings(false);
      }
    };
    fetchBookings();
  }, []);

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

  const getPaymentStatusBadge = (status: string) => {
    const statusConfig: Record<string, { bg: string; text: string; label: string; border: string }> = {
      completed: {
        bg: 'bg-gradient-to-r from-emerald-50 to-green-50',
        text: 'text-emerald-800',
        label: '✅ Paid',
        border: 'border-emerald-200'
      },
      pending: {
        bg: 'bg-gradient-to-r from-amber-50 to-yellow-50',
        text: 'text-amber-800',
        label: '⏳ Pending',
        border: 'border-amber-200'
      },
      failed: {
        bg: 'bg-gradient-to-r from-rose-50 to-red-50',
        text: 'text-rose-800',
        label: '❌ Failed',
        border: 'border-rose-200'
      },
      refunded: {
        bg: 'bg-gradient-to-r from-slate-50 to-gray-50',
        text: 'text-slate-700',
        label: '💰 Refunded',
        border: 'border-slate-200'
      },
    };
    const config = statusConfig[status] || statusConfig.pending;
    return (
      <span className={`px-3 py-1.5 rounded-full text-xs font-semibold border shadow-sm ${config.bg} ${config.text} ${config.border}`}>
        {config.label}
      </span>
    );
  };

  const getBookingStatusBadge = (status: string) => {
    const statusConfig: Record<string, { bg: string; text: string; label: string; border: string }> = {
      pending: {
        bg: 'bg-gradient-to-r from-amber-50 to-yellow-50',
        text: 'text-amber-800',
        label: 'Pending',
        border: 'border-amber-200'
      },
      confirmed: {
        bg: 'bg-gradient-to-r from-blue-50 to-indigo-50',
        text: 'text-blue-800',
        label: 'Confirmed',
        border: 'border-blue-200'
      },
      checked_in: {
        bg: 'bg-gradient-to-r from-emerald-50 to-green-50',
        text: 'text-emerald-800',
        label: 'Checked In',
        border: 'border-emerald-200'
      },
      checked_out: {
        bg: 'bg-gradient-to-r from-slate-50 to-gray-50',
        text: 'text-slate-700',
        label: 'Checked Out',
        border: 'border-slate-200'
      },
      cancelled: {
        bg: 'bg-gradient-to-r from-rose-50 to-red-50',
        text: 'text-rose-800',
        label: '❌ Canceled',
        border: 'border-rose-200'
      },
    };
    const config = statusConfig[status] || statusConfig.pending;
    return (
      <span className={`px-3 py-1.5 rounded-full text-xs font-semibold border shadow-sm ${config.bg} ${config.text} ${config.border}`}>
        {config.label}
      </span>
    );
  };

  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-8 bg-gradient-to-br from-slate-50 via-white to-slate-50 min-h-screen -m-6 p-8">
      {}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-6 animate-fade-in">
        <div>
          <div className="flex items-center gap-3 mb-2">
            <div className="h-1 w-16 bg-gradient-to-r from-blue-400 to-blue-600 rounded-full"></div>
            <h1 className="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-3 text-lg font-light">Hotel operations overview and management</p>
        </div>
        
        {}
        <div className="flex flex-wrap items-center gap-4">
          <div className="flex items-center gap-3">
            <input
              type="date"
              value={dateRange.from}
              onChange={(e) => setDateRange({ ...dateRange, from: e.target.value })}
              className="px-4 py-2.5 bg-white border-2 border-gray-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all duration-200 text-gray-700 font-medium shadow-sm hover:shadow-md"
            />
            <span className="text-slate-500 font-medium">to</span>
            <input
              type="date"
              value={dateRange.to}
              onChange={(e) => setDateRange({ ...dateRange, to: e.target.value })}
              className="px-4 py-2.5 bg-white border-2 border-gray-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all duration-200 text-gray-700 font-medium shadow-sm hover:shadow-md"
            />
          </div>
          <button
            onClick={handleRefresh}
            className="px-5 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 gap-2"
          >
            <RefreshCw className="w-5 h-5" />
            Refresh
          </button>
        </div>
      </div>

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

        {}
        <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 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>
              <p className="text-slate-500 text-xs font-semibold uppercase tracking-wider mb-2">Total Bookings</p>
              <p className="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-4 rounded-2xl shadow-lg">
              <Calendar className="w-7 h-7 text-blue-600" />
            </div>
          </div>
          <div className="flex items-center mt-5 pt-4 border-t border-slate-100">
            <span className="text-slate-500 text-sm">
              {stats?.active_bookings || 0} active bookings
            </span>
          </div>
        </div>

        {}
        <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 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>
              <p className="text-slate-500 text-xs font-semibold uppercase tracking-wider mb-2">Available Rooms</p>
              <p className="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-4 rounded-2xl shadow-lg">
              <Hotel className="w-7 h-7 text-purple-600" />
            </div>
          </div>
          <div className="flex items-center mt-5 pt-4 border-t border-slate-100">
            <span className="text-slate-500 text-sm">
              {stats?.total_rooms || 0} total rooms
            </span>
          </div>
        </div>

        {}
        <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 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>
              <p className="text-slate-500 text-xs font-semibold uppercase tracking-wider mb-2">Pending Payments</p>
              <p className="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-4 rounded-2xl shadow-lg">
              <CreditCard className="w-7 h-7 text-amber-600" />
            </div>
          </div>
          <div className="flex items-center mt-5 pt-4 border-t border-slate-100">
            <span className="text-slate-500 text-sm">
              Require attention
            </span>
          </div>
        </div>
      </div>

      {}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {}
        <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 p-6 animate-fade-in">
          <div className="flex items-center justify-between mb-6 pb-4 border-b border-slate-200">
            <h2 className="text-xl 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-sm text-blue-600 hover:text-blue-700 font-semibold"
            >
              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-4">
              {recentBookings.map((booking) => (
                <div
                  key={booking.id}
                  className="p-4 bg-gradient-to-r from-slate-50 to-white rounded-xl border border-slate-200 hover:shadow-md transition-all duration-200 cursor-pointer"
                  onClick={() => navigate(`/staff/bookings/${booking.id}`)}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-2">
                        <span className="font-bold text-slate-900">{booking.booking_number}</span>
                        {getBookingStatusBadge(booking.status || 'pending')}
                      </div>
                      <p className="text-sm text-slate-600">
                        {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">
                      <p className="font-bold text-emerald-600">{formatCurrency(booking.total_price || 0)}</p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {}
        <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 p-6 animate-fade-in">
          <div className="flex items-center justify-between mb-6 pb-4 border-b border-slate-200">
            <h2 className="text-xl 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-sm text-blue-600 hover:text-blue-700 font-semibold"
            >
              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-4">
              {recentPayments.map((payment) => (
                <div
                  key={payment.id}
                  className="p-4 bg-gradient-to-r from-slate-50 to-white rounded-xl border border-slate-200 hover:shadow-md transition-all duration-200"
                >
                  <div className="flex items-center justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-2">
                        <span className="font-bold text-slate-900 font-mono text-sm">
                          {payment.transaction_id || `PAY-${payment.id}`}
                        </span>
                        {getPaymentStatusBadge(payment.payment_status)}
                      </div>
                      <p className="text-sm text-slate-600">
                        {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">
                      <p className="font-bold text-emerald-600">{formatCurrency(payment.amount || 0)}</p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default StaffDashboardPage;

