"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { useCart } from "@/contexts/cart-context"
import { Button } from "@/components/ui/button"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { CheckCircle2 } from "lucide-react"

// Mock function for YooMoney payment
const processYooMoneyPayment = async (amount: number): Promise<boolean> => {
  // Simulate API call
  await new Promise((resolve) => setTimeout(resolve, 2000))
  // Simulate successful payment (in real app, this would be the actual API response)
  return true
}

export function CheckoutForm() {
  const [step, setStep] = useState(1)
  const [address, setAddress] = useState("")
  const [isProcessing, setIsProcessing] = useState(false)
  const [isOrderPlaced, setIsOrderPlaced] = useState(false)

  const { items, clearCart } = useCart()
  const router = useRouter()

  // Log the cart items to make sure they are correct
  console.log("Cart items:", items)

  // Define the getTotalPrice function inside the component
  const getTotalPrice = () => {
    return items.reduce((total, item) => total + item.price * item.quantity, 0).toFixed(2)
  }

  const handleAddressSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (address.trim()) {
      setStep(2)
    }
  }

  const handlePayment = async () => {
    setIsProcessing(true)
    const totalPrice = getTotalPrice() // Calculate total price here
    console.log("Total Price:", totalPrice) // Log the total price to check

    const paymentSuccess = await processYooMoneyPayment(Number(totalPrice))

    if (paymentSuccess) {
      setIsOrderPlaced(true)
      clearCart()
    } else {
      alert("Оплата не прошла. Пожалуйста, попробуйте еще раз.")
    }
    setIsProcessing(false)
  }

  if (isOrderPlaced) {
    return (
      <div className="text-center py-10">
        <CheckCircle2 className="w-16 h-16 text-green-500 mx-auto mb-4" />
        <h2 className="text-2xl font-bold mb-2">Заказ успешно оформлен!</h2>
        <p className="mb-4">Спасибо за покупку. Ваш заказ будет доставлен по указанному адресу.</p>
        <Button onClick={() => router.push("/")}>Вернуться на главную</Button>
      </div>
    )
  }

  return (
    <div className="max-w-md mx-auto">
      {step === 1 && (
        <form onSubmit={handleAddressSubmit} className="space-y-4">
          <h2 className="text-xl font-bold mb-4">Шаг 1: Адрес доставки</h2>
          <div>
            <Label htmlFor="address">Адрес</Label>
            <Textarea
              id="address"
              value={address}
              onChange={(e) => setAddress(e.target.value)}
              placeholder="Введите полный адрес доставки"
              required
            />
          </div>
          <Button type="submit">Продолжить</Button>
        </form>
      )}

      {step === 2 && (
        <div className="space-y-4">
          <h2 className="text-xl font-bold mb-4">Шаг 2: Оплата</h2>
          <div className="bg-gray-100 p-4 rounded-md">
            <h3 className="font-semibold mb-2">Итого к оплате:</h3>
            <p className="text-2xl font-bold">{getTotalPrice()} ₽</p>
          </div>
          <Button onClick={handlePayment} disabled={isProcessing} className="w-full">
            {isProcessing ? "Обработка..." : "Оплатить через ЮMoney"}
          </Button>
        </div>
      )}
    </div>
  )
}
