'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import AppImage from '@/components/ui/AppImage';
import Link from 'next/link';
import { Lock, CreditCard, Truck, CheckCircle, ChevronLeft } from 'lucide-react';
import Button from '@/components/ui/Button';
import { useCart } from '@/presentation/hooks/useCart';
import { useAuth } from '@/presentation/hooks/useAuth';
import { useCheckout } from '@/presentation/hooks/useCheckout';
import { formatPrice, getFormatLocale } from '@/lib/utils';
import { useTranslation } from '@/hooks/useTranslation';
import { localizeProduct } from '@/lib/product-i18n';


export default function CheckoutPage() {
  const router = useRouter();
  const { items, summary } = useCart();
  const { user, isAuthenticated } = useAuth();
  const { placeOrder } = useCheckout();
  const { t, locale } = useTranslation();

  const [paymentMethod, setPaymentMethod] = useState('card');
  const [isProcessing, setIsProcessing] = useState(false);
  const [orderComplete, setOrderComplete] = useState(false);
  const [orderId, setOrderId] = useState('');

  const [form, setForm] = useState({
    name: user?.name || '',
    email: user?.email || '',
    phone: user?.phone || '',
    street: user?.address.street || '',
    city: user?.address.city || '',
    state: user?.address.state || '',
    zip: user?.address.zip || '',
    cardNumber: '',
    expiry: '',
    cvv: '',
  });

  const { subtotal: total, deliveryFee, grandTotal } = summary;
  const fmt = (n: number) => formatPrice(n, getFormatLocale(locale));

  if (items.length === 0 && !orderComplete) {
    return (
      <div className="mx-auto max-w-7xl px-4 py-20 text-center">
        <h1 className="mb-4 font-display text-2xl font-bold">{t('checkout.noItems')}</h1>
        <Link href="/shop">
          <Button>{t('checkout.goToShop')}</Button>
        </Link>
      </div>
    );
  }

  if (orderComplete) {
    return (
      <div className="mx-auto max-w-lg px-4 py-20 text-center">
        <div className="mx-auto mb-6 flex h-20 w-20 items-center justify-center rounded-full bg-brand-50">
          <CheckCircle className="h-12 w-12 text-brand-700" />
        </div>
        <h1 className="mb-2 font-display text-3xl font-bold text-brand-900">
          {t('checkout.orderConfirmed')}
        </h1>
        <p className="mb-2 text-gray-500">{t('checkout.thankYou')}</p>
        <p className="mb-8 text-sm font-medium text-brand-700">
          {t('checkout.orderId', { id: orderId })}
        </p>
        <div className="flex flex-col gap-3 sm:flex-row sm:justify-center">
          <Link href="/account">
            <Button variant="primary">{t('checkout.viewOrders')}</Button>
          </Link>
          <Link href="/shop">
            <Button variant="secondary">{t('cart.continueShopping')}</Button>
          </Link>
        </div>
      </div>
    );
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsProcessing(true);

    await new Promise((resolve) => setTimeout(resolve, 1500));

    const { order } = placeOrder({
      deliveryAddress: {
        street: form.street,
        city: form.city,
        state: form.state,
        zip: form.zip,
      },
      paymentMethod,
    });

    setOrderId(order.id);
    setOrderComplete(true);
    setIsProcessing(false);
  };

  const updateField = (field: string, value: string) => {
    setForm((prev) => ({ ...prev, [field]: value }));
  };

  return (
    <div className="bg-gray-50">
      <div className="mx-auto max-w-7xl px-4 py-8 sm:px-6 lg:px-8">
        <Link
          href="/cart"
          className="mb-6 inline-flex items-center gap-1 text-sm font-medium text-gray-500 hover:text-brand-700"
        >
          <ChevronLeft className="h-4 w-4 rtl:rotate-180" />
          {t('checkout.backToCart')}
        </Link>

        <h1 className="section-heading mb-8">{t('checkout.title')}</h1>

        <form onSubmit={handleSubmit}>
          <div className="grid gap-8 lg:grid-cols-3">
            <div className="space-y-6 lg:col-span-2">
              {!isAuthenticated && (
                <div className="card-premium p-6">
                  <p className="text-sm text-gray-600">
                    {t('checkout.haveAccount')}{' '}
                    <Link href="/login" className="font-semibold text-brand-700 hover:underline">
                      {t('checkout.signIn')}
                    </Link>{' '}
                    {t('checkout.fasterCheckout')}
                  </p>
                </div>
              )}

              <div className="card-premium p-6">
                <div className="mb-4 flex items-center gap-2">
                  <Truck className="h-5 w-5 text-brand-700" />
                  <h2 className="font-display text-lg font-semibold">
                    {t('checkout.deliveryDetails')}
                  </h2>
                </div>
                <div className="grid gap-4 sm:grid-cols-2">
                  <div className="sm:col-span-2">
                    <label className="label-text">{t('checkout.fullName')}</label>
                    <input
                      required
                      className="input-field"
                      value={form.name}
                      onChange={(e) => updateField('name', e.target.value)}
                    />
                  </div>
                  <div>
                    <label className="label-text">{t('checkout.email')}</label>
                    <input
                      required
                      type="email"
                      className="input-field"
                      value={form.email}
                      onChange={(e) => updateField('email', e.target.value)}
                    />
                  </div>
                  <div>
                    <label className="label-text">{t('checkout.phone')}</label>
                    <input
                      required
                      type="tel"
                      className="input-field"
                      value={form.phone}
                      onChange={(e) => updateField('phone', e.target.value)}
                    />
                  </div>
                  <div className="sm:col-span-2">
                    <label className="label-text">{t('checkout.street')}</label>
                    <input
                      required
                      className="input-field"
                      value={form.street}
                      onChange={(e) => updateField('street', e.target.value)}
                    />
                  </div>
                  <div>
                    <label className="label-text">{t('checkout.city')}</label>
                    <input
                      required
                      className="input-field"
                      value={form.city}
                      onChange={(e) => updateField('city', e.target.value)}
                    />
                  </div>
                  <div>
                    <label className="label-text">{t('checkout.state')}</label>
                    <input
                      required
                      className="input-field"
                      value={form.state}
                      onChange={(e) => updateField('state', e.target.value)}
                    />
                  </div>
                  <div>
                    <label className="label-text">{t('checkout.zip')}</label>
                    <input
                      required
                      className="input-field"
                      value={form.zip}
                      onChange={(e) => updateField('zip', e.target.value)}
                    />
                  </div>
                </div>
              </div>

              <div className="card-premium p-6">
                <div className="mb-4 flex items-center gap-2">
                  <CreditCard className="h-5 w-5 text-brand-700" />
                  <h2 className="font-display text-lg font-semibold">{t('checkout.payment')}</h2>
                </div>

                <div className="mb-4 flex gap-3">
                  {['card', 'cod'].map((method) => (
                    <button
                      key={method}
                      type="button"
                      onClick={() => setPaymentMethod(method)}
                      className={`rounded-lg border-2 px-4 py-2 text-sm font-medium transition-all ${
                        paymentMethod === method
                          ? 'border-brand-700 bg-brand-700 text-white'
                          : 'border-gray-200 text-gray-600 hover:border-brand-300'
                      }`}
                    >
                      {method === 'card'
                        ? t('checkout.creditCard')
                        : t('checkout.cashOnDelivery')}
                    </button>
                  ))}
                </div>

                {paymentMethod === 'card' && (
                  <div className="grid gap-4 sm:grid-cols-2">
                    <div className="sm:col-span-2">
                      <label className="label-text">{t('checkout.cardNumber')}</label>
                      <input
                        required
                        className="input-field"
                        placeholder="1234 5678 9012 3456"
                        value={form.cardNumber}
                        onChange={(e) => updateField('cardNumber', e.target.value)}
                      />
                    </div>
                    <div>
                      <label className="label-text">{t('checkout.expiry')}</label>
                      <input
                        required
                        className="input-field"
                        placeholder="MM/YY"
                        value={form.expiry}
                        onChange={(e) => updateField('expiry', e.target.value)}
                      />
                    </div>
                    <div>
                      <label className="label-text">{t('checkout.cvv')}</label>
                      <input
                        required
                        className="input-field"
                        placeholder="123"
                        value={form.cvv}
                        onChange={(e) => updateField('cvv', e.target.value)}
                      />
                    </div>
                  </div>
                )}
              </div>
            </div>

            <div>
              <div className="card-premium sticky top-24 p-6">
                <h2 className="mb-4 font-display text-lg font-semibold">
                  {t('cart.orderSummary')}
                </h2>

                <div className="mb-4 max-h-60 space-y-3 overflow-y-auto">
                  {items.map((item) => {
                    const localized = localizeProduct(item.product, t);
                    return (
                      <div key={item.id} className="flex gap-3">
                        <div className="relative h-12 w-12 shrink-0 overflow-hidden rounded-lg">
                          <AppImage
                            src={item.product.image}
                            alt={localized.name}
                            fill
                            className="object-cover"
                            sizes="48px"
                          />
                        </div>
                        <div className="flex-1">
                          <p className="text-sm font-medium text-brand-900">
                            {localized.name}
                          </p>
                          <p className="text-xs text-gold-700">
                            {item.customizationLabel}
                          </p>
                          <p className="text-xs text-gray-400">
                            {t('checkout.qty', { count: item.quantity })}
                          </p>
                        </div>
                        <span className="text-sm font-medium">
                          {fmt(item.product.price * item.quantity)}
                        </span>
                      </div>
                    );
                  })}
                </div>

                <div className="space-y-2 border-t border-gray-100 pt-4">
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-500">{t('cart.subtotal')}</span>
                    <span>{fmt(total)}</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-500">{t('cart.delivery')}</span>
                    <span>
                      {deliveryFee === 0 ? t('cart.free') : fmt(deliveryFee)}
                    </span>
                  </div>
                  <div className="flex justify-between pt-2 text-lg font-bold">
                    <span>{t('cart.total')}</span>
                    <span className="text-brand-800">{fmt(grandTotal)}</span>
                  </div>
                </div>

                <Button
                  type="submit"
                  variant="gold"
                  size="lg"
                  className="mt-6 w-full"
                  disabled={isProcessing}
                >
                  <Lock className="h-4 w-4" />
                  {isProcessing
                    ? t('checkout.processing')
                    : t('checkout.pay', { amount: fmt(grandTotal) })}
                </Button>

                <p className="mt-3 flex items-center justify-center gap-1 text-xs text-gray-400">
                  <Lock className="h-3 w-3" />
                  {t('checkout.secure')}
                </p>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}