// src/pages/DealPage.tsx
import { useEffect, useState } from "react"
import { useParams } from "react-router-dom"

import MainLayout from "../layouts/MainLayout"
import DealImages from "../components/DealDetails/DealImages"
import DealDetails from "../components/DealDetails/DealDetails"
import DealDescription from "../components/DealDetails/DealDescription"
import DealComments from "../components/DealDetails/DealComments"

import { getDealDetail } from "../api/deal/getDeal"
import { mapDealDetailResponseToDealDetail } from "../adapters/responses/dealDetailAdapter"
import type { DealDetail } from "../models/deal/DealDetail"

type DealPageProps = {
  onRequireLogin: () => void
}

export default function DealPage({ onRequireLogin }: DealPageProps) {
  const { id } = useParams()
  const [deal, setDeal] = useState<DealDetail | null>(null)

  useEffect(() => {
    if (!id) return

    const loadDeal = async () => {
      try {
        const apiDeal = await getDealDetail(Number(id))
        const mapped = mapDealDetailResponseToDealDetail(apiDeal)
        setDeal(mapped)
      } catch (err) {
        console.error("Deal yüklenemedi:", err)
      }
    }

    loadDeal()
  }, [id])

  if (!deal) return <p className="p-4">Yükleniyor...</p>

  return (
    <MainLayout>
      <div className="max-w-[1400px] mx-auto px-4 py-8 grid grid-cols-1 lg:grid-cols-4 gap-6">
        {/* Sol: görseller */}
        <div className="lg:col-span-1 flex justify-center items-start">
          <DealImages imageUrl={deal.images[0].url} />
        </div>

        {/* Sağ: temel bilgiler */}
        <div className="lg:col-span-3 flex flex-col gap-6">
          <DealDetails
            title={deal.title}
            price={deal.price?.toString() ?? "-"}
            store={deal.seller.name}
            link={deal.url ?? ""}
            postedBy={deal.user.username}
            postedAgo={deal.createdAt}
          />
        </div>

        {/* Alt: açıklama + yorumlar */}
        <div className="lg:col-span-4 flex flex-col gap-6">
          <section>
            <DealDescription description={deal.description} />
          </section>

          <section>
            <DealComments
              dealId={deal.id}
              onRequireLogin={onRequireLogin}
            />
          </section>
        </div>
      </div>
    </MainLayout>
  )
}
