'use client';

import { useEffect, useState, useCallback } from 'react';
import Link from 'next/link';
import { useCart } from '@/lib/cartStore';
import { loginCustomer } from '@/app/account/actions';
import Price from '@/components/Price';
import ShippingSelector from '@/components/ShippingSelector';

interface CheckoutPageClientProps {
  isLoggedIn: boolean;
  customer?: any;
  customerAddress?: any;
}

export default function CheckoutPageClient({ isLoggedIn, customer, customerAddress }: CheckoutPageClientProps) {
  const [mounted, setMounted] = useState(false);
  const [mode, setMode] = useState<'logged-in' | 'login' | 'guest' | 'edit-address' | null>(isLoggedIn ? 'logged-in' : null);
  const [checkingOut, setCheckingOut] = useState(false);
  const [checkoutError, setCheckoutError] = useState<string | null>(null);
  const [deliveryMode, setDeliveryMode] = useState<'shipping' | 'collection'>('shipping');
  const [shippingCountry, setShippingCountry] = useState(customerAddress?.country || 'GB');
  const [shippingService, setShippingService] = useState<string | null>(null);
  const [shippingCost, setShippingCost] = useState(0);
  const [guestData, setGuestData] = useState({
    fullName: '',
    email: '',
    phone: '',
    address: '',
  });
  const [customerAddressData, setCustomerAddressData] = useState({
    phone: customerAddress?.phone || '',
    addressLine1: customerAddress?.addressLine1 || '',
    addressLine2: customerAddress?.addressLine2 || '',
    city: customerAddress?.city || '',
    postalCode: customerAddress?.postalCode || '',
    country: customerAddress?.country || 'GB',
  });

  const items = useCart((s) => s.items);
  const removeItem = useCart((s) => s.removeItem);
  const setQuantity = useCart((s) => s.setQuantity);
  const subtotal = useCart((s) => s.total());
  const total = subtotal + shippingCost;

  const handleShippingSelect = useCallback((country: string, service: string, cost: number) => {
    setShippingCountry(country);
    setShippingService(service);
    setShippingCost(cost);
  }, []);

  useEffect(() => setMounted(true), []);

  if (!mounted) return null;

  if (items.length === 0) {
    return (
      <div className="mx-auto max-w-md px-6 py-16 text-center">
        <h1 className="font-display text-3xl">Checkout</h1>
        <p className="mt-4 text-sm text-muted">Your bag is empty.</p>
        <Link
          href="/products"
          className="mt-6 inline-block bg-clay px-6 py-3 text-sm font-medium text-paper hover:bg-clay-dark"
        >
          Continue shopping
        </Link>
      </div>
    );
  }

  const handleGuestCheckout = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!guestData.fullName || !guestData.email || !guestData.phone || !guestData.address) {
      setCheckoutError('Please fill in all fields.');
      return;
    }
    if (deliveryMode === 'shipping' && !shippingService) {
      setCheckoutError('Please select a shipping method.');
      return;
    }

    setCheckingOut(true);
    setCheckoutError(null);
    try {
      // Mark that we're checking out so LogoutOnUnload doesn't clear cart
      if (typeof window !== 'undefined') {
        sessionStorage.setItem('isCheckingOut', 'true');
      }

      const res = await fetch('/api/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          items,
          guest: {
            name: guestData.fullName,
            email: guestData.email,
            phone: guestData.phone,
            address: guestData.address,
          },
          shippingCountry: deliveryMode === 'collection' ? null : shippingCountry,
          shippingService: deliveryMode === 'collection' ? null : shippingService,
          isCollection: deliveryMode === 'collection',
        }),
      });
      const data = await res.json();
      if (!res.ok || !data.url) {
        if (typeof window !== 'undefined') {
          sessionStorage.removeItem('isCheckingOut');
        }
        throw new Error(data.error ?? 'Something went wrong starting checkout.');
      }
      window.location.href = data.url;
    } catch (err) {
      setCheckoutError(err instanceof Error ? err.message : 'Something went wrong.');
      setCheckingOut(false);
    }
  };

  return (
    <div className="mx-auto max-w-2xl px-6 py-16">
      <div className="flex items-baseline justify-between">
        <h1 className="font-display text-3xl">Checkout</h1>
        <Link
          href="/products"
          className="text-sm text-clay hover:text-clay-dark"
        >
          ← Continue shopping
        </Link>
      </div>

      <div className="mt-8 grid gap-8 md:grid-cols-2">
        {/* Order summary */}
        <div>
          <h2 className="font-display text-lg">Order summary</h2>
          <div className="mt-4 space-y-4 border-t border-line pt-4">
            {items.map((item) => (
              <div key={item.cartItemId} className="flex justify-between items-start text-sm">
                <div>
                  <p className="font-medium">{item.name}</p>
                  <div className="flex items-center gap-2 mt-2 border border-ink w-fit">
                    <button
                      onClick={() => setQuantity(item.cartItemId, item.quantity - 1)}
                      disabled={item.quantity <= 1}
                      className="px-2 py-1 text-xs disabled:opacity-40"
                    >
                      −
                    </button>
                    <span className="w-6 text-center text-xs font-mono">{item.quantity}</span>
                    <button
                      onClick={() => setQuantity(item.cartItemId, item.quantity + 1)}
                      className="px-2 py-1 text-xs hover:bg-surface"
                    >
                      +
                    </button>
                  </div>
                  <button
                    onClick={() => removeItem(item.cartItemId)}
                    className="mt-2 text-xs text-splash-pink hover:text-splash-pink-dark"
                  >
                    Remove
                  </button>
                </div>
                <Price cents={item.unitPrice * item.quantity} className="font-mono" />
              </div>
            ))}
          </div>
          <div className="mt-4 border-t border-line pt-4 space-y-2">
            <div className="flex justify-between text-sm">
              <span>Subtotal</span>
              <Price cents={subtotal} className="font-mono" />
            </div>
            {shippingCost > 0 && (
              <div className="flex justify-between text-sm">
                <span>Shipping ({shippingService})</span>
                <Price cents={shippingCost} className="font-mono" />
              </div>
            )}
            <div className="flex justify-between font-display text-lg pt-2 border-t border-line">
              <span>Total</span>
              <Price cents={total} className="font-mono" />
            </div>
          </div>
        </div>

        {/* Checkout options */}
        <div>
          {mode === 'logged-in' ? (
            <div className="space-y-6">
              <div>
                <h3 className="font-display text-lg">Ready to checkout</h3>
                <p className="mt-2 text-sm text-muted">Logged in as {customer?.email}</p>
              </div>

              <div className="space-y-3 border border-line bg-surface p-4">
                <p className="font-medium text-sm">Delivery address</p>
                {customerAddressData.addressLine1 ? (
                  <div className="text-sm text-muted space-y-1">
                    <p>{customerAddressData.addressLine1}</p>
                    {customerAddressData.addressLine2 && <p>{customerAddressData.addressLine2}</p>}
                    <p>{customerAddressData.city}, {customerAddressData.postalCode}</p>
                    <p className="text-xs mt-2">Phone: {customerAddressData.phone}</p>
                  </div>
                ) : (
                  <p className="text-sm text-splash-orange">No address saved. Please add one below.</p>
                )}
                <button
                  type="button"
                  onClick={() => setMode('edit-address')}
                  className="text-sm text-clay hover:text-clay-dark"
                >
                  {customerAddressData.addressLine1 ? 'Edit address' : 'Add address'}
                </button>
              </div>

              <div>
                <p className="font-medium text-sm mb-3">Delivery</p>
                <div className="inline-flex border border-line">
                  <button
                    type="button"
                    onClick={() => {
                      setDeliveryMode('shipping');
                      setShippingCost(0);
                      setShippingService(null);
                    }}
                    className={`px-4 py-2 text-sm transition-colors ${
                      deliveryMode === 'shipping'
                        ? 'bg-ink text-paper'
                        : 'hover:bg-surface'
                    }`}
                  >
                    Shipping
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      setDeliveryMode('collection');
                      setShippingCost(0);
                      setShippingService(null);
                    }}
                    className={`px-4 py-2 text-sm transition-colors border-l border-line ${
                      deliveryMode === 'collection'
                        ? 'bg-ink text-paper'
                        : 'hover:bg-surface'
                    }`}
                  >
                    Collection
                  </button>
                </div>
              </div>

              {deliveryMode === 'shipping' && (
                <ShippingSelector
                  items={items}
                  onShippingSelect={handleShippingSelect}
                />
              )}

              {deliveryMode === 'collection' && (
                <div className="bg-surface p-4 rounded border border-line">
                  <p className="text-sm text-muted">✓ Free collection pickup - no postage charge</p>
                </div>
              )}

              <button
                onClick={async () => {
                  if (deliveryMode === 'shipping' && !shippingService) {
                    setCheckoutError('Please select a shipping method.');
                    return;
                  }

                  console.log('💳 Checkout button clicked, cart items:', items.length);
                  setCheckingOut(true);
                  setCheckoutError(null);
                  try {
                    // Mark that we're checking out so LogoutOnUnload doesn't clear cart
                    if (typeof window !== 'undefined') {
                      sessionStorage.setItem('isCheckingOut', 'true');
                      console.log('✓ Set isCheckingOut flag in sessionStorage');
                    }

                    console.log('📡 Fetching /api/checkout with', items.length, 'items');
                    console.log('📦 Cart items:', JSON.stringify(items, null, 2));
                    const res = await fetch('/api/checkout', {
                      method: 'POST',
                      headers: { 'Content-Type': 'application/json' },
                      body: JSON.stringify({
                        items,
                        customerId: customer.id,
                        shippingCountry: deliveryMode === 'collection' ? null : shippingCountry,
                        shippingService: deliveryMode === 'collection' ? null : shippingService,
                        isCollection: deliveryMode === 'collection',
                      }),
                    });
                    const data = await res.json();
                    console.log('📦 Checkout response:', { status: res.status, ok: res.ok, hasUrl: !!data.url });
                    if (!res.ok || !data.url) {
                      if (typeof window !== 'undefined') {
                        sessionStorage.removeItem('isCheckingOut');
                      }
                      throw new Error(data.error ?? 'Something went wrong starting checkout.');
                    }
                    console.log('🔗 Redirecting to Stripe');
                    window.location.href = data.url;
                  } catch (err) {
                    const errorMsg = err instanceof Error ? err.message : 'Something went wrong.';
                    console.error('Checkout error:', errorMsg);
                    setCheckoutError(errorMsg);
                    setCheckingOut(false);
                  }
                }}
                disabled={checkingOut}
                className="mt-4 w-full bg-clay px-6 py-3 text-sm font-medium text-paper transition-colors hover:bg-clay-dark disabled:opacity-60"
              >
                {checkingOut ? 'Processing…' : 'Continue to payment'}
              </button>
              {checkoutError && (
                <p className="mt-4 border border-splash-pink/40 bg-splash-pink/10 px-4 py-3 text-sm text-splash-pink">
                  {checkoutError}
                </p>
              )}
            </div>
          ) : mode === null ? (
            <div className="space-y-3">
              <p className="text-sm text-muted">How would you like to checkout?</p>
              <button
                onClick={() => setMode('login')}
                className="w-full border-2 border-ink px-6 py-3 text-sm font-medium text-ink hover:border-clay hover:bg-clay hover:text-paper"
              >
                Log in to existing account
              </button>
              <button
                onClick={() => setMode('guest')}
                className="w-full bg-clay px-6 py-3 text-sm font-medium text-paper hover:bg-clay-dark"
              >
                Continue as guest
              </button>
              <p className="text-xs text-muted">
                Don&apos;t have an account?{' '}
                <Link href="/account/register" className="text-clay hover:text-clay-dark">
                  Create one now
                </Link>
              </p>
            </div>
          ) : mode === 'login' ? (
            <div>
              <button
                onClick={() => setMode(null)}
                className="text-sm text-clay hover:text-clay-dark mb-4"
              >
                ← Back
              </button>
              <h3 className="font-display text-lg">Log in</h3>
              <form action={loginCustomer} className="mt-4 space-y-4">
                <input type="hidden" name="next" value="/checkout" />
                <div>
                  <label htmlFor="email" className="tag-label mb-2 block">
                    Email
                  </label>
                  <input
                    id="email"
                    name="email"
                    type="email"
                    required
                    className="w-full border border-line px-3 py-2 text-sm"
                  />
                </div>
                <div>
                  <label htmlFor="password" className="tag-label mb-2 block">
                    Password
                  </label>
                  <input
                    id="password"
                    name="password"
                    type="password"
                    required
                    className="w-full border border-line px-3 py-2 text-sm"
                  />
                </div>
                <button type="submit" className="w-full bg-clay px-6 py-3 text-sm font-medium text-paper hover:bg-clay-dark">
                  Log in
                </button>
              </form>
            </div>
          ) : mode === 'edit-address' ? (
            <div>
              <button
                onClick={() => setMode('logged-in')}
                className="text-sm text-clay hover:text-clay-dark mb-4"
              >
                ← Back
              </button>
              <h3 className="font-display text-lg">Edit delivery address</h3>
              <form className="mt-4 space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label htmlFor="phone-edit" className="tag-label mb-2 block">
                      Phone number
                    </label>
                    <input
                      id="phone-edit"
                      type="tel"
                      required
                      value={customerAddressData.phone}
                      onChange={(e) => setCustomerAddressData({ ...customerAddressData, phone: e.target.value })}
                      className="w-full border border-line px-3 py-2 text-sm"
                      placeholder="e.g. +44 7700 900000"
                    />
                  </div>
                  <div>
                    <label htmlFor="country-edit" className="tag-label mb-2 block">
                      Country
                    </label>
                    <select
                      id="country-edit"
                      value={customerAddressData.country}
                      onChange={(e) => {
                        setCustomerAddressData({ ...customerAddressData, country: e.target.value });
                        setShippingCountry(e.target.value);
                      }}
                      className="w-full border border-line bg-paper px-3 py-2 text-sm"
                    >
                      <option value="GB">United Kingdom</option>
                      <option value="IE">Ireland</option>
                      <option value="US">United States</option>
                      <option value="CA">Canada</option>
                      <option value="AU">Australia</option>
                      <option value="NZ">New Zealand</option>
                      <option value="DE">Germany</option>
                      <option value="FR">France</option>
                      <option value="NL">Netherlands</option>
                      <option value="ES">Spain</option>
                      <option value="IT">Italy</option>
                      <option value="JP">Japan</option>
                    </select>
                  </div>
                </div>

                <div>
                  <label htmlFor="addressLine1-edit" className="tag-label mb-2 block">
                    Address line 1
                  </label>
                  <input
                    id="addressLine1-edit"
                    type="text"
                    required
                    value={customerAddressData.addressLine1}
                    onChange={(e) => setCustomerAddressData({ ...customerAddressData, addressLine1: e.target.value })}
                    className="w-full border border-line px-3 py-2 text-sm"
                    placeholder="Street address"
                  />
                </div>

                <div>
                  <label htmlFor="addressLine2-edit" className="tag-label mb-2 block">
                    Address line 2 (optional)
                  </label>
                  <input
                    id="addressLine2-edit"
                    type="text"
                    value={customerAddressData.addressLine2}
                    onChange={(e) => setCustomerAddressData({ ...customerAddressData, addressLine2: e.target.value })}
                    className="w-full border border-line px-3 py-2 text-sm"
                    placeholder="Apartment, suite, etc."
                  />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label htmlFor="city-edit" className="tag-label mb-2 block">
                      City
                    </label>
                    <input
                      id="city-edit"
                      type="text"
                      required
                      value={customerAddressData.city}
                      onChange={(e) => setCustomerAddressData({ ...customerAddressData, city: e.target.value })}
                      className="w-full border border-line px-3 py-2 text-sm"
                      placeholder="London"
                    />
                  </div>
                  <div>
                    <label htmlFor="postalCode-edit" className="tag-label mb-2 block">
                      Postal code
                    </label>
                    <input
                      id="postalCode-edit"
                      type="text"
                      required
                      value={customerAddressData.postalCode}
                      onChange={(e) => setCustomerAddressData({ ...customerAddressData, postalCode: e.target.value })}
                      className="w-full border border-line px-3 py-2 text-sm"
                      placeholder="SW1A 1AA"
                    />
                  </div>
                </div>

                <button
                  type="button"
                  onClick={() => setMode('logged-in')}
                  className="w-full bg-clay px-6 py-3 text-sm font-medium text-paper hover:bg-clay-dark"
                >
                  Done editing
                </button>
              </form>
            </div>
          ) : (
            <div>
              <button
                onClick={() => setMode(null)}
                className="text-sm text-clay hover:text-clay-dark mb-4"
              >
                ← Back
              </button>
              <h3 className="font-display text-lg">Guest checkout</h3>
              {checkoutError && (
                <p className="mt-4 border border-splash-pink/40 bg-splash-pink/10 px-4 py-3 text-sm text-splash-pink">
                  {checkoutError}
                </p>
              )}
              <form onSubmit={handleGuestCheckout} className="mt-4 space-y-4">
                <div>
                  <label htmlFor="fullName" className="tag-label mb-2 block">
                    Full name
                  </label>
                  <input
                    id="fullName"
                    type="text"
                    required
                    value={guestData.fullName}
                    onChange={(e) => setGuestData({ ...guestData, fullName: e.target.value })}
                    className="w-full border border-line px-3 py-2 text-sm"
                  />
                </div>
                <div>
                  <label htmlFor="email" className="tag-label mb-2 block">
                    Email
                  </label>
                  <input
                    id="email"
                    type="email"
                    required
                    value={guestData.email}
                    onChange={(e) => setGuestData({ ...guestData, email: e.target.value })}
                    className="w-full border border-line px-3 py-2 text-sm"
                  />
                </div>
                <div>
                  <label htmlFor="phone" className="tag-label mb-2 block">
                    Phone number
                  </label>
                  <input
                    id="phone"
                    type="tel"
                    required
                    value={guestData.phone}
                    onChange={(e) => setGuestData({ ...guestData, phone: e.target.value })}
                    className="w-full border border-line px-3 py-2 text-sm"
                  />
                </div>
                <div>
                  <label htmlFor="address" className="tag-label mb-2 block">
                    Address
                  </label>
                  <textarea
                    id="address"
                    required
                    value={guestData.address}
                    onChange={(e) => setGuestData({ ...guestData, address: e.target.value })}
                    rows={3}
                    className="w-full border border-line px-3 py-2 text-sm"
                  />
                </div>

                <ShippingSelector
                  items={items}
                  onShippingSelect={handleShippingSelect}
                />

                <button
                  type="submit"
                  disabled={checkingOut}
                  className="w-full bg-clay px-6 py-3 text-sm font-medium text-paper transition-colors hover:bg-clay-dark disabled:opacity-60"
                >
                  {checkingOut ? 'Processing…' : 'Continue to payment'}
                </button>
              </form>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
