import { OrderSuccess } from '@/components/orders/OrderSuccess'
import { Loading } from '@/components/shared'
import { APP_NAME } from '@/constants/app.constant'
import { ROUTES_ENUM } from '@/routes/route.constant'
import { useLocalization } from '@/utils/hooks/useLocalization'
import React, { useState, useEffect } from 'react'
import { Helmet } from 'react-helmet'
import { useNavigate } from 'react-router-dom'

const Success: React.FC = () => {
  const navigate = useNavigate()
  const [orderId, setOrderId] = useState<string>('')
  const { translate } = useLocalization()

  useEffect(() => {
    // Get order ID from local storage
    const orderIdData = localStorage.getItem('orderId')
    if (orderIdData) {
      setOrderId(orderIdData)
      // Clear order ID from local storage
      localStorage.removeItem('orderId')
    } else {
      navigate(ROUTES_ENUM.public.home)
    }
  }, [navigate])

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

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

  return (
    <div className="min-h-screen bg-gray-50">
      <Helmet
        titleTemplate={`%s | ${APP_NAME}`}
        title={translate('::' + 'Public.nav.success')}
        defaultTitle={APP_NAME}
      ></Helmet>
      <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">
        <OrderSuccess orderId={orderId} onBackToShop={handleBackToShop} />
      </div>
    </div>
  )
}

export default Success
