'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { loadStripe } from '@stripe/stripe-js';
import { Elements, PaymentElement, useStripe, useElements } from '@stripe/react-stripe-js';
import { Button } from '@/components/ui/button';
import { useCart } from '@/lib/queries/use-cart';
import { api } from '@/lib/api';
import type { CheckoutData, CheckoutConflict, ShippingAddress } from '@alqove/api-client';

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

function formatPrice(cents: number): string {
  return `$${(cents / 100).toFixed(2)}`;
}

// Inner payment form component (needs to be inside <Elements>)
function PaymentForm({ checkout, onCancel }: { checkout: CheckoutData; onCancel: () => void }) {
  const stripe = useStripe();
  const elements = useElements();
  const [paying, setPaying] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handlePay = async () => {
    if (!stripe || !elements) return;
    setPaying(true);
    setError(null);

    const result = await stripe.confirmPayment({
      elements,
      confirmParams: {
        return_url: `${window.location.origin}/purchases`,
      },
    });

    if (result.error) {
      setError(result.error.message || 'Payment failed.');
      setPaying(false);
    }
  };

  return (
    <div>
      <div className="bg-white rounded-lg border border-slate-200 p-5 mb-4">
        <h2 className="font-semibold text-base mb-4">Payment</h2>
        <PaymentElement />
        {error && <p className="text-sm text-red-500 mt-3">{error}</p>}
      </div>

      <div className="sticky top-6 bg-white rounded-lg border border-slate-200 p-5">
        <h2 className="font-bold text-base mb-4">Payment Summary</h2>
        <div className="space-y-2 text-sm">
          <div className="flex justify-between">
            <span className="text-slate-500">Subtotal</span>
            <span>{formatPrice(checkout.subtotal)}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-slate-500">Shipping</span>
            <span>{formatPrice(checkout.shipping_total)}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-slate-500">Discount</span>
            <span className="text-slate-400">&mdash;</span>
          </div>
        </div>
        <div className="border-t-2 border-slate-900 mt-3 pt-3 flex justify-between font-bold text-lg">
          <span>Total</span>
          <span>{formatPrice(checkout.total)}</span>
        </div>
        <Button
          className="w-full mt-5 bg-green-600 hover:bg-green-700"
          size="lg"
          onClick={handlePay}
          disabled={paying || !stripe}
        >
          {paying ? 'Processing...' : `Pay ${formatPrice(checkout.total)}`}
        </Button>
        <button
          onClick={onCancel}
          className="w-full mt-2 py-2 text-sm text-red-500 border border-red-200 rounded-lg hover:bg-red-50"
        >
          Cancel Checkout
        </button>
        <p className="mt-3 text-xs text-slate-400 text-center">Items are held for 10 minutes during checkout</p>
      </div>
    </div>
  );
}

export function CheckoutClient() {
  const router = useRouter();
  const { data: cartResponse, isLoading } = useCart();
  const [step, setStep] = useState<'address' | 'payment'>('address');
  const [checkout, setCheckout] = useState<CheckoutData | null>(null);
  const [conflict, setConflict] = useState<CheckoutConflict | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [address, setAddress] = useState<ShippingAddress>({
    first_name: '',
    last_name: '',
    street: '',
    city: '',
    state: '',
    zip: '',
  });

  const cart = cartResponse?.data;

  const handleAddressChange = (field: keyof ShippingAddress, value: string) => {
    setAddress((prev) => ({ ...prev, [field]: value }));
  };

  const handleInitiateCheckout = async (excludedItemIds: string[] = []) => {
    setSubmitting(true);
    setConflict(null);
    try {
      const response = await api.checkout.initiate(address, excludedItemIds);
      setCheckout(response.data);
      setStep('payment');
    } catch (err: unknown) {
      const conflict = err as CheckoutConflict;
      if (conflict?.error === 'items_unavailable') {
        setConflict(conflict);
      } else {
        const apiErr = err as { message?: string };
        alert(apiErr?.message || 'Checkout failed. Please try again.');
      }
    } finally {
      setSubmitting(false);
    }
  };

  const handleCancelCheckout = async () => {
    if (checkout) {
      try {
        await api.checkout.cancel(checkout.checkout_id);
      } catch {
        // Best effort
      }
    }
    router.push('/cart');
  };

  if (isLoading) {
    return (
      <div className="mx-auto max-w-7xl px-4 py-8">
        <div className="animate-pulse space-y-4">
          <div className="h-8 w-48 rounded bg-slate-200" />
          <div className="h-96 rounded bg-slate-200" />
        </div>
      </div>
    );
  }

  if (!cart || cart.item_count === 0) {
    return (
      <div className="mx-auto max-w-7xl px-4 py-16 text-center">
        <h1 className="text-2xl font-bold text-slate-900">Your cart is empty</h1>
        <p className="mt-2 text-slate-500">Add items to your cart before checking out.</p>
        <Button className="mt-6" onClick={() => router.push('/items')}>
          Browse Items
        </Button>
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-7xl px-4 py-8">
      <h1 className="text-2xl font-bold text-slate-900 mb-6">Checkout</h1>

      {/* Partial availability modal */}
      {conflict && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
          <div className="bg-white rounded-xl p-6 max-w-md w-full mx-4 shadow-xl">
            <h2 className="text-lg font-bold mb-1">Some items are no longer available</h2>
            <p className="text-sm text-slate-500 mb-4">The following items were sold while you were shopping:</p>
            {conflict.unavailable_items.map((item) => (
              <div key={item.id} className="bg-red-50 border border-red-200 rounded-lg p-3 mb-3 flex gap-3">
                <div>
                  <div className="font-semibold text-sm line-through text-slate-400">{item.title}</div>
                  <div className="text-xs text-red-500 mt-0.5">No longer available</div>
                </div>
              </div>
            ))}
            <div className="bg-slate-50 rounded-lg p-3 mb-4">
              <div className="text-sm font-semibold mb-2">Updated totals:</div>
              <div className="flex justify-between text-sm mb-1">
                <span className="text-slate-500">Remaining items ({conflict.available_items.length})</span>
                <span>{formatPrice(conflict.updated_totals.subtotal)}</span>
              </div>
              <div className="flex justify-between text-sm mb-1">
                <span className="text-slate-500">Shipping</span>
                <span>{formatPrice(conflict.updated_totals.shipping_total)}</span>
              </div>
              <div className="flex justify-between text-sm font-bold mt-2 pt-2 border-t border-slate-200">
                <span>New Total</span>
                <span>{formatPrice(conflict.updated_totals.total)}</span>
              </div>
            </div>
            <div className="flex gap-3">
              <Button
                variant="outline"
                className="flex-1"
                onClick={() => {
                  setConflict(null);
                  router.push('/cart');
                }}
              >
                Back to Cart
              </Button>
              <Button
                className="flex-1"
                onClick={() => {
                  const excludedIds = conflict.unavailable_items.map((i) => i.id);
                  setConflict(null);
                  handleInitiateCheckout(excludedIds);
                }}
              >
                Continue with {formatPrice(conflict.updated_totals.total)}
              </Button>
            </div>
          </div>
        </div>
      )}

      <div className="flex gap-8">
        <div className="flex-1">
          {step === 'address' && (
            <>
              {/* Shipping Address Form */}
              <div className="bg-white rounded-lg border border-slate-200 p-5 mb-4">
                <h2 className="font-semibold text-base mb-4">Shipping Address</h2>
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-xs text-slate-500 mb-1">First Name</label>
                    <input
                      className="w-full rounded-md border border-slate-300 px-3 py-2 text-sm"
                      value={address.first_name}
                      onChange={(e) => handleAddressChange('first_name', e.target.value)}
                    />
                  </div>
                  <div>
                    <label className="block text-xs text-slate-500 mb-1">Last Name</label>
                    <input
                      className="w-full rounded-md border border-slate-300 px-3 py-2 text-sm"
                      value={address.last_name}
                      onChange={(e) => handleAddressChange('last_name', e.target.value)}
                    />
                  </div>
                  <div className="col-span-2">
                    <label className="block text-xs text-slate-500 mb-1">Street Address</label>
                    <input
                      className="w-full rounded-md border border-slate-300 px-3 py-2 text-sm"
                      value={address.street}
                      onChange={(e) => handleAddressChange('street', e.target.value)}
                    />
                  </div>
                  <div>
                    <label className="block text-xs text-slate-500 mb-1">City</label>
                    <input
                      className="w-full rounded-md border border-slate-300 px-3 py-2 text-sm"
                      value={address.city}
                      onChange={(e) => handleAddressChange('city', e.target.value)}
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-xs text-slate-500 mb-1">State</label>
                      <input
                        className="w-full rounded-md border border-slate-300 px-3 py-2 text-sm"
                        maxLength={2}
                        value={address.state}
                        onChange={(e) => handleAddressChange('state', e.target.value)}
                      />
                    </div>
                    <div>
                      <label className="block text-xs text-slate-500 mb-1">ZIP</label>
                      <input
                        className="w-full rounded-md border border-slate-300 px-3 py-2 text-sm"
                        value={address.zip}
                        onChange={(e) => handleAddressChange('zip', e.target.value)}
                      />
                    </div>
                  </div>
                </div>
              </div>

              {/* Per-store order details */}
              <div className="bg-white rounded-lg border border-slate-200 p-5">
                <h2 className="font-semibold text-base mb-4">Order Details</h2>
                {cart.stores.map((sg, idx) => (
                  <div key={sg.store.id} className={idx > 0 ? 'border-t border-slate-200 pt-4 mt-4' : ''}>
                    <div className="flex items-center gap-2 mb-2">
                      <div className="h-6 w-6 rounded-full bg-forest-600 flex items-center justify-center text-[10px] font-semibold text-white">
                        {sg.store.name.charAt(0)}
                      </div>
                      <span className="font-semibold text-sm">{sg.store.name}</span>
                    </div>
                    <div className="pl-8 text-sm text-slate-600 space-y-1">
                      {sg.items.map((ci) => (
                        <div key={ci.id} className="flex justify-between">
                          <span>{ci.item.title}</span>
                          <span>{formatPrice(ci.item.price)}</span>
                        </div>
                      ))}
                      <div className="flex justify-between text-slate-400 pt-1 mt-1 border-t border-slate-100">
                        <span>Shipping</span>
                        <span>{formatPrice(sg.shipping)}</span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </>
          )}

          {step === 'payment' && checkout && (
            <Elements stripe={stripePromise} options={{ clientSecret: checkout.client_secret }}>
              <PaymentForm checkout={checkout} onCancel={handleCancelCheckout} />
            </Elements>
          )}
        </div>

        {/* Right sidebar — only show in address step */}
        {step === 'address' && (
          <div className="w-80 flex-shrink-0">
            <div className="sticky top-6 bg-white rounded-lg border border-slate-200 p-5">
              <h2 className="font-bold text-base mb-4">Order Summary</h2>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-slate-500">Subtotal</span>
                  <span>{formatPrice(cart.subtotal)}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-500">Shipping</span>
                  <span>{formatPrice(cart.shipping_total)}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-500">Discount</span>
                  <span className="text-slate-400">&mdash;</span>
                </div>
              </div>
              <div className="border-t-2 border-slate-900 mt-3 pt-3 flex justify-between font-bold text-lg">
                <span>Total</span>
                <span>{formatPrice(cart.total)}</span>
              </div>
              <Button
                className="w-full mt-5"
                size="lg"
                onClick={() => handleInitiateCheckout()}
                disabled={
                  submitting ||
                  !address.first_name ||
                  !address.last_name ||
                  !address.street ||
                  !address.city ||
                  !address.state ||
                  !address.zip
                }
              >
                {submitting ? 'Processing...' : 'Continue to Payment'}
              </Button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
