import { Cart } from '@/components/orders/Cart'
import { PaymentForm } from '@/components/orders/PaymentForm'
import { Loading } from '@/components/shared'
import { APP_NAME } from '@/constants/app.constant'
import { CustomTenantDto } from '@/proxy/config/models'
import { OrderDto } from '@/proxy/order/models'
import { ROUTES_ENUM } from '@/routes/route.constant'
import { OrderService } from '@/services/order.service'
import {
  CartState,
  clearCart,
  initialCartState,
  removeItemFromCart,
  updateCartItemQuantity,
} from '@/utils/cartUtils'
import { useLocalization } from '@/utils/hooks/useLocalization'
import React, { useState, useEffect } from 'react'
import { Helmet } from 'react-helmet'
import { useNavigate } from 'react-router-dom'

const Payment: React.FC = () => {
  const navigate = useNavigate()
  const [tenant, setTenant] = useState<CustomTenantDto | null>(null)
  const [isCartOpen, setIsCartOpen] = useState(false)
  const [cartState, setCartState] = useState<CartState>(initialCartState)
  const { translate } = useLocalization()

  useEffect(() => {
    const tenantData = localStorage.getItem('tenantData') // ✅ güncellendi
    const savedCartState = localStorage.getItem('cartState')

    if (tenantData) {
      setTenant(JSON.parse(tenantData))
    } else {
      navigate(ROUTES_ENUM.public.checkout)
    }

    if (savedCartState) {
      setCartState(JSON.parse(savedCartState))
    }
  }, [navigate])

  // Save cart state to localStorage whenever it changes
  useEffect(() => {
    localStorage.setItem('cartState', JSON.stringify(cartState))
  }, [cartState])

  const handleCheckout = () => {
    setIsCartOpen(false)
    navigate(ROUTES_ENUM.public.checkout)
  }

  const handleUpdateQuantity = (id: string, quantity: number) => {
    setCartState((currentState) => updateCartItemQuantity(currentState, id, quantity))
  }

  const handleRemoveItem = (id: string) => {
    setCartState((currentState) => removeItemFromCart(currentState, id))
  }

  const handleClearCart = () => {
    setCartState(clearCart())
  }

  const handlePaymentComplete = async (paymentData: Record<string, unknown>) => {
    if (!tenant) return

    try {
      const orderData = {
        tenant,
        items: cartState.items,
        subtotal: cartState.total,
        commission: paymentData.commission,
        total: paymentData.total,
        paymentMethodId: paymentData.paymentMethodId,
        installment: paymentData.installment,
        paymentData: {
          cardNumber: paymentData.cardNumber
            ? `****${(paymentData.cardNumber as string).slice(-4)}`
            : null,
          cardName: paymentData.cardName,
          installment: paymentData.installment,
        },
      } as OrderDto

      const orderService = new OrderService()
      const result = await orderService.createOrder(orderData)

      if (result.success && result.orderId) {
        localStorage.setItem('orderId', result.orderId) // ✅ güncellendi
        setCartState(clearCart())
        localStorage.removeItem('tenantData') // ✅ temizlik
        localStorage.removeItem('cartState') // ✅ temizlik
        navigate(ROUTES_ENUM.public.success)
      } else {
        alert('Sipariş oluşturulurken hata oluştu: ' + result.error)
      }
    } catch (error) {
      alert('Sipariş oluşturulurken hata oluştu')
      console.error('Order creation error:', error)
    }
  }

  const handleBackToTenant = () => {
    navigate(ROUTES_ENUM.public.checkout)
  }

  if (!tenant) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gray-50 dark:bg-gray-950">
        <div className="text-center">
          <Loading loading={!tenant} />
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-950">
      <Helmet
        titleTemplate={`%s | ${APP_NAME}`}
        title={translate('::' + 'Public.nav.payment')}
        defaultTitle={APP_NAME}
      ></Helmet>

      {/* Hero Section */}
      <div className="relative bg-blue-900 text-white py-12">
        <div
          className="absolute inset-0 opacity-20"
          style={{
            backgroundSize: 'cover',
            backgroundPosition: 'center',
          }}
        ></div>
      </div>

      <div className="container mx-auto px-4 pt-4">
        <PaymentForm
          tenant={tenant}
          onBack={handleBackToTenant}
          onComplete={handlePaymentComplete}
          cartState={cartState}
        />

        <Cart
          isOpen={isCartOpen}
          onClose={() => setIsCartOpen(false)}
          onCheckout={handleCheckout}
          cartState={cartState}
          updateQuantity={handleUpdateQuantity}
          removeItem={handleRemoveItem}
          clearCart={handleClearCart}
        />
      </div>
    </div>
  )
}

export default Payment
