'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import StoreLayout from '@/components/layout/StoreLayout';
import { useCart } from '@/context/CartContext';
import { useAuth } from '@/context/AuthContext';
import { useLanguage } from '@/context/LanguageContext';
import styles from './checkout.module.css';

export default function CheckoutPage() {
  const { t, language } = useLanguage();
  const { items, total, couponDiscount, clearCart } = useCart();
  const { user } = useAuth();
  const router = useRouter();
  const [step, setStep] = useState(1);
  const [processing, setProcessing] = useState(false);
  const [paymentMethod, setPaymentMethod] = useState<'knet' | 'visa' | 'apple'>('knet');
  const [form, setForm] = useState({
    firstName: user?.name?.split(' ')[0] || '',
    lastName: user?.name?.split(' ')[1] || '',
    phone: user?.phone || '',
    email: user?.email || '',
    area: '',
    block: '',
    street: '',
    building: '',
    floor: '',
    notes: '',
  });

  const shipping = total > 15 ? 0 : 1.5;
  const discountAmt = (items.reduce((s, i) => s + i.price * i.quantity, 0) * couponDiscount) / 100;
  const finalTotal = total + shipping;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setProcessing(true);
    try {
      const res = await fetch('/api/orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          user: user ? { id: user.id } : null,
          items,
          address: {
            firstName: form.firstName,
            lastName: form.lastName,
            phone: form.phone,
            email: form.email,
            area: form.area,
            block: form.block,
            street: form.street,
            building: form.building,
            notes: form.notes,
          },
          couponDiscount,
          paymentMethod,
        })
      });

      const data = await res.json();
      if (data.success && data.order) {
        // Now initiate payment
        try {
          const payRes = await fetch('/api/payment/initiate', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ 
              orderId: data.order.id, 
              paymentMethod 
            })
          });
          const payData = await payRes.json();
          
          if (payData.success && payData.paymentUrl) {
            clearCart();
            window.location.href = payData.paymentUrl; // Redirect to MyFatoorah
          } else {
            alert('Payment initialization failed: ' + (payData.message || 'Unknown error'));
            setProcessing(false);
          }
        } catch (payErr) {
          console.error('Payment Error', payErr);
          alert('Error connecting to payment gateway.');
          setProcessing(false);
        }
      } else {
        alert(data.message || 'Failed to place order. Please try again.');
        setProcessing(false);
      }
    } catch (err: any) {
      console.error(err);
      alert('Network error while placing order.');
      setProcessing(false);
    }
  };

  if (items.length === 0) return (
    <StoreLayout>
      <div style={{ textAlign: 'center', padding: '100px 24px' }}>
        <p style={{ marginBottom: '16px', color: 'var(--text-muted)' }}>{t.cart.empty}</p>
        <Link href="/products" className="btn btn-primary">{t.cart.continueShopping}</Link>
      </div>
    </StoreLayout>
  );

  return (
    <StoreLayout>
      <div className={styles.page}>
        <div className="container">
          <h1 className={styles.title}>{t.checkout.title}</h1>

          {/* Progress Steps */}
          <div className={styles.steps}>
            {[t.checkout.shipping, t.checkout.payment, t.checkout.review].map((s, i) => (
              <div key={i} className={`${styles.step} ${step > i + 1 ? styles.done : ''} ${step === i + 1 ? styles.active : ''}`}>
                <div className={styles.stepNum}>{step > i + 1 ? '✓' : i + 1}</div>
                <span className={styles.stepLabel}>{s}</span>
              </div>
            ))}
          </div>

          <form onSubmit={handleSubmit} className={styles.layout}>
            {/* Form */}
            <div className={styles.formArea}>
              {step === 1 && (
                <div className={styles.formSection}>
                  <h3 className={styles.sectionTitle}>📦 {t.checkout.shipping}</h3>
                  <div className={styles.formGrid}>
                    <div className="form-group">
                      <label className="form-label">{t.checkout.firstName} *</label>
                      <input required className="form-input" value={form.firstName} onChange={e => setForm(p => ({ ...p, firstName: e.target.value }))} />
                    </div>
                    <div className="form-group">
                      <label className="form-label">{t.checkout.lastName} *</label>
                      <input required className="form-input" value={form.lastName} onChange={e => setForm(p => ({ ...p, lastName: e.target.value }))} />
                    </div>
                    <div className="form-group">
                      <label className="form-label">{t.checkout.phone} *</label>
                      <input required type="tel" className="form-input" value={form.phone} onChange={e => setForm(p => ({ ...p, phone: e.target.value }))} placeholder="+965" />
                    </div>
                    <div className="form-group">
                      <label className="form-label">{t.checkout.email}</label>
                      <input type="email" className="form-input" value={form.email} onChange={e => setForm(p => ({ ...p, email: e.target.value }))} />
                    </div>
                    <div className="form-group">
                      <label className="form-label">{t.checkout.area} *</label>
                      <input required className="form-input" value={form.area} onChange={e => setForm(p => ({ ...p, area: e.target.value }))} placeholder={language === 'ar' ? 'مثال: الصالحية' : 'e.g. Salmiya'} />
                    </div>
                    <div className="form-group">
                      <label className="form-label">{t.checkout.block} *</label>
                      <input required className="form-input" value={form.block} onChange={e => setForm(p => ({ ...p, block: e.target.value }))} />
                    </div>
                    <div className="form-group">
                      <label className="form-label">{t.checkout.street} *</label>
                      <input required className="form-input" value={form.street} onChange={e => setForm(p => ({ ...p, street: e.target.value }))} />
                    </div>
                    <div className="form-group">
                      <label className="form-label">{t.checkout.building} *</label>
                      <input required className="form-input" value={form.building} onChange={e => setForm(p => ({ ...p, building: e.target.value }))} />
                    </div>
                    <div className="form-group" style={{ gridColumn: '1 / -1' }}>
                      <label className="form-label">{t.checkout.notes}</label>
                      <textarea className="form-input" rows={3} value={form.notes} onChange={e => setForm(p => ({ ...p, notes: e.target.value }))} style={{ resize: 'vertical' }} />
                    </div>
                  </div>
                  <button type="button" className="btn btn-primary btn-lg" style={{ marginTop: '24px' }} onClick={() => setStep(2)}>
                    {language === 'ar' ? 'التالي: الدفع →' : 'Next: Payment →'}
                  </button>
                </div>
              )}

              {step === 2 && (
                <div className={styles.formSection}>
                  <h3 className={styles.sectionTitle}>💳 {t.checkout.payment}</h3>
                  <div className={styles.paymentMethods}>
                    {[
                      { id: 'knet', label: t.checkout.knet, icon: '🏦', desc: language === 'ar' ? 'الدفع عبر بطاقة كي نت' : 'Pay with KNET card' },
                      { id: 'visa', label: t.checkout.visa, icon: '💳', desc: language === 'ar' ? 'فيزا أو ماستركارد' : 'Visa or MasterCard' },
                      { id: 'apple', label: t.checkout.applePay, icon: '', desc: language === 'ar' ? 'ادفع باستخدام آبل باي' : 'Pay with Apple Pay' },
                    ].map(m => (
                      <div key={m.id} className={`${styles.payMethod} ${paymentMethod === m.id ? styles.payActive : ''}`} onClick={() => setPaymentMethod(m.id as any)}>
                        <div className={styles.payIcon}>{m.icon}</div>
                        <div>
                          <div className={styles.payLabel}>{m.label}</div>
                          <div className={styles.payDesc}>{m.desc}</div>
                        </div>
                        <div className={styles.payCheck}>{paymentMethod === m.id ? '●' : '○'}</div>
                      </div>
                    ))}
                  </div>
                  <div className={styles.btnRow}>
                    <button type="button" className="btn btn-ghost" onClick={() => setStep(1)}>← {language === 'ar' ? 'رجوع' : 'Back'}</button>
                    <button type="button" className="btn btn-primary btn-lg" onClick={() => setStep(3)}>{language === 'ar' ? 'مراجعة الطلب →' : 'Review Order →'}</button>
                  </div>
                </div>
              )}

              {step === 3 && (
                <div className={styles.formSection}>
                  <h3 className={styles.sectionTitle}>✅ {t.checkout.review}</h3>
                  <div className={styles.reviewItems}>
                    {items.map(item => (
                      <div key={item.id} className={styles.reviewItem}>
                        <span>{language === 'ar' ? item.nameAr : item.name} × {item.quantity}</span>
                        <span>{(item.price * item.quantity).toFixed(3)} {t.product.kwd}</span>
                      </div>
                    ))}
                  </div>
                  <div className={styles.reviewAddress}>
                    <div style={{ color: 'var(--text-muted)', fontSize: '0.85rem', marginBottom: '4px' }}>
                      📍 {language === 'ar' ? 'عنوان التوصيل:' : 'Delivery to:'}
                    </div>
                    <div style={{ fontSize: '0.9rem' }}>
                      {form.firstName} {form.lastName} • {form.phone}<br />
                      {form.area}, {form.block}, {form.street}, {form.building}
                    </div>
                  </div>
                  <div className={styles.btnRow}>
                    <button type="button" className="btn btn-ghost" onClick={() => setStep(2)}>← {language === 'ar' ? 'رجوع' : 'Back'}</button>
                    <button type="submit" className="btn btn-orange btn-lg" disabled={processing}>
                      {processing ? `⏳ ${t.checkout.processing}` : `✓ ${t.checkout.placeOrder}`}
                    </button>
                  </div>
                </div>
              )}
            </div>

            {/* Order Summary */}
            <div className={styles.summary}>
              <h3 className={styles.summaryTitle}>{language === 'ar' ? 'ملخص الطلب' : 'Order Summary'}</h3>
              {items.map(item => (
                <div key={item.id} className={styles.summaryItem}>
                  <span className={styles.summaryItemName}>{language === 'ar' ? item.nameAr : item.name} × {item.quantity}</span>
                  <span>{(item.price * item.quantity).toFixed(3)}</span>
                </div>
              ))}
              <div className={styles.divider}></div>
              {discountAmt > 0 && <div className={styles.summaryRow} style={{ color: 'var(--success)' }}><span>{t.cart.discount}</span><span>−{discountAmt.toFixed(3)}</span></div>}
              <div className={styles.summaryRow}><span>{t.cart.shipping}</span><span>{shipping === 0 ? (language === 'ar' ? 'مجاني' : 'FREE') : `${shipping.toFixed(3)}`}</span></div>
              <div className={styles.summaryTotal}><span>{t.cart.total}</span><span>{finalTotal.toFixed(3)} {t.product.kwd}</span></div>
            </div>
          </form>
        </div>
      </div>
    </StoreLayout>
  );
}
