import { Cart } from '@/components/orders/Cart'
import { TenantForm } from '@/components/orders/TenantForm'
import { APP_NAME } from '@/constants/app.constant'
import { CustomTenantDto } from '@/proxy/config/models'
import { ROUTES_ENUM } from '@/routes/route.constant'
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 Checkout: React.FC = () => {
  const navigate = useNavigate()
  const [isCartOpen, setIsCartOpen] = useState(false)
  const { translate } = useLocalization()

  const [cartState, setCartState] = useState<CartState>(() => {
    const savedCart = localStorage.getItem('cartState')
    return savedCart ? JSON.parse(savedCart) : initialCartState
  })

  useEffect(() => {
    localStorage.setItem('cartState', JSON.stringify(cartState))
  }, [cartState])

  const handleTenantSubmit = (tenantData: CustomTenantDto) => {
    localStorage.setItem('tenantData', JSON.stringify(tenantData))
    navigate(ROUTES_ENUM.public.payment)
  }

  const handleBackToCatalog = () => {
    navigate(ROUTES_ENUM.public.home)
  }

  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())
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-950">
      <Helmet
        titleTemplate={`%s | ${APP_NAME}`}
        title={translate('::' + 'Public.nav.checkout')}
        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-12">
        <TenantForm onSubmit={handleTenantSubmit} onBack={handleBackToCatalog} />

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

export default Checkout
