import React, { useState, useEffect, useRef } from 'react';
import { Users, Calendar, Building2, ArrowRight } from 'lucide-react';
import groupBookingService, { GroupBooking } from '../../features/bookings/services/groupBookingService';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import { useFormatCurrency } from '../../features/payments/hooks/useFormatCurrency';
import { formatDate } from '../../shared/utils/format';
import CreateGroupBookingModal from '../../features/hotel_services/components/CreateGroupBookingModal';
import { useNavigate } from 'react-router-dom';

const GroupBookingPage: React.FC = () => {
  const navigate = useNavigate();
  const { formatCurrency } = useFormatCurrency();
  const [groupBookings, setGroupBookings] = useState<GroupBooking[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const abortControllerRef = useRef<AbortController | null>(null);

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

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

    fetchGroupBookings();

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

  const fetchGroupBookings = async () => {
    try {
      setLoading(true);
      const response = await groupBookingService.getMyGroupBookings();
      setGroupBookings(response.data.group_bookings);
    } catch (error: unknown) {
      const isAbortError = (e: unknown): boolean => {
        if (typeof e === 'object' && e !== null) {
          const err = e as { name?: string; code?: string };
          return err.name === 'AbortError' || err.code === 'ERR_CANCELED';
        }
        return false;
      };
      if (isAbortError(error)) {
        return;
      }
      toast.error(getUserFriendlyError(error) || 'Unable to load group bookings');
    } finally {
      setLoading(false);
    }
  };

  const getStatusBadge = (status: string) => {
    const badges: Record<string, { bg: string; text: string; label: string }> = {
      draft: { bg: 'bg-gray-100', text: 'text-gray-700', label: 'Draft' },
      pending: { bg: 'bg-yellow-100', text: 'text-yellow-800', label: 'Pending' },
      confirmed: { bg: 'bg-blue-100', text: 'text-blue-800', label: 'Confirmed' },
      partially_confirmed: { bg: 'bg-purple-100', text: 'text-purple-800', label: 'Partially Confirmed' },
      checked_in: { bg: 'bg-green-100', text: 'text-green-800', label: 'Checked In' },
      checked_out: { bg: 'bg-gray-100', text: 'text-gray-700', label: 'Checked Out' },
      cancelled: { bg: 'bg-red-100', text: 'text-red-800', label: 'Cancelled' },
    };
    const badge = badges[status] || badges.draft;
    return (
      <span className={`px-3 py-1 rounded-full text-xs font-semibold ${badge.bg} ${badge.text}`}>
        {badge.label}
      </span>
    );
  };

  if (loading) {
    return <Loading />;
  }

  return (
    <div className="container mx-auto px-4 py-8 max-w-7xl">
      <div className="mb-8">
        <div className="flex justify-between items-start mb-4">
          <div>
            <h1 className="text-3xl font-bold text-gray-900 mb-2">Group Bookings</h1>
            <p className="text-gray-600">
              Manage your group bookings and coordinate room blocks for your group
            </p>
          </div>
          <button
            onClick={() => setShowCreateModal(true)}
            className="flex items-center gap-2 px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 shadow-lg"
          >
            <Users className="w-5 h-5" />
            Create Group Booking
          </button>
        </div>
      </div>

      {groupBookings.length === 0 ? (
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-12 text-center">
          <Users className="w-16 h-16 text-gray-400 mx-auto mb-4" />
          <h3 className="text-xl font-semibold text-gray-900 mb-2">No Group Bookings Yet</h3>
          <p className="text-gray-600 mb-6">
            Create your first group booking to block multiple rooms for your group
          </p>
          <button
            onClick={() => setShowCreateModal(true)}
            className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            Create Group Booking
          </button>
        </div>
      ) : (
        <div className="grid gap-6">
          {groupBookings.map((booking) => (
            <div
              key={booking.id}
              className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 hover:shadow-md transition-shadow cursor-pointer"
              onClick={() => navigate(`/admin/group-bookings?view=${booking.id}`)}
            >
              <div className="flex justify-between items-start mb-4">
                <div>
                  <h3 className="text-xl font-semibold text-gray-900 mb-1">
                    {booking.group_name || booking.group_booking_number}
                  </h3>
                  <p className="text-sm text-gray-500">Booking #{booking.group_booking_number}</p>
                  {booking.group_type && (
                    <span className="inline-block mt-2 px-3 py-1 bg-gray-100 text-gray-700 rounded-full text-xs">
                      {booking.group_type}
                    </span>
                  )}
                </div>
                {getStatusBadge(booking.status)}
              </div>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                <div className="flex items-center gap-3">
                  <Calendar className="w-5 h-5 text-gray-400" />
                  <div>
                    <p className="text-sm text-gray-500">Check-in</p>
                    <p className="font-medium text-gray-900">
                      {formatDate(booking.check_in_date, 'short')}
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <Calendar className="w-5 h-5 text-gray-400" />
                  <div>
                    <p className="text-sm text-gray-500">Check-out</p>
                    <p className="font-medium text-gray-900">
                      {formatDate(booking.check_out_date, 'short')}
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <Building2 className="w-5 h-5 text-gray-400" />
                  <div>
                    <p className="text-sm text-gray-500">Rooms / Guests</p>
                    <p className="font-medium text-gray-900">
                      {booking.total_rooms} rooms • {booking.total_guests} guests
                    </p>
                  </div>
                </div>
              </div>

              <div className="flex justify-between items-center pt-4 border-t border-gray-200">
                <div>
                  <p className="text-sm text-gray-500">Total Price</p>
                  <p className="text-2xl font-bold text-gray-900">
                    {formatCurrency(booking.total_price)}
                  </p>
                  {booking.discount_amount > 0 && (
                    <p className="text-sm text-green-600">
                      Saved {formatCurrency(booking.discount_amount)} with group discount
                    </p>
                  )}
                </div>
                <div className="flex items-center gap-2 text-blue-600">
                  <span className="text-sm font-medium">View Details</span>
                  <ArrowRight className="w-4 h-4" />
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Create Group Booking Modal */}
      <CreateGroupBookingModal
        isOpen={showCreateModal}
        onClose={() => setShowCreateModal(false)}
        onSuccess={() => {
          setShowCreateModal(false);
          fetchGroupBookings();
        }}
      />
    </div>
  );
};

export default GroupBookingPage;

