import { useState } from "react"
import { useNavigate } from "react-router-dom"
import MainLayout from "../layouts/MainLayout"

import { createDeal } from "../api/deal/newDeal"
import { lookupSellerFromLink } from "../api/seller/from-lookup"
import { mapDealDraftToCreateRequest } from "../adapters/requests/dealCreateAdapter.ts"

import DealLinkStep from "../components/CreateDeal/DealLinkStep"
import DealDetailsStep from "../components/CreateDeal/DealDetailsStep"

import type { SellerLookupInput } from "../api/seller/types.ts"
import type { DealDraft } from "../models/DealDraft"

type Step = "link" | "details"

export default function CreateDealPage() {
  const navigate = useNavigate()

  const [step, setStep] = useState<Step>("link")
  const [loading, setLoading] = useState(false)

  const [dealDraft, setDealDraft] = useState<DealDraft>({
    title: "",
    description: "",
    url: "",
    price: undefined,
    imageUrl: "",
    images: [], // <-- ekle
    seller: {
      id: -1,
      name: "",
      url: null,
    },
    customCompany: undefined,
  })

  /* -------- STEP 1 — LINK -------- */

  const handleLinkSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()

    // OFFLINE DEAL
    if (!dealDraft.url) {
      setStep("details")
      return
    }

    setLoading(true)

    try {
      // 🔥 2. Seller → Lookup Request (ADAPTER)
      const input: SellerLookupInput = { url: dealDraft.url }
      // 🔥 3. API CALL
      const seller = await lookupSellerFromLink(input)
      const nextSeller = seller ?? {
        id: -1,
        name: "",
        url: null,
      }

      setDealDraft((d) => {
        const next = { ...d, seller: nextSeller }
        console.log("NEXT:", next)
        return next
      })
      setStep("details")
    } catch (err) {
      console.error("Seller lookup failed:", err)

      setDealDraft((d) => ({
        ...d,
        seller: {
          id: -1,
          name: "",
          url: null,
        },
      }))

      setStep("details")
    } finally {
      setLoading(false)
    }
  }

  /* -------- FINAL SUBMIT -------- */

  const handleFinalSubmit = async () => {
    try {
      const created = await createDeal(mapDealDraftToCreateRequest(dealDraft))
      const id = created?.id

      if (!id) throw new Error("Deal oluşturuldu ama id dönmedi")

      // ✅ başarıyla oluşturulduysa deal sayfasına git
      navigate(`/deal/${id}`)
    } catch (err: unknown) {
      alert(err instanceof Error ? err.message : "Sunucu hatası")
    }
  }

  function resetForm() {
    setDealDraft({
      title: "",
      description: "",
      url: "",
      price: undefined,
      imageUrl: "",
      images: [],
      seller: {
        id: -1,
        name: "",
        url: null,
      },
      customCompany: undefined,
    })
    setStep("link")
  }

  return (
    <MainLayout>
      <div className="max-w-6xl mx-auto bg-surface p-6 mt-8 rounded-2xl">
        {step === "link" && (
          <DealLinkStep
            url={dealDraft.url}
            loading={loading}
            onChange={(url) =>
              setDealDraft((d) => ({
                ...d,
                url,
              }))
            }
            onSubmit={handleLinkSubmit}
          />
        )}

        {step === "details" && (
          <DealDetailsStep
            data={dealDraft}
            onChange={setDealDraft}
            onBack={() => setStep("link")}
            onSubmit={handleFinalSubmit}
          />
        )}
      </div>
    </MainLayout>
  )
}
