"use client"

import { useEffect, useState } from "react"
import { useSearchParams, useRouter } from "next/navigation"
import Link from "next/link"
import { CheckCircle, ShoppingBag, ArrowRight, Wallet } from "lucide-react"
import axiosInstance from "@/utils/axios"
import { useAuth } from "@/context/AuthContext"

export default function CheckoutSuccessPage() {
  const searchParams = useSearchParams()
  const router = useRouter()
  const { user } = useAuth()
  const [order, setOrder] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  const orderId = searchParams.get("orderId")
  const paymentMethod = searchParams.get("paymentMethod")
  const reference = searchParams.get("reference")

  useEffect(() => {
    if (!orderId) {
      router.push("/")
      return
    }

    if (!user) {
      router.push("/login")
      return
    }

    const fetchOrder = async () => {
      try {
        const response = await axiosInstance.get(`/orders/${orderId}`)
        if (response.data.status) {
          setOrder(response.data.data)
        } else {
          setError("Bestelling niet gevonden")
        }
      } catch (err) {
        console.error("Error fetching order:", err)
        setError("Er is een fout opgetreden bij het ophalen van de bestelling")
      } finally {
        setLoading(false)
      }
    }

    fetchOrder()
  }, [orderId, router, user])

  if (loading) {
    return (
      <div className="container mx-auto px-4 py-12 flex justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-teal-600"></div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="container mx-auto px-4 py-12">
        <div className="max-w-2xl mx-auto bg-white p-8 rounded-lg shadow-sm">
          <h1 className="text-2xl font-bold text-red-600 mb-4">Fout</h1>
          <p className="text-gray-700 mb-6">{error}</p>
          <Link
            href="/"
            className="inline-flex items-center px-6 py-3 bg-teal-600 text-white rounded-md hover:bg-teal-700 transition-colors"
          >
            Terug naar home
          </Link>
        </div>
      </div>
    )
  }

  return (
    <div className="container mx-auto px-4 py-12">
      <div className="max-w-2xl mx-auto bg-white p-8 rounded-lg shadow-sm">
        <div className="flex flex-col items-center mb-8">
          <div className="h-16 w-16 bg-teal-100 rounded-full flex items-center justify-center mb-4">
            <CheckCircle className="h-10 w-10 text-teal-600" />
          </div>
          <h1 className="text-2xl font-bold text-gray-900">Bedankt voor je bestelling!</h1>
          <p className="text-gray-600 mt-2">Je bestelling is succesvol geplaatst.</p>
        </div>

        <div className="border-t border-b py-4 mb-6">
          <div className="flex justify-between mb-2">
            <span className="text-gray-600">Bestelnummer:</span>
            <span className="font-medium">{order?.orderNumber || orderId}</span>
          </div>
          <div className="flex justify-between mb-2">
            <span className="text-gray-600">Datum:</span>
            <span className="font-medium">
              {order?.createdAt
                ? new Date(order.createdAt).toLocaleDateString("nl-NL", {
                  day: "numeric",
                  month: "long",
                  year: "numeric",
                })
                : ""}
            </span>
          </div>
          <div className="flex justify-between mb-2">
            <span className="text-gray-600">Betaalstatus:</span>
            <span className={`font-medium ${order?.paymentStatus === "paid" ? "text-green-600" : "text-orange-500"}`}>
              {order?.paymentStatus === "paid" ? "Betaald" : "In afwachting"}
            </span>
          </div>
          <div className="flex justify-between">
            <span className="text-gray-600">Betaalmethode:</span>
            <span className="font-medium flex items-center">
              {paymentMethod === "wallet" || order?.paymentMethod === "wallet" ? (
                <>
                  <Wallet size={16} className="mr-1 text-teal-600" /> Wallet
                </>
              ) : (
                order?.paymentMethod || "Onbekend"
              )}
            </span>
          </div>

          {/* Show reference if wallet payment */}
          {(paymentMethod === "wallet" || order?.paymentMethod === "wallet") &&
            (reference || order?.paymentReference) && (
              <div className="flex justify-between mt-2">
                <span className="text-gray-600">Referentie:</span>
                <span className="font-medium">{reference || order?.paymentReference}</span>
              </div>
            )}
        </div>

        <div className="mb-8">
          <h2 className="text-lg font-semibold mb-4">Wat gebeurt er nu?</h2>
          <ol className="space-y-4">
            <li className="flex">
              <div className="h-6 w-6 bg-teal-100 rounded-full flex items-center justify-center mr-3 flex-shrink-0">
                <span className="text-sm font-medium text-teal-600">1</span>
              </div>
              <div>
                <p className="text-gray-700">
                  We hebben je bestelling ontvangen en zullen deze zo snel mogelijk verwerken.
                </p>
              </div>
            </li>
            <li className="flex">
              <div className="h-6 w-6 bg-teal-100 rounded-full flex items-center justify-center mr-3 flex-shrink-0">
                <span className="text-sm font-medium text-teal-600">2</span>
              </div>
              <div>
                <p className="text-gray-700">Je ontvangt een bevestigingsmail met de details van je bestelling.</p>
              </div>
            </li>
            <li className="flex">
              <div className="h-6 w-6 bg-teal-100 rounded-full flex items-center justify-center mr-3 flex-shrink-0">
                <span className="text-sm font-medium text-teal-600">3</span>
              </div>
              <div>
                <p className="text-gray-700">
                  Zodra je bestelling is verzonden, ontvang je een e-mail met de verzendgegevens.
                </p>
              </div>
            </li>
          </ol>
        </div>

        <div className="flex flex-col sm:flex-row justify-between gap-4">
          <Link
            href="/dashboard/orders"
            className="inline-flex items-center justify-center px-6 py-3 bg-teal-600 text-white rounded-md hover:bg-teal-700 transition-colors"
          >
            <ShoppingBag className="h-5 w-5 mr-2" />
            Bekijk mijn bestellingen
          </Link>
          <Link
            href="/shop"
            className="inline-flex items-center justify-center px-6 py-3 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 transition-colors"
          >
            Verder winkelen
            <ArrowRight className="h-5 w-5 ml-2" />
          </Link>
        </div>
      </div>
    </div>
  )
}
