"use client";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState, Suspense } from "react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchListingDetail } from "@/store/slices/marketplaceListingDetailSlice";
import { ListingWizard } from "@/components/marketplace/ListingWizard";
import type { WizardData, ListingImage } from "@/components/marketplace/types";
import { Loader2 } from "lucide-react";

function CreateListingContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const editSlug = searchParams.get("edit");

  const dispatch = useAppDispatch();
  const { listing: apiDetail, isLoading } = useAppSelector(
    (s) => s.marketplaceListingDetail,
  );

  const [editListingId, setEditListingId] = useState<number | undefined>();
  const [initialData, setInitialData] = useState<
    Partial<WizardData> | undefined
  >();

  /* Kick off listing fetch when edit slug is present */
  useEffect(() => {
    if (!editSlug) return;
    const parts = editSlug.split("-");
    const id = Number(parts[parts.length - 1]);
    if (!id) return;
    setEditListingId(id);
    dispatch(fetchListingDetail(id));
  }, [editSlug, dispatch]);

  /* Map API detail → WizardData once the fetch completes */
  useEffect(() => {
    if (!apiDetail || !editListingId) return;
    if (apiDetail.id !== editListingId) return;

    /* API returns full URLs — extract just the filename for the edit payload */
    const filenameFromUrl = (url: string) => url.split("/").pop() ?? url;

    const images: ListingImage[] = [];

    /* 1. Cover image first, marked isCover: true */
    if (apiDetail.image) {
      images.push({
        id: "cover-0",
        url: apiDetail.image,
        isCover: true,
        existingFilename: filenameFromUrl(apiDetail.image),
      });
    }

    /* 2. Gallery images (non-cover) */
    for (const g of apiDetail.gallery ?? []) {
      images.push({
        id: String(g.id),
        url: g.image,
        isCover: false,
        galleryId: g.id,
        existingFilename: filenameFromUrl(g.image),
      });
    }

    setInitialData({
      title: apiDetail.title,
      description: apiDetail.description,
      categoryId: apiDetail.category_id,
      category: apiDetail.category_name,
      condition: apiDetail.listing_condition === 1 ? "new" : "used",
      images,
      price: String(apiDetail.price),
      quantity: String(apiDetail.quantity ?? 1),
      originalPrice: "",
      isNegotiable: false,
      city: apiDetail.city,
      area: apiDetail.area,
      pincode: "",
      latitude: apiDetail.latitude ?? "",
      longitude: apiDetail.longitude ?? "",
    });
  }, [apiDetail, editListingId]);

  /* Show loader while fetching listing for edit */
  if (editListingId && (isLoading || !initialData)) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="flex flex-col items-center gap-3">
          <Loader2 size={32} className="animate-spin text-[#fc0000]" />
          <p className="text-sm text-[var(--text-muted)]">Loading listing…</p>
        </div>
      </div>
    );
  }

  return (
    <ListingWizard
      onBack={() => router.back()}
      onComplete={() => router.push("/marketplace/seller/listings")}
      editListingId={editListingId}
      initialData={initialData}
    />
  );
}

export default function MarketplaceCreatePage() {
  return (
    <Suspense>
      <CreateListingContent />
    </Suspense>
  );
}
