import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { api } from '../context/AuthContext';
import { Loader2, CreditCard, Lock, CheckCircle, AlertCircle, ArrowLeft, ChevronRight } from 'lucide-react';
import { loadStripe } from '@stripe/stripe-js';
import { Elements, CardElement, useStripe, useElements } from '@stripe/react-stripe-js';
import toast from 'react-hot-toast';

const stripePromise = loadStripe(process.env.VITE_STRIPE_PUBLISHABLE_KEY || 'pk_test_demo');

function CheckoutForm({ booking, onSuccess }) {
  const stripe = useStripe();
  const elements = useElements();
  const [processing, setProcessing] = useState(false);
  const [error, setError] = useState(null);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!stripe || !elements) return;
    setProcessing(true);
    setError(null);

    const cardElement = elements.getElement(CardElement);
    const { error: cardError, paymentMethod } = await stripe.createPaymentMethod('card', cardElement);

    if (cardError) {
      setError(cardError.message);
      setProcessing(false);
      return;
    }

    try {
      const res = await api.post('/payments/confirm', {
        bookingId: booking._id,
        paymentMethodId: paymentMethod.id
      });
      if (res.data.success) {
        toast.success('Payment successful!');
        onSuccess();
      } else {
        setError(res.data.error || 'Payment failed');
      }
    } catch (err) {
      setError(err.response?.data?.error || 'Payment failed');
    } finally {
      setProcessing(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {error && (
        <div className="p-3 bg-red-50 border border-red-200 rounded-lg flex items-center gap-2 text-red-700 text-sm">
          <AlertCircle className="w-4 h-4" />
          {error}
        </div>
      )}

      <div className="bg-white border border-gray-200 rounded-lg p-4">
        <label className="label mb-2">Card Details</label>
        <CardElement
          options={{
            style: {
              base: { fontSize: '16px', color: '#1f2937', '::placeholder': { color: '#9ca3af' } },
              invalid: { color: '#ef4444', iconColor: '#ef4444' }
            }
          }}
        />
      </div>

      <div className="flex items-center gap-2 text-sm text-gray-500">
        <Lock className="w-4 h-4" />
        <span>Secured by Stripe. We never see your card details.</span>
      </div>

      <button type="submit" disabled={processing || !stripe} className="btn-primary w-full py-3 text-lg">
        {processing ? (
          <>
            <Loader2 className="w-5 h-5 animate-spin mr-2" />
            Processing...
          </>
        ) : (
          `Pay $${(booking.price * 1.1).toFixed(2)}`
        )}
      </button>
    </form>
  );
}

export default function Checkout() {
  const { bookingId } = useParams();
  const navigate = useNavigate();
  const { user } = useAuth();
  const [booking, setBooking] = useState(null);
  const [loading, setLoading] = useState(true);
  const [step, setStep] = useState('payment');

  useEffect(() => {
    api.get(`/bookings/${bookingId}`).then(res => { setBooking(res.data.booking); setLoading(false); }).catch(() => { toast.error('Booking not found'); navigate('/dashboard'); });
  }, [bookingId, navigate]);

  const handleSuccess = () => {
    setStep('success');
    setTimeout(() => navigate('/dashboard'), 3000);
  };

  if (loading) return <div className="min-h-screen flex items-center justify-center"><Loader2 className="w-8 h-8 animate-spin text-primary-600" /></div>;
  if (!booking) return null;
  if (booking.paymentStatus === 'paid') return <div className="min-h-screen flex items-center justify-center"><p>Already paid. <a href="/dashboard" className="text-primary-600">Go to dashboard</a></p></div>;

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="bg-white border-b border-gray-200">
        <div className="container py-4">
          <a href="/dashboard" className="inline-flex items-center gap-2 text-sm text-gray-600 hover:text-primary-600">
            <ArrowLeft className="w-4 h-4" />
            Back to Booking
          </a>
        </div>
      </div>

      <div className="container py-8">
        <div className="grid lg:grid-cols-3 gap-8">
          <div className="lg:col-span-2">
            <div className="card">
              <div className="p-6 border-b border-gray-100">
                <div className="flex items-center gap-2 text-sm text-gray-500">
                  <span className="px-2 py-0.5 bg-primary-100 text-primary-600 rounded text-xs font-medium">Step 1</span>
                  <span className="text-gray-300">Payment</span>
                  <ChevronRight className="w-4 h-4" />
                  <span className="px-2 py-0.5 bg-gray-100 text-gray-500 rounded text-xs font-medium">Step 2</span>
                  <span className="text-gray-500">Confirmation</span>
                </div>
              </div>

              <div className="p-6">
                {step === 'payment' ? (
                  <>
                    <h2 className="text-xl font-bold mb-6">Complete Your Payment</h2>
                    <Elements stripe={stripePromise}>
                      <CheckoutForm booking={booking} onSuccess={handleSuccess} />
                    </Elements>
                  </>
                ) : (
                  <div className="text-center py-12">
                    <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                      <CheckCircle className="w-8 h-8 text-green-600" />
                    </div>
                    <h3 className="text-xl font-bold text-green-700">Payment Successful!</h3>
                    <p className="text-gray-600 mt-2">Your booking is now confirmed. The provider will be notified.</p>
                    <p className="text-sm text-gray-500 mt-4">Redirecting to dashboard...</p>
                  </div>
                )}
              </div>
            </div>
          </div>

          <div className="lg:col-span-1">
            <div className="card p-6 sticky top-24">
              <h3 className="text-lg font-semibold mb-4">Order Summary</h3>
              <div className="space-y-3 mb-4">
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600">{booking.service?.title || 'Service'}</span>
                  <span className="font-medium">${booking.service?.price || booking.price}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600">Platform Fee (10%)</span>
                  <span className="font-medium">${((booking.service?.price || booking.price) * 0.1).toFixed(2)}</span>
                </div>
                <div className="border-t border-gray-100 pt-3">
                  <div className="flex justify-between font-semibold text-lg">
                    <span>Total</span>
                    <span className="text-primary-600">${((booking.service?.price || booking.price) * 1.1).toFixed(2)}</span>
                  </div>
                </div>
              </div>

              <div className="pt-4 border-t border-gray-100 space-y-3 text-sm">
                <div className="flex items-center gap-2 text-gray-600">
                  <Lock className="w-4 h-4 text-primary-600" />
                  <span>Secure SSL encryption</span>
                </div>
                <div className="flex items-center gap-2 text-gray-600">
                  <CreditCard className="w-4 h-4 text-primary-600" />
                  <span>Visa, Mastercard, Amex</span>
                </div>
                <div className="flex items-center gap-2 text-gray-600">
                  <CheckCircle className="w-4 h-4 text-green-500" />
                  <span>No hidden fees</span>
                </div>
              </div>

              <div className="mt-6 p-4 bg-gray-50 rounded-lg text-sm">
                <p className="text-gray-600"><strong>Booking:</strong> {booking.service?.title}</p>
                <p className="text-gray-600"><strong>Date:</strong> {new Date(booking.scheduledAt).toLocaleDateString()}</p>
                <p className="text-gray-600"><strong>Provider:</strong> {booking.provider?.name}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}