import React, { useState } from 'react';
import { Search, FileText, CreditCard, Printer, CheckCircle } from 'lucide-react';
import { bookingService, Booking } from '../../services/api';
import { toast } from 'react-toastify';
import Loading from '../../components/common/Loading';
import CurrencyIcon from '../../components/common/CurrencyIcon';
import { useFormatCurrency } from '../../hooks/useFormatCurrency';

interface ServiceItem {
  service_name: string;
  quantity: number;
  price: number;
  total: number;
}

const CheckOutPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const [bookingNumber, setBookingNumber] = useState('');
  const [booking, setBooking] = useState<Booking | null>(null);
  const [loading, setLoading] = useState(false);
  const [searching, setSearching] = useState(false);
  const [services, setServices] = useState<ServiceItem[]>([]);
  const [paymentMethod, setPaymentMethod] = useState<'cash' | 'stripe'>('cash');
  const [discount, setDiscount] = useState(0);
  const [showInvoice, setShowInvoice] = useState(false);

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

    try {
      setSearching(true);
      const response = await bookingService.checkBookingByNumber(bookingNumber);
      const foundBooking = response.data.booking;
      
      if (foundBooking.status !== 'checked_in') {
        toast.warning('Only checked-in bookings can be checked out');
      }
      
      setBooking(foundBooking);
      
      // Mock services data - in production will fetch from API
      setServices([
        { service_name: 'Laundry', quantity: 2, price: 50000, total: 100000 },
        { service_name: 'Minibar', quantity: 1, price: 150000, total: 150000 },
      ]);
      
      toast.success('Booking found');
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Booking not found');
      setBooking(null);
    } finally {
      setSearching(false);
    }
  };

  const calculateRoomFee = () => {
    if (!booking) return 0;
    return booking.total_price || 0;
  };

  const calculateServiceFee = () => {
    return services.reduce((sum, service) => sum + service.total, 0);
  };

  const calculateAdditionalFee = () => {
    // Additional fees from check-in (children, extra person)
    return 0; // In production will get from booking data
  };

  const calculateDeposit = () => {
    // Deposit already paid
    return booking?.total_price ? booking.total_price * 0.3 : 0;
  };

  const calculateSubtotal = () => {
    return calculateRoomFee() + calculateServiceFee() + calculateAdditionalFee();
  };

  const calculateDiscount = () => {
    return discount;
  };

  const calculateTotal = () => {
    return calculateSubtotal() - calculateDiscount();
  };

  const calculateRemaining = () => {
    return calculateTotal() - calculateDeposit();
  };


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

    if (calculateRemaining() < 0) {
      toast.error('Invalid refund amount');
      return;
    }

    try {
      setLoading(true);
      
      // Update booking status
      await bookingService.updateBooking(booking.id, {
        status: 'checked_out',
      } as any);

      // Create payment record (if needed)
      // await paymentService.createPayment({...});

      toast.success('Check-out successful');
      setShowInvoice(true);
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'An error occurred during check-out');
    } finally {
      setLoading(false);
    }
  };

  const handlePrintInvoice = () => {
    window.print();
  };

  const resetForm = () => {
    setBooking(null);
    setBookingNumber('');
    setServices([]);
    setDiscount(0);
    setPaymentMethod('cash');
    setShowInvoice(false);
  };

  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-out</h1>
          <p className="text-gray-500 mt-1">Payment and check-out process</p>
        </div>
      </div>

      {/* Search Booking */}
      {!showInvoice && (
        <div className="bg-white p-6 rounded-lg shadow-sm">
          <h2 className="text-lg font-semibold mb-4">1. Search booking</h2>
          <div className="flex gap-4">
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
              <input
                type="text"
                value={bookingNumber}
                onChange={(e) => setBookingNumber(e.target.value)}
                onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
                placeholder="Enter booking number or room number"
                className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
              />
            </div>
            <button
              onClick={handleSearch}
              disabled={searching}
              className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-gray-400 flex items-center gap-2"
            >
              {searching ? 'Searching...' : 'Search'}
            </button>
          </div>
        </div>
      )}

      {/* Invoice */}
      {booking && !showInvoice && (
        <>
          {/* Booking Info */}
          <div className="bg-white p-6 rounded-lg shadow-sm">
            <h2 className="text-lg font-semibold mb-4">2. Booking information</h2>
            <div className="grid grid-cols-2 gap-6">
              <div className="space-y-2">
                <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">Room number:</span>
                  <span className="font-semibold">{booking.room?.room_number}</span>
                </div>
              </div>
              <div className="space-y-2">
                <div className="flex justify-between">
                  <span className="text-gray-600">Check-in:</span>
                  <span>{booking.check_in_date ? new Date(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 ? new Date(booking.check_out_date).toLocaleDateString('en-US') : 'N/A'}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">Nights:</span>
                  <span>
                    {booking.check_in_date && booking.check_out_date
                      ? Math.ceil((new Date(booking.check_out_date).getTime() - new Date(booking.check_in_date).getTime()) / (1000 * 60 * 60 * 24))
                      : 0} night(s)
                  </span>
                </div>
              </div>
            </div>
          </div>

          {/* Bill Details */}
          <div className="bg-white p-6 rounded-lg shadow-sm">
            <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
              <FileText className="w-5 h-5 text-blue-600" />
              3. Invoice details
            </h2>
            
            {/* Room Fee */}
            <div className="mb-4">
              <h3 className="font-medium text-gray-700 mb-2">Room fee</h3>
              <div className="bg-gray-50 p-4 rounded-lg">
                <div className="flex justify-between">
                  <span>{booking.room?.room_type?.name || 'Room'}</span>
                  <span className="font-semibold">{formatCurrency(calculateRoomFee())}</span>
                </div>
              </div>
            </div>

            {/* Service Fee */}
            {services.length > 0 && (
              <div className="mb-4">
                <h3 className="font-medium text-gray-700 mb-2">Services used</h3>
                <div className="bg-gray-50 p-4 rounded-lg space-y-2">
                  {services.map((service, index) => (
                    <div key={index} className="flex justify-between text-sm">
                      <span>
                        {service.service_name} (x{service.quantity})
                      </span>
                      <span>{formatCurrency(service.total)}</span>
                    </div>
                  ))}
                  <div className="pt-2 border-t border-gray-200 flex justify-between font-medium">
                    <span>Total services:</span>
                    <span>{formatCurrency(calculateServiceFee())}</span>
                  </div>
                </div>
              </div>
            )}

            {/* Additional Fee */}
            {calculateAdditionalFee() > 0 && (
              <div className="mb-4">
                <h3 className="font-medium text-gray-700 mb-2">Additional fees</h3>
                <div className="bg-gray-50 p-4 rounded-lg">
                  <div className="flex justify-between">
                    <span>Extra person/children fee</span>
                    <span className="font-semibold">{formatCurrency(calculateAdditionalFee())}</span>
                  </div>
                </div>
              </div>
            )}

            {/* Discount */}
            <div className="mb-4">
              <h3 className="font-medium text-gray-700 mb-2">Discount</h3>
              <div className="flex gap-4">
                <input
                  type="number"
                  value={discount}
                  onChange={(e) => setDiscount(parseFloat(e.target.value) || 0)}
                  placeholder="Enter discount amount"
                  className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                />
              </div>
            </div>

            {/* Summary */}
            <div className="border-t-2 border-gray-300 pt-4 space-y-2">
              <div className="flex justify-between text-lg">
                <span>Subtotal:</span>
                <span className="font-semibold">{formatCurrency(calculateSubtotal())}</span>
              </div>
              {discount > 0 && (
                <div className="flex justify-between text-red-600">
                  <span>Discount:</span>
                  <span>-{formatCurrency(discount)}</span>
                </div>
              )}
              <div className="flex justify-between text-xl font-bold text-blue-600">
                <span>Total:</span>
                <span>{formatCurrency(calculateTotal())}</span>
              </div>
              <div className="flex justify-between text-gray-600">
                <span>Deposit paid:</span>
                <span>-{formatCurrency(calculateDeposit())}</span>
              </div>
              <div className="flex justify-between text-2xl font-bold text-green-600 pt-2 border-t border-gray-200">
                <span>Remaining payment:</span>
                <span>{formatCurrency(calculateRemaining())}</span>
              </div>
            </div>
          </div>

          {/* Payment Method */}
          <div className="bg-white p-6 rounded-lg shadow-sm">
            <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
              <CreditCard className="w-5 h-5 text-green-600" />
              4. Payment method
            </h2>
            <div className="grid grid-cols-3 gap-4">
              <button
                onClick={() => setPaymentMethod('cash')}
                className={`p-4 border-2 rounded-lg text-center transition-all ${
                  paymentMethod === 'cash'
                    ? 'border-blue-600 bg-blue-50 text-blue-600'
                    : 'border-gray-300 hover:border-gray-400'
                }`}
              >
                <CurrencyIcon className="mx-auto mb-2" size={32} />
                <div className="font-medium">Cash</div>
              </button>
              <button
                onClick={() => setPaymentMethod('stripe')}
                className={`p-4 border-2 rounded-lg text-center transition-all ${
                  paymentMethod === 'stripe'
                    ? 'border-indigo-600 bg-indigo-50 text-indigo-600'
                    : 'border-gray-300 hover:border-gray-400'
                }`}
              >
                <CreditCard className="w-8 h-8 mx-auto mb-2" />
                <div className="font-medium">Stripe</div>
              </button>
            </div>
          </div>

          {/* Action */}
          <div className="bg-gradient-to-r from-green-50 to-emerald-50 p-6 rounded-lg border border-green-200">
            <div className="flex justify-between items-center">
              <div>
                <h3 className="text-lg font-semibold text-gray-900">Confirm check-out</h3>
                <p className="text-sm text-gray-600 mt-1">
                  Total payment: <span className="font-bold text-green-600 text-lg">{formatCurrency(calculateRemaining())}</span>
                </p>
              </div>
              <button
                onClick={handleCheckOut}
                disabled={booking.status !== 'checked_in'}
                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 payment & Check-out
              </button>
            </div>
          </div>
        </>
      )}

      {/* Invoice Display */}
      {showInvoice && booking && (
        <div className="bg-white p-8 rounded-lg shadow-lg">
          <div className="text-center mb-6">
            <h2 className="text-2xl font-bold text-gray-900">PAYMENT INVOICE</h2>
            <p className="text-gray-600 mt-1">Check-out successful</p>
          </div>

          <div className="border-t-2 border-b-2 border-gray-300 py-6 mb-6">
            <div className="grid grid-cols-2 gap-6">
              <div>
                <p className="text-sm text-gray-600">Booking number:</p>
                <p className="font-semibold">{booking.booking_number}</p>
              </div>
              <div>
                <p className="text-sm text-gray-600">Check-out date:</p>
                <p className="font-semibold">{new Date().toLocaleString('en-US')}</p>
              </div>
              <div>
                <p className="text-sm text-gray-600">Customer:</p>
                <p className="font-semibold">{booking.user?.full_name}</p>
              </div>
              <div>
                <p className="text-sm text-gray-600">Payment method:</p>
                <p className="font-semibold">
                  {paymentMethod === 'cash' ? 'Cash' : 'Stripe'}
                </p>
              </div>
            </div>
          </div>

          <div className="mb-6">
            <div className="flex justify-between text-xl font-bold text-green-600 mb-4">
              <span>Total payment:</span>
              <span>{formatCurrency(calculateRemaining())}</span>
            </div>
          </div>

          <div className="flex gap-4">
            <button
              onClick={handlePrintInvoice}
              className="flex-1 px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center justify-center gap-2"
            >
              <Printer className="w-5 h-5" />
              Print invoice
            </button>
            <button
              onClick={resetForm}
              className="flex-1 px-6 py-3 bg-gray-600 text-white rounded-lg hover:bg-gray-700"
            >
              Complete
            </button>
          </div>
        </div>
      )}

      {/* Empty State */}
      {!booking && !searching && !showInvoice && (
        <div className="bg-gray-50 rounded-lg p-12 text-center">
          <Search className="w-16 h-16 text-gray-400 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">
            No booking selected
          </h3>
          <p className="text-gray-600">
            Please enter booking number to start check-out process
          </p>
        </div>
      )}
    </div>
  );
};

export default CheckOutPage;
