import { useState } from "react"
import MainLayout from "../layouts/MainLayout"
import { createDeal } from "../api/deal/newDeal"

export default function SubmitDealPage() {
  const [title, setTitle] = useState("")
  const [description, setDescription] = useState("")
  const [url, setUrl] = useState("")
  const [imageUrl, setImageUrl] = useState("")
  const [price, setPrice] = useState("")

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    const token = localStorage.getItem("token")
    if (!token) {
      alert("Fırsat eklemek için giriş yapmalısın.")
      return
    }

    try {
      await createDeal( {
        title,
        description,
        url,
        imageUrl,
        price: parseFloat(price),
      })

      alert("Fırsat başarıyla gönderildi.")
      setTitle("")
      setDescription("")
      setUrl("")
      setImageUrl("")
      setPrice("")
    } catch (err: any) {
      alert(err.message || "Sunucu hatası.")
    }
  }

  return (
    <MainLayout>
      <div className="max-w-xl mx-auto bg-surface/50 p-6 rounded-lg shadow-sm mt-8">
        <h1 className="text-2xl font-semibold mb-4 text-primary">Fırsat Yolla</h1>
        <form onSubmit={handleSubmit} className="flex flex-col gap-4">
          <input
            type="text"
            placeholder="Başlık"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            className="border rounded-md px-3 py-2"
            required
          />
          <textarea
            placeholder="Açıklama"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            className="border rounded-md px-3 py-2 h-24"
          />
          <input
            type="url"
            placeholder="Ürün Linki"
            value={url}
            onChange={(e) => setUrl(e.target.value)}
            className="border rounded-md px-3 py-2"
          />
          <input
            type="url"
            placeholder="Görsel URL"
            value={imageUrl}
            onChange={(e) => setImageUrl(e.target.value)}
            className="border rounded-md px-3 py-2"
          />
          <input
            type="number"
            placeholder="Fiyat"
            value={price}
            onChange={(e) => setPrice(e.target.value)}
            className="border rounded-md px-3 py-2"
          />
          <button
            type="submit"
            className="bg-primary text-white py-2 rounded-md hover:bg-primary/90 transition"
          >
            Gönder
          </button>
        </form>
      </div>
    </MainLayout>
  )
}
