import React, { useEffect, useState } from 'react';
import { Search, Eye, XCircle, CheckCircle, Loader2, Users, Plus } from 'lucide-react';
import { groupBookingService, GroupBooking } from '../../services/api';
import { toast } from 'react-toastify';
import Loading from '../../components/common/Loading';
import Pagination from '../../components/common/Pagination';
import { useFormatCurrency } from '../../hooks/useFormatCurrency';
import { formatDate } from '../../utils/format';
import CreateGroupBookingModal from '../../components/shared/CreateGroupBookingModal';

const GroupBookingManagementPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const [groupBookings, setGroupBookings] = useState<GroupBooking[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedBooking, setSelectedBooking] = useState<GroupBooking | null>(null);
  const [showDetailModal, setShowDetailModal] = useState(false);
  const [confirmingBookingId, setConfirmingBookingId] = useState<number | null>(null);
  const [cancellingBookingId, setCancellingBookingId] = useState<number | null>(null);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [filters, setFilters] = useState({
    search: '',
    status: '',
  });
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const itemsPerPage = 10;

  useEffect(() => {
    setCurrentPage(1);
  }, [filters]);

  useEffect(() => {
    fetchGroupBookings();
  }, [filters, currentPage]);

  const fetchGroupBookings = async () => {
    try {
      setLoading(true);
      const response = await groupBookingService.getGroupBookings({
        ...filters,
        page: currentPage,
        limit: itemsPerPage,
      });
      setGroupBookings(response.data.group_bookings);
      if (response.data.pagination) {
        setTotalPages(response.data.pagination.totalPages);
      }
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Unable to load group bookings');
    } finally {
      setLoading(false);
    }
  };

  const handleConfirmBooking = async (id: number) => {
    if (!window.confirm('Are you sure you want to confirm this group booking?')) return;
    
    try {
      setConfirmingBookingId(id);
      await groupBookingService.confirmGroupBooking(id);
      toast.success('Group booking confirmed successfully');
      await fetchGroupBookings();
      if (selectedBooking?.id === id) {
        const updated = await groupBookingService.getGroupBooking(id);
        setSelectedBooking(updated.data.group_booking);
      }
    } catch (error: any) {
      toast.error(error.response?.data?.detail || error.response?.data?.message || 'Unable to confirm booking');
    } finally {
      setConfirmingBookingId(null);
    }
  };

  const handleCancelBooking = async (id: number) => {
    if (!window.confirm('Are you sure you want to cancel this group booking?')) return;
    
    try {
      setCancellingBookingId(id);
      await groupBookingService.cancelGroupBooking(id, 'Cancelled by admin');
      toast.success('Group booking cancelled successfully');
      await fetchGroupBookings();
      if (selectedBooking?.id === id) {
        setShowDetailModal(false);
      }
    } catch (error: any) {
      toast.error(error.response?.data?.detail || error.response?.data?.message || 'Unable to cancel booking');
    } finally {
      setCancellingBookingId(null);
    }
  };

  const handleViewDetails = async (booking: GroupBooking) => {
    try {
      const response = await groupBookingService.getGroupBooking(booking.id);
      setSelectedBooking(response.data.group_booking);
      setShowDetailModal(true);
    } catch (error: any) {
      toast.error('Unable to load booking details');
    }
  };

  const getStatusBadge = (status: string) => {
    const badges: Record<string, { bg: string; text: string; label: string; border: string }> = {
      draft: { 
        bg: 'bg-gradient-to-r from-gray-50 to-slate-50', 
        text: 'text-gray-700', 
        label: 'Draft',
        border: 'border-gray-200'
      },
      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'
      },
      partially_confirmed: { 
        bg: 'bg-gradient-to-r from-purple-50 to-violet-50', 
        text: 'text-purple-800', 
        label: 'Partially Confirmed',
        border: 'border-purple-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: 'Cancelled',
        border: 'border-rose-200'
      },
    };
    const badge = badges[status] || badges.draft;
    return (
      <span className={`px-3 py-1 rounded-full text-xs font-semibold border ${badge.bg} ${badge.text} ${badge.border}`}>
        {badge.label}
      </span>
    );
  };

  if (loading && groupBookings.length === 0) {
    return <Loading />;
  }

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

      {/* Filters */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-6">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
            <input
              type="text"
              placeholder="Search by booking number, group name..."
              value={filters.search}
              onChange={(e) => setFilters({ ...filters, search: e.target.value })}
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>
          <select
            value={filters.status}
            onChange={(e) => setFilters({ ...filters, status: e.target.value })}
            className="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          >
            <option value="">All Statuses</option>
            <option value="draft">Draft</option>
            <option value="pending">Pending</option>
            <option value="confirmed">Confirmed</option>
            <option value="partially_confirmed">Partially Confirmed</option>
            <option value="checked_in">Checked In</option>
            <option value="checked_out">Checked Out</option>
            <option value="cancelled">Cancelled</option>
          </select>
        </div>
      </div>

      {/* Group Bookings Table */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50 border-b border-gray-200">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Booking Number
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Group Name
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Coordinator
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Dates
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Rooms / Guests
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Total Price
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Status
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {groupBookings.length === 0 ? (
                <tr>
                  <td colSpan={8} className="px-6 py-12 text-center text-gray-500">
                    No group bookings found
                  </td>
                </tr>
              ) : (
                groupBookings.map((booking) => (
                  <tr key={booking.id} className="hover:bg-gray-50 transition-colors">
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm font-medium text-gray-900">
                        {booking.group_booking_number}
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-gray-900">
                        {booking.group_name || 'N/A'}
                      </div>
                      {booking.group_type && (
                        <div className="text-xs text-gray-500">{booking.group_type}</div>
                      )}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-gray-900">{booking.coordinator.name}</div>
                      <div className="text-xs text-gray-500">{booking.coordinator.email}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-gray-900">
                        {formatDate(booking.check_in_date, 'short')}
                      </div>
                      <div className="text-xs text-gray-500">
                        to {formatDate(booking.check_out_date, 'short')}
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center gap-2 text-sm text-gray-900">
                        <Users className="w-4 h-4" />
                        {booking.total_rooms} rooms
                      </div>
                      <div className="text-xs text-gray-500">{booking.total_guests} guests</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm font-medium text-gray-900">
                        {formatCurrency(booking.total_price)}
                      </div>
                      {booking.discount_amount > 0 && (
                        <div className="text-xs text-green-600">
                          -{formatCurrency(booking.discount_amount)} discount
                        </div>
                      )}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      {getStatusBadge(booking.status)}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                      <div className="flex items-center gap-2">
                        <button
                          onClick={() => handleViewDetails(booking)}
                          className="text-blue-600 hover:text-blue-900 flex items-center gap-1"
                        >
                          <Eye className="w-4 h-4" />
                          View
                        </button>
                        {booking.status === 'draft' || booking.status === 'pending' ? (
                          <button
                            onClick={() => handleConfirmBooking(booking.id)}
                            disabled={confirmingBookingId === booking.id}
                            className="text-green-600 hover:text-green-900 flex items-center gap-1 disabled:opacity-50"
                          >
                            {confirmingBookingId === booking.id ? (
                              <Loader2 className="w-4 h-4 animate-spin" />
                            ) : (
                              <CheckCircle className="w-4 h-4" />
                            )}
                            Confirm
                          </button>
                        ) : null}
                        {booking.status !== 'cancelled' && booking.status !== 'checked_out' ? (
                          <button
                            onClick={() => handleCancelBooking(booking.id)}
                            disabled={cancellingBookingId === booking.id}
                            className="text-red-600 hover:text-red-900 flex items-center gap-1 disabled:opacity-50"
                          >
                            {cancellingBookingId === booking.id ? (
                              <Loader2 className="w-4 h-4 animate-spin" />
                            ) : (
                              <XCircle className="w-4 h-4" />
                            )}
                            Cancel
                          </button>
                        ) : null}
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {totalPages > 1 && (
          <div className="px-6 py-4 border-t border-gray-200">
            <Pagination
              currentPage={currentPage}
              totalPages={totalPages}
              onPageChange={setCurrentPage}
            />
          </div>
        )}
      </div>

      {/* Detail Modal */}
      {showDetailModal && selectedBooking && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-y-auto">
            <div className="p-6 border-b border-gray-200">
              <div className="flex justify-between items-start">
                <div>
                  <h2 className="text-2xl font-bold text-gray-900">
                    {selectedBooking.group_booking_number}
                  </h2>
                  <p className="text-gray-600 mt-1">{selectedBooking.group_name || 'No group name'}</p>
                </div>
                <button
                  onClick={() => setShowDetailModal(false)}
                  className="text-gray-400 hover:text-gray-600"
                >
                  <XCircle className="w-6 h-6" />
                </button>
              </div>
            </div>

            <div className="p-6 space-y-6">
              {/* Booking Info */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <h3 className="text-sm font-medium text-gray-500 mb-2">Coordinator</h3>
                  <p className="text-gray-900">{selectedBooking.coordinator.name}</p>
                  <p className="text-sm text-gray-600">{selectedBooking.coordinator.email}</p>
                  {selectedBooking.coordinator.phone && (
                    <p className="text-sm text-gray-600">{selectedBooking.coordinator.phone}</p>
                  )}
                </div>
                <div>
                  <h3 className="text-sm font-medium text-gray-500 mb-2">Status</h3>
                  {getStatusBadge(selectedBooking.status)}
                </div>
                <div>
                  <h3 className="text-sm font-medium text-gray-500 mb-2">Check-in</h3>
                  <p className="text-gray-900">{formatDate(selectedBooking.check_in_date, 'short')}</p>
                </div>
                <div>
                  <h3 className="text-sm font-medium text-gray-500 mb-2">Check-out</h3>
                  <p className="text-gray-900">{formatDate(selectedBooking.check_out_date, 'short')}</p>
                </div>
              </div>

              {/* Room Blocks */}
              {selectedBooking.room_blocks && selectedBooking.room_blocks.length > 0 && (
                <div>
                  <h3 className="text-lg font-semibold text-gray-900 mb-3">Room Blocks</h3>
                  <div className="space-y-3">
                    {selectedBooking.room_blocks.map((block) => (
                      <div key={block.id} className="border border-gray-200 rounded-lg p-4">
                        <div className="flex justify-between items-start">
                          <div>
                            <p className="font-medium text-gray-900">
                              {block.room_type?.name || `Room Type ${block.room_type_id}`}
                            </p>
                            <p className="text-sm text-gray-600">
                              {block.rooms_blocked} rooms blocked • {block.rooms_confirmed} confirmed • {block.rooms_available} available
                            </p>
                          </div>
                          <div className="text-right">
                            <p className="font-medium text-gray-900">
                              {formatCurrency(block.rate_per_room)}/room
                            </p>
                            <p className="text-sm text-gray-600">
                              Total: {formatCurrency(block.total_block_price)}
                            </p>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Members */}
              {selectedBooking.members && selectedBooking.members.length > 0 && (
                <div>
                  <h3 className="text-lg font-semibold text-gray-900 mb-3">
                    Members ({selectedBooking.members.length})
                  </h3>
                  <div className="space-y-2">
                    {selectedBooking.members.map((member) => (
                      <div key={member.id} className="border border-gray-200 rounded-lg p-3">
                        <div className="flex justify-between items-start">
                          <div>
                            <p className="font-medium text-gray-900">{member.full_name}</p>
                            {member.email && <p className="text-sm text-gray-600">{member.email}</p>}
                            {member.phone && <p className="text-sm text-gray-600">{member.phone}</p>}
                            {member.assigned_room_id && (
                              <p className="text-sm text-blue-600">Room #{member.assigned_room_id}</p>
                            )}
                          </div>
                          {member.individual_amount && (
                            <div className="text-right">
                              <p className="text-sm text-gray-600">
                                Amount: {formatCurrency(member.individual_amount)}
                              </p>
                              <p className="text-sm text-gray-600">
                                Paid: {formatCurrency(member.individual_paid)}
                              </p>
                            </div>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Pricing */}
              <div className="border-t border-gray-200 pt-4">
                <h3 className="text-lg font-semibold text-gray-900 mb-3">Pricing Summary</h3>
                <div className="space-y-2">
                  <div className="flex justify-between">
                    <span className="text-gray-600">Original Total:</span>
                    <span className="text-gray-900">{formatCurrency(selectedBooking.original_total_price)}</span>
                  </div>
                  {selectedBooking.discount_amount > 0 && (
                    <div className="flex justify-between text-green-600">
                      <span>Discount ({selectedBooking.group_discount_percentage}%):</span>
                      <span>-{formatCurrency(selectedBooking.discount_amount)}</span>
                    </div>
                  )}
                  <div className="flex justify-between font-semibold text-lg border-t border-gray-200 pt-2">
                    <span>Total Price:</span>
                    <span>{formatCurrency(selectedBooking.total_price)}</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-600">Amount Paid:</span>
                    <span className="text-gray-900">{formatCurrency(selectedBooking.amount_paid)}</span>
                  </div>
                  <div className="flex justify-between text-sm font-medium">
                    <span className="text-gray-900">Balance Due:</span>
                    <span className={selectedBooking.balance_due > 0 ? 'text-red-600' : 'text-green-600'}>
                      {formatCurrency(selectedBooking.balance_due)}
                    </span>
                  </div>
                </div>
              </div>

              {/* Payments */}
              {selectedBooking.payments && selectedBooking.payments.length > 0 && (
                <div>
                  <h3 className="text-lg font-semibold text-gray-900 mb-3">Payments</h3>
                  <div className="space-y-2">
                    {selectedBooking.payments.map((payment) => (
                      <div key={payment.id} className="border border-gray-200 rounded-lg p-3">
                        <div className="flex justify-between items-start">
                          <div>
                            <p className="font-medium text-gray-900">
                              {formatCurrency(payment.amount)} - {payment.payment_method}
                            </p>
                            <p className="text-sm text-gray-600">
                              {payment.payment_type} • {payment.payment_status}
                            </p>
                            {payment.payment_date && (
                              <p className="text-xs text-gray-500">
                                {new Date(payment.payment_date).toLocaleDateString()}
                              </p>
                            )}
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

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

export default GroupBookingManagementPage;

