import React, { useState, useEffect } from 'react';
import { X, Search, Calendar, Users, DollarSign, CreditCard, FileText, User } from 'lucide-react';
import bookingService from '../../bookings/services/bookingService';
import roomService from '../../rooms/services/roomService';
import userService from '../../auth/services/userService';
import type { Room } from '../../rooms/services/roomService';
import type { User as UserType } from '../../auth/services/userService';
import { toast } from 'react-toastify';
import { useFormatCurrency } from '../../payments/hooks/useFormatCurrency';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';

interface CreateBookingModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

const CreateBookingModal: React.FC<CreateBookingModalProps> = ({
  isOpen,
  onClose,
  onSuccess,
}) => {
  const { formatCurrency } = useFormatCurrency();
  const [loading, setLoading] = useState(false);
  const [searchingRooms, setSearchingRooms] = useState(false);
  const [searchingUsers, setSearchingUsers] = useState(false);

  // Form state
  const [selectedUser, setSelectedUser] = useState<UserType | null>(null);
  const [userSearch, setUserSearch] = useState('');
  const [userSearchResults, setUserSearchResults] = useState<UserType[]>([]);
  const [showUserResults, setShowUserResults] = useState(false);

  const [selectedRoom, setSelectedRoom] = useState<Room | null>(null);
  const [checkInDate, setCheckInDate] = useState<Date | null>(null);
  const [checkOutDate, setCheckOutDate] = useState<Date | null>(null);
  const [guestCount, setGuestCount] = useState(1);
  const [totalPrice, setTotalPrice] = useState<number>(0);
  const [paymentMethod, setPaymentMethod] = useState<'cash' | 'stripe' | 'paypal'>('cash');
  const [paymentStatus, setPaymentStatus] = useState<'full' | 'deposit' | 'unpaid'>('unpaid');
  const [bookingStatus, setBookingStatus] = useState<'pending' | 'confirmed'>('confirmed');
  const [specialRequests, setSpecialRequests] = useState('');
  const [availableRooms, setAvailableRooms] = useState<Room[]>([]);

  // Search for users
  useEffect(() => {
    if (userSearch.length >= 2) {
      const timeoutId = setTimeout(async () => {
        try {
          setSearchingUsers(true);
          const response = await userService.getUsers({
            search: userSearch,
            role: 'customer',
            limit: 10,
          });
          setUserSearchResults(response.data.users || []);
          setShowUserResults(true);
        } catch (error: unknown) {
          console.error('Error searching users:', error);
        } finally {
          setSearchingUsers(false);
        }
      }, 300);

      return () => clearTimeout(timeoutId);
    } else {
      setUserSearchResults([]);
      setShowUserResults(false);
    }
  }, [userSearch]);

  // Search for available rooms when dates are selected
  useEffect(() => {
    if (checkInDate && checkOutDate && checkInDate < checkOutDate) {
      const searchRooms = async () => {
        try {
          setSearchingRooms(true);
          const checkInStr = checkInDate.toISOString().split('T')[0];
          const checkOutStr = checkOutDate.toISOString().split('T')[0];
          
          const response = await roomService.searchAvailableRooms({
            from: checkInStr,
            to: checkOutStr,
            limit: 50,
          });
          
          setAvailableRooms(response.data.rooms || []);
          
          // Auto-calculate price if room is selected
          if (selectedRoom) {
            const nights = Math.ceil((checkOutDate.getTime() - checkInDate.getTime()) / (1000 * 60 * 60 * 24));
            const roomPrice = selectedRoom.room_type?.base_price || selectedRoom.price || 0;
            setTotalPrice(roomPrice * nights);
          }
        } catch (error: unknown) {
          console.error('Error searching rooms:', error);
          toast.error('Failed to search available rooms');
        } finally {
          setSearchingRooms(false);
        }
      };

      searchRooms();
    } else {
      setAvailableRooms([]);
    }
  }, [checkInDate, checkOutDate, selectedRoom]);

  // Calculate price when room or dates change
  useEffect(() => {
    if (selectedRoom && checkInDate && checkOutDate && checkInDate < checkOutDate) {
      const nights = Math.ceil((checkOutDate.getTime() - checkInDate.getTime()) / (1000 * 60 * 60 * 24));
      const roomPrice = selectedRoom.room_type?.base_price || selectedRoom.price || 0;
      setTotalPrice(roomPrice * nights);
    }
  }, [selectedRoom, checkInDate, checkOutDate]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!selectedUser) {
      toast.error('Please select a guest');
      return;
    }

    if (!selectedRoom) {
      toast.error('Please select a room');
      return;
    }

    if (!checkInDate || !checkOutDate) {
      toast.error('Please select check-in and check-out dates');
      return;
    }

    if (checkInDate >= checkOutDate) {
      toast.error('Check-out date must be after check-in date');
      return;
    }

    if (totalPrice <= 0) {
      toast.error('Total price must be greater than 0');
      return;
    }

    try {
      setLoading(true);
      
      const bookingData = {
        user_id: selectedUser.id,
        room_id: selectedRoom.id,
        check_in_date: checkInDate.toISOString().split('T')[0],
        check_out_date: checkOutDate.toISOString().split('T')[0],
        guest_count: guestCount,
        total_price: totalPrice,
        payment_method: paymentMethod,
        payment_status: paymentStatus, // 'full', 'deposit', or 'unpaid'
        notes: specialRequests,
        status: bookingStatus,
        guest_info: {
          full_name: selectedUser.full_name || '',
          email: selectedUser.email || '',
          phone: selectedUser.phone_number || '',
        },
      };

      await bookingService.adminCreateBooking(bookingData);
      toast.success('Booking created successfully!');
      handleClose();
      onSuccess();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || getUserFriendlyError(error) || 'Failed to create booking');
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    setSelectedUser(null);
    setUserSearch('');
    setUserSearchResults([]);
    setShowUserResults(false);
    setSelectedRoom(null);
    setCheckInDate(null);
    setCheckOutDate(null);
    setGuestCount(1);
    setTotalPrice(0);
    setPaymentMethod('cash');
    setPaymentStatus('unpaid');
    setBookingStatus('confirmed');
    setSpecialRequests('');
    setAvailableRooms([]);
    onClose();
  };

  const handleSelectUser = (user: UserType) => {
    setSelectedUser(user);
    setUserSearch(user.full_name);
    setShowUserResults(false);
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/70 backdrop-blur-md flex items-center justify-center z-50 p-4 animate-fade-in">
      <div className="bg-white rounded-3xl shadow-2xl w-full max-w-4xl max-h-[90vh] overflow-hidden animate-scale-in border border-slate-200">
        {/* Header */}
        <div className="bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 px-8 py-6 border-b border-slate-700">
          <div className="flex justify-between items-center">
            <div>
              <h2 className="text-3xl font-bold text-amber-100 mb-1">Create New Booking</h2>
              <p className="text-amber-200/80 text-sm font-light">Mark a room as booked for specific dates</p>
            </div>
            <button
              onClick={handleClose}
              className="w-10 h-10 flex items-center justify-center rounded-xl text-amber-100 hover:text-white hover:bg-slate-700/50 transition-all duration-200 border border-slate-600 hover:border-amber-400"
            >
              <X className="w-6 h-6" />
            </button>
          </div>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="p-8 overflow-y-auto max-h-[calc(90vh-120px)]">
          <div className="space-y-6">
            {/* Guest Selection */}
            <div>
              <label className="block text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
                <User className="w-5 h-5 text-amber-600" />
                Guest / Customer *
              </label>
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 w-5 h-5" />
                <input
                  type="text"
                  placeholder="Search for customer by name or email..."
                  value={userSearch}
                  onChange={(e) => setUserSearch(e.target.value)}
                  onFocus={() => setShowUserResults(userSearchResults.length > 0)}
                  className="w-full pl-10 pr-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                />
                {showUserResults && userSearchResults.length > 0 && (
                  <div className="absolute z-10 w-full mt-2 bg-white border-2 border-slate-200 rounded-xl shadow-lg max-h-60 overflow-y-auto">
                    {userSearchResults.map((user) => (
                      <button
                        key={user.id}
                        type="button"
                        onClick={() => handleSelectUser(user)}
                        className="w-full text-left px-4 py-3 hover:bg-amber-50 transition-colors border-b border-slate-100 last:border-0"
                      >
                        <div className="font-semibold text-slate-900">{user.full_name}</div>
                        <div className="text-sm text-slate-500">{user.email}</div>
                        {user.phone_number && (
                          <div className="text-xs text-slate-400">{user.phone_number}</div>
                        )}
                      </button>
                    ))}
                  </div>
                )}
                {searchingUsers && (
                  <div className="absolute right-3 top-1/2 transform -translate-y-1/2">
                    <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-amber-600"></div>
                  </div>
                )}
              </div>
              {selectedUser && (
                <div className="mt-2 p-3 bg-amber-50 rounded-lg border border-amber-200">
                  <div className="font-semibold text-slate-900">{selectedUser.full_name}</div>
                  <div className="text-sm text-slate-600">{selectedUser.email}</div>
                </div>
              )}
            </div>

            {/* Date Selection */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
                  <Calendar className="w-5 h-5 text-amber-600" />
                  Check-in Date *
                </label>
                <DatePicker
                  selected={checkInDate}
                  onChange={(date: Date | null) => setCheckInDate(date)}
                  minDate={new Date()}
                  dateFormat="yyyy-MM-dd"
                  className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                  placeholderText="Select check-in date"
                />
              </div>
              <div>
                <label className="block text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
                  <Calendar className="w-5 h-5 text-amber-600" />
                  Check-out Date *
                </label>
                <DatePicker
                  selected={checkOutDate}
                  onChange={(date: Date | null) => setCheckOutDate(date)}
                  minDate={checkInDate || new Date()}
                  dateFormat="yyyy-MM-dd"
                  className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                  placeholderText="Select check-out date"
                />
              </div>
            </div>

            {/* Room Selection */}
            <div>
              <label className="block text-sm font-semibold text-slate-700 mb-2">
                Room *
              </label>
              {searchingRooms && checkInDate && checkOutDate ? (
                <div className="p-4 text-center text-slate-500">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-amber-600 mx-auto mb-2"></div>
                  Searching available rooms...
                </div>
              ) : availableRooms.length > 0 ? (
                <select
                  value={selectedRoom?.id || ''}
                  onChange={(e) => {
                    const room = availableRooms.find((r) => r.id === parseInt(e.target.value));
                    setSelectedRoom(room || null);
                  }}
                  className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                >
                  <option value="">Select a room</option>
                  {availableRooms.map((room) => (
                    <option key={room.id} value={room.id}>
                      Room {room.room_number} - {room.room_type?.name || 'Standard'} - {formatCurrency(room.room_type?.base_price || room.price || 0)}/night
                    </option>
                  ))}
                </select>
              ) : checkInDate && checkOutDate ? (
                <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-xl text-yellow-800">
                  No available rooms found for the selected dates. Please try different dates.
                </div>
              ) : (
                <div className="p-4 bg-slate-50 border border-slate-200 rounded-xl text-slate-500">
                  Please select check-in and check-out dates to see available rooms
                </div>
              )}
            </div>

            {/* Guest Count and Price */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
                  <Users className="w-5 h-5 text-amber-600" />
                  Number of Guests *
                </label>
                <input
                  type="number"
                  min="1"
                  value={guestCount}
                  onChange={(e) => setGuestCount(parseInt(e.target.value) || 1)}
                  className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                />
              </div>
              <div>
                <label className="block text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
                  <DollarSign className="w-5 h-5 text-amber-600" />
                  Total Price *
                </label>
                <input
                  type="number"
                  min="0"
                  step="0.01"
                  value={totalPrice}
                  onChange={(e) => setTotalPrice(parseFloat(e.target.value) || 0)}
                  className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                />
                {selectedRoom && checkInDate && checkOutDate && (
                  <p className="text-xs text-slate-500 mt-1">
                    {formatCurrency(totalPrice)} for{' '}
                    {Math.ceil((checkOutDate.getTime() - checkInDate.getTime()) / (1000 * 60 * 60 * 24))} night(s)
                  </p>
                )}
              </div>
            </div>

            {/* Payment Method and Payment Status */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
                  <CreditCard className="w-5 h-5 text-amber-600" />
                  Payment Method *
                </label>
                <select
                  value={paymentMethod}
                  onChange={(e) => setPaymentMethod(e.target.value as 'cash' | 'stripe' | 'paypal')}
                  className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                >
                  <option value="cash">Cash</option>
                  <option value="stripe">Card (Stripe)</option>
                  <option value="paypal">PayPal</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
                  <DollarSign className="w-5 h-5 text-amber-600" />
                  Payment Status *
                </label>
                <select
                  value={paymentStatus}
                  onChange={(e) => setPaymentStatus(e.target.value as 'full' | 'deposit' | 'unpaid')}
                  className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                >
                  <option value="unpaid">Unpaid (Pay at Check-in)</option>
                  <option value="deposit">20% Deposit Only (Rest at Check-in)</option>
                  <option value="full">Fully Paid</option>
                </select>
              </div>
            </div>

            {/* Booking Summary */}
            {totalPrice > 0 && (
              <div className="bg-gradient-to-br from-slate-50 to-amber-50/30 rounded-xl border-2 border-amber-200/50 p-6 space-y-3">
                <h3 className="text-lg font-bold text-slate-900 mb-4 flex items-center gap-2">
                  <FileText className="w-5 h-5 text-amber-600" />
                  Booking Summary
                </h3>
                
                {selectedRoom && checkInDate && checkOutDate && (
                  <div className="space-y-2 text-sm">
                    <div className="flex justify-between items-center">
                      <span className="text-slate-600">Room:</span>
                      <span className="font-semibold text-slate-900">
                        {selectedRoom.room_type?.name || 'Standard Room'} - Room {selectedRoom.room_number}
                      </span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-slate-600">Room price/night:</span>
                      <span className="font-semibold text-slate-900">
                        {formatCurrency(selectedRoom.room_type?.base_price || selectedRoom.price || 0)}
                      </span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-slate-600">Nights:</span>
                      <span className="font-semibold text-slate-900">
                        {Math.ceil((checkOutDate.getTime() - checkInDate.getTime()) / (1000 * 60 * 60 * 24))} night(s)
                      </span>
                    </div>
                    <div className="flex justify-between items-center border-t border-amber-200 pt-2">
                      <span className="text-slate-600">Room Total:</span>
                      <span className="font-semibold text-slate-900">
                        {formatCurrency((selectedRoom.room_type?.base_price || selectedRoom.price || 0) * Math.ceil((checkOutDate.getTime() - checkInDate.getTime()) / (1000 * 60 * 60 * 24)))}
                      </span>
                    </div>
                  </div>
                )}
                
                <div className="border-t border-amber-200 pt-3 space-y-2">
                  <div className="flex justify-between items-center">
                    <span className="text-slate-600">Subtotal:</span>
                    <span className="font-semibold text-slate-900">{formatCurrency(totalPrice)}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-slate-600">Total:</span>
                    <span className="text-lg font-bold text-slate-900">{formatCurrency(totalPrice)}</span>
                  </div>
                </div>

                {paymentStatus === 'deposit' && (
                  <div className="bg-amber-100/50 rounded-lg p-4 border border-amber-300 space-y-2">
                    <div className="flex justify-between items-center">
                      <span className="text-amber-800 font-semibold">Deposit to pay (20%):</span>
                      <span className="text-lg font-bold text-amber-900">{formatCurrency(totalPrice * 0.2)}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-amber-700">Remaining balance:</span>
                      <span className="font-semibold text-amber-900">{formatCurrency(totalPrice * 0.8)}</span>
                    </div>
                    <p className="text-xs text-amber-700 mt-2 italic">
                      Pay 20% deposit to secure booking, remaining balance on arrival
                    </p>
                  </div>
                )}

                {paymentStatus === 'full' && (
                  <div className="bg-green-100/50 rounded-lg p-4 border border-green-300">
                    <div className="flex justify-between items-center">
                      <span className="text-green-800 font-semibold">Amount to pay:</span>
                      <span className="text-lg font-bold text-green-900">{formatCurrency(totalPrice)}</span>
                    </div>
                    <p className="text-xs text-green-700 mt-2 italic">
                      Full payment will be marked as completed
                    </p>
                  </div>
                )}

                {paymentStatus === 'unpaid' && (
                  <div className="bg-blue-100/50 rounded-lg p-4 border border-blue-300">
                    <div className="flex justify-between items-center">
                      <span className="text-blue-800 font-semibold">Payment due at check-in:</span>
                      <span className="text-lg font-bold text-blue-900">{formatCurrency(totalPrice)}</span>
                    </div>
                    <p className="text-xs text-blue-700 mt-2 italic">
                      Guest will pay the full amount upon arrival
                    </p>
                  </div>
                )}
              </div>
            )}

            {/* Booking Status */}
            <div>
              <label className="block text-sm font-semibold text-slate-700 mb-2">
                Booking Status *
              </label>
              <select
                value={bookingStatus}
                onChange={(e) => setBookingStatus(e.target.value as 'pending' | 'confirmed')}
                className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
              >
                <option value="confirmed">Confirmed</option>
                <option value="pending">Pending</option>
              </select>
            </div>

            {/* Special Requests */}
            <div>
              <label className="block text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
                <FileText className="w-5 h-5 text-amber-600" />
                Special Requests / Notes
              </label>
              <textarea
                value={specialRequests}
                onChange={(e) => setSpecialRequests(e.target.value)}
                rows={3}
                className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all resize-none"
                placeholder="Any special requests or notes..."
              />
            </div>
          </div>

          {/* Actions */}
          <div className="mt-8 pt-6 border-t border-slate-200 flex justify-end gap-4">
            <button
              type="button"
              onClick={handleClose}
              className="px-6 py-3 bg-slate-200 text-slate-700 rounded-xl font-semibold hover:bg-slate-300 transition-all duration-200"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={loading}
              className="px-6 py-3 bg-gradient-to-r from-amber-500 to-amber-600 text-white rounded-xl font-semibold hover:from-amber-600 hover:to-amber-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 shadow-lg hover:shadow-xl"
            >
              {loading ? 'Creating...' : 'Create Booking'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default CreateBookingModal;

