import React, { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { useInventory } from '../hooks/useInventory';
import { ordersAPI } from '../utils/api';
import Logo from '../components/Logo';
import { 
  ArrowLeft, 
  Calendar, 
  Clock, 
  Package, 
  CheckCircle,
  Loader2,
  MapPin,
  User,
  Mail
} from 'lucide-react';

interface CartItem {
  id: string;
  name: string;
  quantity: number;
  unit?: string;
  imageUrl?: string;
  categoryId?: string;
}

const Checkout: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { user } = useAuth();
  const { categories, refetch: refetchInventory } = useInventory();
  
  // Get cart items from location state
  const cartItems: CartItem[] = location.state?.cartItems || [];
  
  const [selectedDate, setSelectedDate] = useState('');
  const [selectedTime, setSelectedTime] = useState('10:00 AM');
  const [notes, setNotes] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  // Generate available dates (next 7 days, Monday-Friday)
  const getAvailableDates = () => {
    const dates = [];
    const today = new Date();
    
    for (let i = 1; i <= 14; i++) {
      const date = new Date(today);
      date.setDate(today.getDate() + i);
      
      // Only include weekdays (Monday = 1, Friday = 5)
      if (date.getDay() >= 1 && date.getDay() <= 5) {
        dates.push({
          value: date.toISOString().split('T')[0],
          label: date.toLocaleDateString('en-US', { 
            weekday: 'long', 
            year: 'numeric', 
            month: 'long', 
            day: 'numeric' 
          })
        });
      }
    }
    
    return dates;
  };

  const availableTimeSlots = [
    '10:00 AM',
    '11:00 AM', 
    '12:00 PM',
    '1:00 PM',
    '2:00 PM',
    '3:00 PM'
  ];

  const getCategoryName = (categoryId?: string) => {
    if (!categoryId) return 'Uncategorized';
    const cat = categories.find(c => c.id === categoryId);
    return cat?.name || 'Uncategorized';
  };

  // yyyy-mm-dd + "10:00 AM" -> ISO string (local)
  const toISOFromDateAndTime = (yyyyMmDd: string, timeLabel: string) => {
    // timeLabel like "10:00 AM"
    const [time, meridiem] = timeLabel.split(' ');
    let [hh, mm] = time.split(':').map(Number);
    if (meridiem === 'PM' && hh !== 12) hh += 12;
    if (meridiem === 'AM' && hh === 12) hh = 0;

    const [y, m, d] = yyyyMmDd.split('-').map(Number);
    const dt = new Date(y, m - 1, d, hh, mm, 0, 0);
    return dt.toISOString();
  };

  const handleCheckout = async () => {
    if (!selectedDate) {
      setError('Please select a pickup date');
      return;
    }

    if (!selectedTime) {
      setError('Please select a pickup time');
      return;
    }

    if (cartItems.length === 0) {
      setError('Your cart is empty');
      return;
    }

    setLoading(true);
    setError('');

    try {

      // Turn the selected date/time into ISO
      const pickupAtISO = toISOFromDateAndTime(selectedDate, selectedTime);

      // Create order with cart items
      const orderData = {
        name: `Pickup Order - ${selectedDate}`,
        quantity: cartItems.reduce((sum, item) => sum + item.quantity, 0),
        unit: `${selectedDate} at ${selectedTime}`,
        priority: pickupAtISO,
        notes: `Items: ${cartItems.map(item => `${item.quantity}x ${item.name}`).join(', ')}${notes ? `\nNotes: ${notes}` : ''}`,
        cartItems
      };

      // 1. Create the order only once
      const createResp = await ordersAPI.create(orderData);
      const orderId = createResp?.order?.id || createResp?.id;
      if (!orderId) throw new Error('Order ID missing from create response');

      // 2. Call the schedule endpoint to trigger the email
      await ordersAPI.schedule(String(orderId), {
        pickupAtISO,
        // make user-selectable later
        pickupLocation: 'Campus Pantry'
      });

      // Refresh inventory to reflect deducted quantities
      await refetchInventory();
      // Navigate back to user dashboard with success message
      navigate('/user-dashboard', {
        state: {
          message: 'Order placed! You’ll get a confirmation email with pickup details.',
          orderPlaced: true
        }
      });
    } catch (err: any) {
      setError(err.message || 'Failed to place order. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const goBack = () => {
    navigate('/user-dashboard', { state: { returnToInventory: true } });
  };

  if (cartItems.length === 0) {
    return (
      <div className="min-h-screen">
        <header className="bg-white/90 backdrop-blur border-b border-light-gray shadow-soft">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex items-center py-4">
              <Logo size="md" showText={false} />
              <h1 className="text-2xl font-bold text-deep-forest ml-4">Checkout</h1>
            </div>
          </div>
        </header>
        
        <main className="max-w-4xl mx-auto py-8 px-4">
          <div className="glass-card p-8 text-center">
            <Package className="h-16 w-16 text-secondary-text mx-auto mb-4 opacity-50" />
            <h2 className="text-xl font-semibold text-deep-forest mb-2">Your cart is empty</h2>
            <p className="text-secondary-text mb-6">Add some items to your cart before checkout.</p>
            <button 
              onClick={goBack}
              className="px-6 py-2 bg-btn-primary text-white rounded-lg hover:bg-btn-primary-hover transition-colors font-medium"
            >
              Continue Shopping
            </button>
          </div>
        </main>
      </div>
    );
  }

  return (
    <div className="min-h-screen">
      {/* Header */}
      <header className="bg-white/90 backdrop-blur border-b border-light-gray shadow-soft">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center py-4">
            <Logo size="md" showText={false} />
            <h1 className="text-2xl font-bold text-deep-forest ml-4">Checkout</h1>
          </div>
        </div>
      </header>

      <main className="max-w-4xl mx-auto py-8 px-4">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          
          {/* Order Summary */}
          <div className="space-y-6">
            <div className="glass-card p-6">
              <h2 className="text-lg font-semibold text-deep-forest mb-4 flex items-center">
                <Package className="h-5 w-5 mr-2 text-primary-green" />
                Order Summary
              </h2>
              
              <div className="space-y-4">
                {cartItems.map((item) => (
                  <div key={item.id} className="flex items-center space-x-4 p-3 bg-card-hover rounded-lg border border-light-gray">
                    <div className="w-12 h-12 rounded-lg overflow-hidden bg-gray-100 flex items-center justify-center">
                      {item.imageUrl ? (
                        <img 
                          src={item.imageUrl} 
                          alt={item.name}
                          className="w-full h-full object-cover"
                          onError={(e) => {
                            e.currentTarget.style.display = 'none';
                            e.currentTarget.parentElement!.innerHTML = '📦';
                            e.currentTarget.parentElement!.classList.add('text-xl', 'flex', 'items-center', 'justify-center');
                          }}
                        />
                      ) : (
                        <span className="text-xl">📦</span>
                      )}
                    </div>
                    <div className="flex-1">
                      <h4 className="font-medium text-primary-text">{item.name}</h4>
                      <p className="text-sm text-secondary-text">{getCategoryName(item.categoryId)}</p>
                    </div>
                    <div className="text-right">
                      <p className="font-semibold text-primary-text">{item.quantity} {item.unit || 'units'}</p>
                    </div>
                  </div>
                ))}
              </div>
              
              <div className="mt-4 pt-4 border-t border-light-gray">
                <div className="flex justify-between items-center">
                  <span className="font-semibold text-deep-forest">Total Items:</span>
                  <span className="font-bold text-primary-green text-lg">
                    {cartItems.reduce((sum, item) => sum + item.quantity, 0)} items
                  </span>
                </div>
              </div>
            </div>

            {/* Pickup Information */}
            <div className="glass-card p-6">
              <h2 className="text-lg font-semibold text-deep-forest mb-4 flex items-center">
                <MapPin className="h-5 w-5 mr-2 text-primary-green" />
                Pickup Information
              </h2>
              
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-primary-text mb-2">
                    <Calendar className="h-4 w-4 inline mr-1" />
                    Pickup Date *
                  </label>
                  <select
                    value={selectedDate}
                    onChange={(e) => setSelectedDate(e.target.value)}
                    className="w-full px-3 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text"
                  >
                    <option value="">Select a date</option>
                    {getAvailableDates().map((date) => (
                      <option key={date.value} value={date.value}>
                        {date.label}
                      </option>
                    ))}
                  </select>
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-primary-text mb-2">
                    <Clock className="h-4 w-4 inline mr-1" />
                    Pickup Time *
                  </label>
                  <select
                    value={selectedTime}
                    onChange={(e) => setSelectedTime(e.target.value)}
                    className="w-full px-3 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text"
                  >
                    {availableTimeSlots.map((time) => (
                      <option key={time} value={time}>
                        {time}
                      </option>
                    ))}
                  </select>
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-primary-text mb-2">
                    Additional Notes (Optional)
                  </label>
                  <textarea
                    value={notes}
                    onChange={(e) => setNotes(e.target.value)}
                    placeholder="Any special instructions or notes..."
                    rows={3}
                    className="w-full px-3 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text resize-none"
                  />
                </div>
              </div>
            </div>
          </div>

          {/* User Information & Confirmation */}
          <div className="space-y-6">
            <div className="glass-card p-6">
              <h2 className="text-lg font-semibold text-deep-forest mb-4 flex items-center">
                <User className="h-5 w-5 mr-2 text-primary-green" />
                Contact Information
              </h2>
              
              <div className="space-y-3">
                <div className="flex items-center">
                  <User className="h-4 w-4 text-secondary-text mr-3" />
                  <span className="text-primary-text">{user?.fullName || 'User'}</span>
                </div>
                <div className="flex items-center">
                  <Mail className="h-4 w-4 text-secondary-text mr-3" />
                  <span className="text-primary-text">{user?.email}</span>
                </div>
              </div>
            </div>

            <div className="bg-green-50 border border-fresh rounded-xl p-6">
              <h3 className="font-semibold text-deep-forest mb-3 flex items-center">
                <CheckCircle className="h-5 w-5 mr-2 text-primary-green" />
                What happens next?
              </h3>
              <ul className="space-y-2 text-sm text-primary-text">
                <li>• You'll receive a confirmation email with pickup details</li>
                <li>• Items will be reserved for your selected pickup time</li>
                <li>• Bring a valid ID when you arrive for pickup</li>
                <li>• Items will be held for 24 hours after your scheduled time</li>
              </ul>
            </div>

            {error && (
              <div className="bg-warning/10 border border-warning text-warning px-4 py-3 rounded-lg text-sm">
                {error}
              </div>
            )}

            <div className="space-y-3">
              <button
                onClick={handleCheckout}
                disabled={loading || !selectedDate || !selectedTime}
                className="w-full bg-btn-primary text-white py-3 rounded-lg hover:bg-btn-primary-hover active:bg-btn-primary-active transition-colors font-medium text-lg shadow-sm disabled:opacity-50 flex items-center justify-center"
              >
                {loading ? (
                  <>
                    <Loader2 className="h-5 w-5 mr-2 animate-spin" />
                    Processing Order...
                  </>
                ) : (
                  'Place Order'
                )}
              </button>
              
              <button
                onClick={goBack}
                className="w-full border-2 border-light-gray text-primary-text py-3 rounded-lg hover:bg-card-hover hover:border-primary-green transition-colors font-medium flex items-center justify-center"
              >
                <ArrowLeft className="h-4 w-4 mr-2" />
                Back to Shopping
              </button>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
};

export default Checkout;
