import React, { useState, useEffect } from 'react';
import { Search, User, Hotel, CheckCircle, AlertCircle, Calendar, LogIn, LogOut } from 'lucide-react';
import { bookingService, Booking } from '../../services/api';
import { toast } from 'react-toastify';
import Loading from '../../components/common/Loading';
import { useFormatCurrency } from '../../hooks/useFormatCurrency';
import { parseDateLocal } from '../../utils/format';

interface GuestInfo {
  name: string;
  id_number: string;
  phone: string;
}

const CheckInPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const [selectedDate, setSelectedDate] = useState<string>(() => {
    const today = new Date();
    return today.toISOString().split('T')[0];
  });
  const [searchQuery, setSearchQuery] = useState('');
  const [checkInBookings, setCheckInBookings] = useState<Booking[]>([]);
  const [checkOutBookings, setCheckOutBookings] = useState<Booking[]>([]);
  const [loadingBookings, setLoadingBookings] = useState(false);
  const [booking, setBooking] = useState<Booking | null>(null);
  const [loading, setLoading] = useState(false);
  const [searching, setSearching] = useState(false);
  const [actualRoomNumber, setActualRoomNumber] = useState('');
  const [guests, setGuests] = useState<GuestInfo[]>([{ name: '', id_number: '', phone: '' }]);
  const [extraPersons, setExtraPersons] = useState(0);
  const [children, setChildren] = useState(0);
  const [additionalFee, setAdditionalFee] = useState(0);

  
  useEffect(() => {
    fetchBookingsForDate();
  }, [selectedDate, searchQuery]);

  const fetchBookingsForDate = async () => {
    if (!selectedDate) return;

    try {
      setLoadingBookings(true);
      const date = new Date(selectedDate);
      date.setHours(0, 0, 0, 0);
      const nextDay = new Date(date);
      nextDay.setDate(nextDay.getDate() + 1);

      
      const params: any = {
        limit: 200, 
      };
      if (searchQuery) {
        params.search = searchQuery;
      }

      
      const startDate = new Date(date);
      startDate.setDate(startDate.getDate() - 3);
      const endDate = new Date(date);
      endDate.setDate(endDate.getDate() + 3);
      
      params.startDate = startDate.toISOString();
      params.endDate = endDate.toISOString();

      const response = await bookingService.getAllBookings(params);
      const allBookings = response.data.bookings || [];
      
      
      const filteredCheckIns = allBookings.filter((booking) => {
        if (!booking.check_in_date || booking.status !== 'confirmed') return false;
        const checkInDate = new Date(booking.check_in_date);
        checkInDate.setHours(0, 0, 0, 0);
        return checkInDate.getTime() === date.getTime();
      });
      setCheckInBookings(filteredCheckIns);

      
      const filteredCheckOuts = allBookings.filter((booking) => {
        if (!booking.check_out_date || booking.status !== 'checked_in') return false;
        const checkOutDate = new Date(booking.check_out_date);
        checkOutDate.setHours(0, 0, 0, 0);
        return checkOutDate.getTime() === date.getTime();
      });
      setCheckOutBookings(filteredCheckOuts);
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Unable to load bookings');
    } finally {
      setLoadingBookings(false);
    }
  };

  const handleSearchByNumber = async () => {
    if (!searchQuery.trim()) {
      toast.error('Please enter booking number');
      return;
    }

    try {
      setSearching(true);
      const response = await bookingService.checkBookingByNumber(searchQuery);
      setBooking(response.data.booking);
      setActualRoomNumber(response.data.booking.room?.room_number || '');
      
      if ((response as any).warning) {
        const warning = (response as any).warning;
        toast.warning(
          `⚠️ Payment Reminder: Guest has remaining balance of ${formatCurrency(warning.remaining_balance)} (${warning.payment_percentage.toFixed(1)}% paid)`,
          { autoClose: 8000 }
        );
      } else {
        toast.success('Booking found');
      }
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Booking not found');
      setBooking(null);
    } finally {
      setSearching(false);
    }
  };

  const handleSelectBooking = async (bookingNumber: string) => {
    try {
      setSearching(true);
      const response = await bookingService.checkBookingByNumber(bookingNumber);
      setBooking(response.data.booking);
      setActualRoomNumber(response.data.booking.room?.room_number || '');
      setSearchQuery(bookingNumber);
      
      if ((response as any).warning) {
        const warning = (response as any).warning;
        toast.warning(
          `⚠️ Payment Reminder: Guest has remaining balance of ${formatCurrency(warning.remaining_balance)} (${warning.payment_percentage.toFixed(1)}% paid)`,
          { autoClose: 8000 }
        );
      } else {
        toast.success('Booking selected');
      }
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Unable to load booking');
    } finally {
      setSearching(false);
    }
  };

  const handleAddGuest = () => {
    setGuests([...guests, { name: '', id_number: '', phone: '' }]);
  };

  const handleRemoveGuest = (index: number) => {
    if (guests.length > 1) {
      setGuests(guests.filter((_, i) => i !== index));
    }
  };

  const handleGuestChange = (index: number, field: keyof GuestInfo, value: string) => {
    const newGuests = [...guests];
    newGuests[index][field] = value;
    setGuests(newGuests);
  };

  const calculateAdditionalFee = () => {
    const extraPersonFee = extraPersons * 200000;
    const childrenFee = children * 100000;
    const total = extraPersonFee + childrenFee;
    setAdditionalFee(total);
    return total;
  };

  const handleCheckIn = async () => {
    if (!booking) return;

    if (!actualRoomNumber.trim()) {
      toast.error('Please enter actual room number');
      return;
    }

    const mainGuest = guests[0];
    if (!mainGuest.name || !mainGuest.id_number || !mainGuest.phone) {
      toast.error('Please fill in all main guest information');
      return;
    }

    try {
      setLoading(true);
      calculateAdditionalFee();

      const response = await bookingService.updateBooking(booking.id, {
        status: 'checked_in',
      } as any);

      if ((response as any).warning) {
        const warning = (response as any).warning;
        toast.warning(
          `⚠️ Check-in successful, but guest has remaining balance: ${formatCurrency(warning.remaining_balance)} (${warning.payment_percentage.toFixed(1)}% paid)`,
          { autoClose: 10000 }
        );
      } else {
        toast.success('Check-in successful');
      }
      
      
      setBooking(null);
      setSearchQuery('');
      setActualRoomNumber('');
      setGuests([{ name: '', id_number: '', phone: '' }]);
      setExtraPersons(0);
      setChildren(0);
      setAdditionalFee(0);
      await fetchBookingsForDate();
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'An error occurred during check-in');
    } finally {
      setLoading(false);
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', { 
      weekday: 'short', 
      year: 'numeric', 
      month: 'short', 
      day: 'numeric' 
    });
  };

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

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Check-in</h1>
          <p className="text-gray-500 mt-1">Customer check-in process</p>
        </div>
      </div>

      {}
      <div className="bg-white p-6 rounded-lg shadow-sm">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              <Calendar className="w-4 h-4 inline mr-2" />
              Select Date
            </label>
            <input
              type="date"
              value={selectedDate}
              onChange={(e) => setSelectedDate(e.target.value)}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              <Search className="w-4 h-4 inline mr-2" />
              Search by Booking Number
            </label>
            <div className="flex gap-2">
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onKeyPress={(e) => e.key === 'Enter' && handleSearchByNumber()}
                placeholder="Enter booking number"
                className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
              />
              <button
                onClick={handleSearchByNumber}
                disabled={searching}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-gray-400"
              >
                {searching ? '...' : 'Search'}
              </button>
            </div>
          </div>
          <div className="flex items-end">
            <button
              onClick={() => {
                const today = new Date();
                setSelectedDate(today.toISOString().split('T')[0]);
                setSearchQuery('');
              }}
              className="w-full px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200"
            >
              Reset to Today
            </button>
          </div>
        </div>
      </div>

      {}
      {!booking && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {}
          <div className="bg-white p-6 rounded-lg shadow-sm">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-xl font-semibold flex items-center gap-2">
                <LogIn className="w-5 h-5 text-green-600" />
                Check-ins for {formatDate(selectedDate)}
              </h2>
              <span className="px-3 py-1 bg-green-100 text-green-800 rounded-full text-sm font-medium">
                {checkInBookings.length}
              </span>
            </div>
            {loadingBookings ? (
              <div className="text-center py-8">
                <Loading />
              </div>
            ) : checkInBookings.length === 0 ? (
              <div className="text-center py-8 text-gray-500">
                <LogIn className="w-12 h-12 mx-auto mb-2 text-gray-300" />
                <p>No check-ins scheduled for this date</p>
              </div>
            ) : (
              <div className="space-y-3 max-h-96 overflow-y-auto">
                {checkInBookings.map((b) => (
                  <div
                    key={b.id}
                    onClick={() => handleSelectBooking(b.booking_number)}
                    className="p-4 border border-gray-200 rounded-lg hover:border-blue-500 hover:shadow-md cursor-pointer transition-all"
                  >
                    <div className="flex justify-between items-start">
                      <div className="flex-1">
                        <div className="font-semibold text-gray-900">{b.booking_number}</div>
                        <div className="text-sm text-gray-600 mt-1">{b.user?.full_name}</div>
                        <div className="text-xs text-gray-500 mt-1">
                          {b.room?.room_type?.name} • {formatCurrency(b.total_price)}
                        </div>
                      </div>
                      <div className="text-right">
                        <span className={`px-2 py-1 rounded text-xs font-medium ${
                          b.status === 'confirmed' ? 'bg-green-100 text-green-800' :
                          b.status === 'checked_in' ? 'bg-blue-100 text-blue-800' :
                          'bg-gray-100 text-gray-800'
                        }`}>
                          {b.status}
                        </span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {}
          <div className="bg-white p-6 rounded-lg shadow-sm">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-xl font-semibold flex items-center gap-2">
                <LogOut className="w-5 h-5 text-orange-600" />
                Check-outs for {formatDate(selectedDate)}
              </h2>
              <span className="px-3 py-1 bg-orange-100 text-orange-800 rounded-full text-sm font-medium">
                {checkOutBookings.length}
              </span>
            </div>
            {loadingBookings ? (
              <div className="text-center py-8">
                <Loading />
              </div>
            ) : checkOutBookings.length === 0 ? (
              <div className="text-center py-8 text-gray-500">
                <LogOut className="w-12 h-12 mx-auto mb-2 text-gray-300" />
                <p>No check-outs scheduled for this date</p>
              </div>
            ) : (
              <div className="space-y-3 max-h-96 overflow-y-auto">
                {checkOutBookings.map((b) => (
                  <div
                    key={b.id}
                    onClick={() => handleSelectBooking(b.booking_number)}
                    className="p-4 border border-gray-200 rounded-lg hover:border-orange-500 hover:shadow-md cursor-pointer transition-all"
                  >
                    <div className="flex justify-between items-start">
                      <div className="flex-1">
                        <div className="font-semibold text-gray-900">{b.booking_number}</div>
                        <div className="text-sm text-gray-600 mt-1">{b.user?.full_name}</div>
                        <div className="text-xs text-gray-500 mt-1">
                          {b.room?.room_type?.name} • {formatCurrency(b.total_price)}
                        </div>
                      </div>
                      <div className="text-right">
                        <span className={`px-2 py-1 rounded text-xs font-medium ${
                          b.status === 'checked_in' ? 'bg-blue-100 text-blue-800' :
                          b.status === 'checked_out' ? 'bg-gray-100 text-gray-800' :
                          'bg-gray-100 text-gray-800'
                        }`}>
                          {b.status}
                        </span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      )}

      {}
      {booking && (
        <>
          <div className="bg-white p-6 rounded-lg shadow-sm">
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-lg font-semibold flex items-center gap-2">
                <CheckCircle className="w-5 h-5 text-green-600" />
                2. Booking Information
              </h2>
              <button
                onClick={() => {
                  setBooking(null);
                  setSearchQuery('');
                }}
                className="text-gray-500 hover:text-gray-700"
              >
                Close
              </button>
            </div>
            <div className="grid grid-cols-2 gap-6">
              <div>
                <div className="space-y-3">
                  <div className="flex justify-between">
                    <span className="text-gray-600">Booking Number:</span>
                    <span className="font-semibold">{booking.booking_number}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600">Customer:</span>
                    <span className="font-semibold">{booking.user?.full_name}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600">Email:</span>
                    <span>{booking.user?.email}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600">Phone:</span>
                    <span>{booking.user?.phone_number || 'N/A'}</span>
                  </div>
                </div>
              </div>
              <div>
                <div className="space-y-3">
                  <div className="flex justify-between">
                    <span className="text-gray-600">Room Type:</span>
                    <span className="font-semibold">{booking.room?.room_type?.name || 'N/A'}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600">Check-in:</span>
                    <span>{booking.check_in_date ? parseDateLocal(booking.check_in_date).toLocaleDateString('en-US') : 'N/A'}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600">Check-out:</span>
                    <span>{booking.check_out_date ? parseDateLocal(booking.check_out_date).toLocaleDateString('en-US') : 'N/A'}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600">Number of Guests:</span>
                    <span>{booking.guest_count} guest(s)</span>
                  </div>
                </div>
              </div>
            </div>

            {}
            {booking.payment_balance && booking.payment_balance.remaining_balance > 0.01 && (
              <div className="mt-6 p-4 bg-gradient-to-r from-amber-50 to-orange-50 rounded-lg border-2 border-amber-400">
                <div className="flex items-start gap-3">
                  <AlertCircle className="w-6 h-6 text-amber-600 mt-0.5 flex-shrink-0" />
                  <div className="flex-1">
                    <h3 className="text-lg font-bold text-amber-900 mb-2">
                      ⚠️ Payment Reminder
                    </h3>
                    <p className="text-amber-800 mb-3">
                      This guest has <strong>not fully paid</strong> for their booking. Please collect the remaining balance during check-in.
                    </p>
                    <div className="grid grid-cols-2 gap-4 bg-white/50 p-3 rounded-lg">
                      <div>
                        <span className="text-sm text-amber-700">Total Price:</span>
                        <p className="text-lg font-bold text-gray-900">{formatCurrency(booking.payment_balance.total_price)}</p>
                      </div>
                      <div>
                        <span className="text-sm text-amber-700">Amount Paid:</span>
                        <p className="text-lg font-bold text-green-600">{formatCurrency(booking.payment_balance.total_paid)}</p>
                      </div>
                      <div>
                        <span className="text-sm text-amber-700">Payment Progress:</span>
                        <p className="text-lg font-bold text-blue-600">{booking.payment_balance.payment_percentage.toFixed(1)}%</p>
                      </div>
                      <div>
                        <span className="text-sm text-amber-700">Remaining Balance:</span>
                        <p className="text-xl font-bold text-red-600">{formatCurrency(booking.payment_balance.remaining_balance)}</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {}
            <div className="mt-6 p-4 bg-gradient-to-r from-green-50 to-emerald-50 rounded-lg border border-green-200">
              <h3 className="text-md font-semibold text-gray-900 mb-3 flex items-center gap-2">
                <CheckCircle className="w-5 h-5 text-green-600" />
                Payment Information
              </h3>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <span className="text-gray-600">Payment Method:</span>
                      <span className="font-semibold">
                        {booking.payment_method === 'cash'
                          ? '💵 Pay at Hotel'
                          : booking.payment_method === 'stripe'
                          ? '💳 Stripe (Card)'
                          : booking.payment_method === 'paypal'
                          ? '💳 PayPal'
                          : booking.payment_method || 'N/A'}
                      </span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-600">Payment Status:</span>
                      <span className={`font-semibold ${
                        booking.payment_status === 'paid'
                          ? 'text-green-600'
                          : booking.payment_status === 'refunded'
                          ? 'text-orange-600'
                          : 'text-red-600'
                      }`}>
                        {booking.payment_status === 'paid'
                          ? '✅ Paid'
                          : booking.payment_status === 'refunded'
                          ? '💰 Refunded'
                          : '❌ Unpaid'}
                      </span>
                    </div>
                  </div>
                </div>
                <div>
                  <div className="space-y-2">
                    {(() => {
                      const paymentBalance = booking.payment_balance || (() => {
                        const completedPayments = booking.payments?.filter(
                          (p) => p.payment_status === 'completed'
                        ) || [];
                        const amountPaid = completedPayments.reduce(
                          (sum, p) => sum + (p.amount || 0),
                          0
                        );
                        const remainingDue = booking.total_price - amountPaid;
                        return {
                          total_paid: amountPaid,
                          total_price: booking.total_price,
                          remaining_balance: remainingDue,
                          is_fully_paid: remainingDue <= 0.01,
                          payment_percentage: booking.total_price > 0 ? (amountPaid / booking.total_price * 100) : 0
                        };
                      })();
                      
                      const completedPayments = booking.payments?.filter(
                        (p) => p.payment_status === 'completed'
                      ) || [];
                      const hasPayments = completedPayments.length > 0;
                      
                      return (
                        <>
                          <div className="flex justify-between">
                            <span className="text-gray-600">Total Price:</span>
                            <span className="font-semibold text-gray-900">{formatCurrency(paymentBalance.total_price)}</span>
                          </div>
                          {hasPayments && (
                            <>
                              <div className="flex justify-between">
                                <span className="text-gray-600">Amount Paid:</span>
                                <span className="font-semibold text-green-600">{formatCurrency(paymentBalance.total_paid)}</span>
                              </div>
                              {paymentBalance.remaining_balance > 0.01 && (
                                <div className="flex justify-between">
                                  <span className="text-gray-600">Remaining Due:</span>
                                  <span className="font-semibold text-red-600">{formatCurrency(paymentBalance.remaining_balance)}</span>
                                </div>
                              )}
                              {completedPayments.length > 0 && (
                                <div className="mt-2 pt-2 border-t border-green-200">
                                  <p className="text-xs text-gray-500 mb-1">Payment Details:</p>
                                  {completedPayments.map((payment, idx) => (
                                    <div key={payment.id || idx} className="text-xs text-gray-600">
                                      • {formatCurrency(payment.amount)} via {payment.payment_method === 'stripe' ? 'Stripe' : payment.payment_method === 'paypal' ? 'PayPal' : payment.payment_method || 'Cash'}
                                      {payment.payment_type === 'deposit' && ' (Deposit 20%)'}
                                      {payment.transaction_id && ` - ${payment.transaction_id}`}
                                    </div>
                                  ))}
                                </div>
                              )}
                            </>
                          )}
                        </>
                      );
                    })()}
                  </div>
                </div>
              </div>
            </div>

            {booking.status !== 'confirmed' && (
              <div className="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg flex items-start gap-2">
                <AlertCircle className="w-5 h-5 text-yellow-600 mt-0.5" />
                <div>
                  <p className="text-sm text-yellow-800 font-medium">Warning</p>
                  <p className="text-sm text-yellow-700">
                    Booking status: <span className="font-semibold">{booking.status}</span>. 
                    Only check-in confirmed bookings.
                  </p>
                </div>
              </div>
            )}
          </div>

          {}
          <div className="bg-white p-6 rounded-lg shadow-sm">
            <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
              <Hotel className="w-5 h-5 text-blue-600" />
              3. Assign Actual Room Number
            </h2>
            <div className="max-w-md">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Room Number <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                value={actualRoomNumber}
                onChange={(e) => setActualRoomNumber(e.target.value)}
                placeholder="e.g: 101, 202, 305"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
              />
              <p className="text-xs text-gray-500 mt-1">
                Enter the actual room number to assign to the guest
              </p>
            </div>
          </div>

          {}
          <div className="bg-white p-6 rounded-lg shadow-sm">
            <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
              <User className="w-5 h-5 text-purple-600" />
              4. Guest Information
            </h2>
            <div className="space-y-4">
              {guests.map((guest, index) => (
                <div key={index} className="p-4 border border-gray-200 rounded-lg">
                  <div className="flex justify-between items-center mb-3">
                    <h3 className="font-medium">
                      {index === 0 ? 'Main Guest' : `Guest ${index + 1}`}
                      {index === 0 && <span className="text-red-500 ml-1">*</span>}
                    </h3>
                    {index > 0 && (
                      <button
                        onClick={() => handleRemoveGuest(index)}
                        className="text-red-600 hover:text-red-800 text-sm"
                      >
                        Remove
                      </button>
                    )}
                  </div>
                  <div className="grid grid-cols-3 gap-4">
                    <div>
                      <label className="block text-sm text-gray-700 mb-1">
                        Full Name {index === 0 && <span className="text-red-500">*</span>}
                      </label>
                      <input
                        type="text"
                        value={guest.name}
                        onChange={(e) => handleGuestChange(index, 'name', e.target.value)}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                        placeholder="John Doe"
                      />
                    </div>
                    <div>
                      <label className="block text-sm text-gray-700 mb-1">
                        ID Number {index === 0 && <span className="text-red-500">*</span>}
                      </label>
                      <input
                        type="text"
                        value={guest.id_number}
                        onChange={(e) => handleGuestChange(index, 'id_number', e.target.value)}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                        placeholder="001234567890"
                      />
                    </div>
                    <div>
                      <label className="block text-sm text-gray-700 mb-1">
                        Phone Number {index === 0 && <span className="text-red-500">*</span>}
                      </label>
                      <input
                        type="tel"
                        value={guest.phone}
                        onChange={(e) => handleGuestChange(index, 'phone', e.target.value)}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                        placeholder="0912345678"
                      />
                    </div>
                  </div>
                </div>
              ))}
              <button
                onClick={handleAddGuest}
                className="text-blue-600 hover:text-blue-800 text-sm font-medium"
              >
                + Add Guest
              </button>
            </div>
          </div>

          {}
          <div className="bg-white p-6 rounded-lg shadow-sm">
            <h2 className="text-lg font-semibold mb-4">5. Additional Fees (if any)</h2>
            <div className="grid grid-cols-3 gap-6">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Extra Persons
                </label>
                <input
                  type="number"
                  min="0"
                  value={extraPersons}
                  onChange={(e) => {
                    setExtraPersons(parseInt(e.target.value) || 0);
                    calculateAdditionalFee();
                  }}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                />
                <p className="text-xs text-gray-500 mt-1">€50/person</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Number of Children
                </label>
                <input
                  type="number"
                  min="0"
                  value={children}
                  onChange={(e) => {
                    setChildren(parseInt(e.target.value) || 0);
                    calculateAdditionalFee();
                  }}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                />
                <p className="text-xs text-gray-500 mt-1">€25/child</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Total Additional Fee
                </label>
                <div className="px-4 py-2 bg-gray-50 border border-gray-300 rounded-lg text-lg font-semibold text-blue-600">
                  {formatCurrency(calculateAdditionalFee())}
                </div>
              </div>
            </div>
          </div>

          {}
          <div className="bg-gradient-to-r from-blue-50 to-indigo-50 p-6 rounded-lg border border-blue-200">
            <div className="flex justify-between items-center">
              <div>
                <h3 className="text-lg font-semibold text-gray-900">Confirm Check-in</h3>
                <p className="text-sm text-gray-600 mt-1">
                  Guest: <span className="font-medium">{booking.user?.full_name}</span> | 
                  Room: <span className="font-medium">{actualRoomNumber || 'Not assigned'}</span>
                  {additionalFee > 0 && (
                    <> | Additional Fee: <span className="font-medium text-red-600">{formatCurrency(additionalFee)}</span></>
                  )}
                </p>
              </div>
              <button
                onClick={handleCheckIn}
                disabled={!actualRoomNumber || !guests[0].name || booking.status !== 'confirmed'}
                className="px-8 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:bg-gray-400 disabled:cursor-not-allowed font-semibold flex items-center gap-2"
              >
                <CheckCircle className="w-5 h-5" />
                Confirm Check-in
              </button>
            </div>
          </div>
        </>
      )}
    </div>
  );
};

export default CheckInPage;
