import { useState } from "react"
import MainLayout from "../layouts/MainLayout"

import { createDeal } from "../api/deal/newDeal"
import { lookupSellerFromLink } from "../api/seller/from-lookup"

import { mapSellerFromLookupRequest } from "../adapters/requests/sellerFromLookupAdapter"
import { mapSellerFromLookupResponse } from "../adapters/responses/sellerFromLookupAdapter"
import { mapDealDraftToCreateRequest } from "../adapters/requests/dealCreateAdapter.ts"

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

import type { DealDraft } from "../models/DealDraft"
import type { Seller } from "../models/seller/Seller"

type Step = "link" | "details"

export default function CreateDealPage() {
  const [step, setStep] = useState<Step>("link")
  const [loading, setLoading] = useState(false)

  const [dealDraft, setDealDraft] = useState<DealDraft>({
    title: "",
    description: "",
    url: "",
    price: undefined,
    imageUrl: "",
    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 {
      // 🔥 1. URL → Seller (temporary)
      const tempSeller: Seller = {
        id: -1,
        name: "",
        url: dealDraft.url,
      }

      // 🔥 2. Seller → Lookup Request (ADAPTER)
      const lookupRequest =
        mapSellerFromLookupRequest(tempSeller)

      // 🔥 3. API CALL
      const lookupResponse =
        await lookupSellerFromLink(lookupRequest)

      // 🔥 4. Response → Seller (ADAPTER)
      const seller =
        mapSellerFromLookupResponse(lookupResponse)

      setDealDraft(d => ({
        ...d,
        seller,
      }))

      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 {
      await createDeal(
        mapDealDraftToCreateRequest(dealDraft)
      )

      alert("Fırsat başarıyla gönderildi.")
      resetForm()
    } catch (err: unknown) {
      alert(err instanceof Error ? err.message : "Sunucu hatası")
    }
  }

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

  return (
    <MainLayout>
      <div className="max-w-xl mx-auto bg-surface p-6 mt-8 rounded-lg">
        {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>
  )
}
