'use client'

import { useState, useRef, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { useCartStore } from '../store/cart'
import { formatTL } from '../lib/format'

const BANK_INFO = {
  bankName: process.env.NEXT_PUBLIC_BANK_NAME ?? '',
  accountHolder: process.env.NEXT_PUBLIC_BANK_ACCOUNT_NAME ?? '',
  iban: process.env.NEXT_PUBLIC_BANK_IBAN ?? '',
}

export default function CartClient() {
  const router = useRouter()
  const { items, removeItem, updateQuantity, clearCart, total } = useCartStore()
  const [shippingAddress, setShippingAddress] = useState('')
  const [paymentMethod, setPaymentMethod] = useState<'ONLINE' | 'BANK_TRANSFER'>('BANK_TRANSFER')
  const [notes, setNotes] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [iyzicoHtml, setIyzicoHtml] = useState<string | null>(null)
  const iyzicoRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (!iyzicoHtml || !iyzicoRef.current) return
    const container = iyzicoRef.current
    container.innerHTML = iyzicoHtml
    const scripts = container.querySelectorAll('script')
    scripts.forEach(oldScript => {
      const newScript = document.createElement('script')
      if (oldScript.src) {
        newScript.src = oldScript.src
      } else {
        newScript.textContent = oldScript.textContent
      }
      newScript.async = true
      document.body.appendChild(newScript)
      oldScript.remove()
    })
  }, [iyzicoHtml])

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (items.length === 0) return
    if (!shippingAddress.trim()) {
      setError('Teslimat adresi zorunludur.')
      return
    }

    setSubmitting(true)
    setError(null)

    const payload = {
      items: items.map(i => ({ productId: i.productId, quantity: i.quantity })),
      shippingAddress,
      paymentMethod,
      notes: notes.trim() || undefined,
    }

    try {
      if (paymentMethod === 'ONLINE') {
        const res = await fetch('/api/payment/init', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
        })
        const data = await res.json()
        if (!res.ok) {
          setError(data.error ?? 'Ödeme başlatılamadı.')
          return
        }
        clearCart()
        setIyzicoHtml(data.checkoutFormContent)
      } else {
        const res = await fetch('/api/orders', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
        })
        const data = await res.json()
        if (!res.ok) {
          setError(data.error ?? 'Sipariş oluşturulamadı.')
          return
        }
        clearCart()
        router.push(`/bayi/orders/${data.orderNo}`)
      }
    } catch {
      setError('Bir hata oluştu. Lütfen tekrar deneyin.')
    } finally {
      setSubmitting(false)
    }
  }

  if (iyzicoHtml !== null) {
    return (
      <div className="p-6 md:p-8 max-w-2xl mx-auto">
        <h1 className="font-display text-3xl font-light text-brown mb-6">Ödeme</h1>
        <div ref={iyzicoRef} id="iyzipay-checkout-form" className="responsive" />
      </div>
    )
  }

  if (items.length === 0) {
    return (
      <div className="p-8 text-center py-20">
        <p className="font-display text-2xl text-brown/40">Sepetiniz boş</p>
        <a href="/bayi/products"
          className="mt-4 inline-block rounded-lg font-body text-sm text-earth hover:text-brown transition-colors">
          Ürünlere Göz At →
        </a>
      </div>
    )
  }

  return (
    <div className="p-6 md:p-8 max-w-5xl mx-auto">
      <h1 className="font-display text-3xl font-light text-brown mb-8">Sepet</h1>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Ürün listesi */}
        <div className="lg:col-span-2 space-y-3">
          {items.map(item => (
            <div key={item.productId} className="bg-white rounded-xl p-4 flex items-center gap-4">
              <div className="flex-1 min-w-0">
                <p className="font-body text-sm font-medium text-brown truncate">{item.nameTr}</p>
                {item.size && <p className="font-body text-xs text-brown/40">{item.size}</p>}
                <p className="font-body text-sm text-earth mt-1">{formatTL(item.discountedPrice)} / adet</p>
              </div>
              <div className="flex items-center gap-2">
                <button onClick={() => updateQuantity(item.productId, item.quantity - 1)}
                  className="w-7 h-7 rounded-lg flex items-center justify-center border border-sand text-brown hover:border-earth transition-colors font-body">
                  −
                </button>
                <span className="w-8 text-center font-body text-sm">{item.quantity}</span>
                <button onClick={() => updateQuantity(item.productId, item.quantity + 1)}
                  className="w-7 h-7 rounded-lg flex items-center justify-center border border-sand text-brown hover:border-earth transition-colors font-body">
                  +
                </button>
              </div>
              <div className="text-right min-w-[70px]">
                <p className="font-body text-sm font-medium text-brown">
                  {formatTL(item.discountedPrice * item.quantity)}
                </p>
              </div>
              <button onClick={() => removeItem(item.productId)}
                className="text-brown/30 hover:text-red-500 transition-colors font-body text-lg leading-none">
                ×
              </button>
            </div>
          ))}

          <div className="bg-white rounded-xl p-4 flex justify-between items-center font-body">
            <span className="text-sm text-brown/60">
              {items.length} ürün, {items.reduce((s, i) => s + i.quantity, 0)} adet
            </span>
            <span className="text-lg font-medium text-brown">
              Toplam: {formatTL(total())}
            </span>
          </div>
        </div>

        {/* Sipariş formu */}
        <form onSubmit={handleSubmit} className="space-y-5">
          <div className="bg-white rounded-xl p-6 space-y-5">
            <h2 className="font-display text-xl text-brown">Sipariş Bilgileri</h2>

            <div>
              <label className="block font-body text-sm text-brown mb-2">
                Teslimat Adresi <span className="text-red-500">*</span>
              </label>
              <textarea rows={3} value={shippingAddress}
                onChange={e => setShippingAddress(e.target.value)}
                required placeholder="Adres, İl, Posta Kodu"
                className="w-full px-3 py-2 rounded-lg border border-sand bg-cream font-body text-sm focus:outline-none focus:border-earth transition-colors resize-none" />
            </div>

            <div>
              <label className="block font-body text-sm text-brown mb-2">Ödeme Yöntemi</label>
              <div className="space-y-2">
                {[
                  { value: 'BANK_TRANSFER', label: 'Havale / EFT' },
                  { value: 'ONLINE', label: 'Online Ödeme (İyzico)' },
                ].map(opt => (
                  <label key={opt.value}
                    className="flex items-center gap-3 cursor-pointer p-3 rounded-lg border border-sand hover:border-earth transition-colors">
                    <input type="radio" name="paymentMethod" value={opt.value}
                      checked={paymentMethod === opt.value}
                      onChange={() => setPaymentMethod(opt.value as typeof paymentMethod)}
                      className="accent-brown" />
                    <span className="font-body text-sm text-brown">{opt.label}</span>
                  </label>
                ))}
              </div>
            </div>

            {paymentMethod === 'BANK_TRANSFER' && BANK_INFO.iban && (
              <div className="bg-sand rounded-lg p-4 text-sm font-body space-y-1">
                <p className="font-medium text-brown mb-2">Banka Bilgileri</p>
                <p className="text-brown/70">{BANK_INFO.bankName}</p>
                <p className="text-brown/70">{BANK_INFO.accountHolder}</p>
                <p className="font-mono text-brown tracking-wide">{BANK_INFO.iban}</p>
                <p className="text-earth text-xs mt-2">
                  Açıklama kısmına sipariş numaranızı yazmayı unutmayın.
                </p>
              </div>
            )}

            <div>
              <label className="block font-body text-sm text-brown mb-2">
                Sipariş Notu (isteğe bağlı)
              </label>
              <textarea rows={2} value={notes}
                onChange={e => setNotes(e.target.value)}
                placeholder="Özel talepler, renk tercihi vb."
                className="w-full px-3 py-2 rounded-lg border border-sand bg-cream font-body text-sm focus:outline-none focus:border-earth transition-colors resize-none" />
            </div>

            {error && (
              <p className="font-body text-sm text-red-600 bg-red-50 rounded-lg px-3 py-2">{error}</p>
            )}

            <button type="submit" disabled={submitting || items.length === 0}
              className="w-full py-3 rounded-lg bg-brown text-cream font-body text-sm tracking-widest uppercase hover:bg-earth transition-colors disabled:opacity-60">
              {submitting
                ? (paymentMethod === 'ONLINE' ? 'Ödemeye yönlendiriliyor...' : 'Sipariş oluşturuluyor...')
                : `Sipariş Oluştur — ${formatTL(total())}`}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
