/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import React, { useEffect, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Check, Upload, X, Loader2 } from "lucide-react";
import ProfileUpdatedModal from "@/components/profile/ProfileUpdatedModal";
import routes from "@/app/routes";
import { useAppDispatch, useAppSelector } from "@/state/hooks";
import { fetchProfile } from "@/state/profile/profileSlice";
import {
  createNewListing,
  updateExistingListing,
  fetchListingById,
  clearListingError,
  clearActiveListing,
  getCategories,
} from "@/state/listing";
import AustralianLocationSelect from "@/components/shared/form/AustralianLocationSelect";
import { AUSTRALIA, toAustralianLocality, type AustralianLocality } from "@/lib/australianLocations";
import { getPhoneError, isAllowedPhoneInput } from "@/lib/validation/phone";

const MAX_PICTURES = 5;
// Australian marketplace: seller listings are priced in AUD only
const LISTING_CURRENCY = "AUD";
// Keep in sync with LISTING_TITLE_MAX / LISTING_DESCRIPTION_MAX in the API
const TITLE_MAX = 250;
const DESCRIPTION_MAX = 20000;

type CategoryOption = { id: string; name: string };

/**
 * Flattens the category tree into select options labelled with their full path
 * ("Main > Sub > Sub-Sub"), mirroring extractCategoryOptions in the admin
 * ProductsManagementTable so sellers see the same structure admins do.
 * Inactive categories (and everything under them) are skipped.
 */
function extractCategoryOptions(nodes: any[], parentPath = ""): CategoryOption[] {
  const options: CategoryOption[] = [];
  for (const node of nodes) {
    if (node.status && node.status !== "active") continue;

    const isNavOrRoot = node.type === "root" || node.type === "navigation" || node.level <= 0;
    const currentPath = isNavOrRoot ? "" : parentPath ? `${parentPath} > ${node.name}` : node.name;
    const id = node.id || node._id;
    if (!isNavOrRoot && id) {
      options.push({ id: String(id), name: currentPath || node.name });
    }

    const children = node.children || node.categories || node.subCategories || node.subSubCategories || [];
    if (Array.isArray(children) && children.length > 0) {
      options.push(...extractCategoryOptions(children, currentPath));
    }
  }
  return options;
}

const STEPS = [
  { step: 1, label: "Personal & Business Info" },
  { step: 2, label: "Product Details" },
  { step: 3, label: "Upload & Submit" },
] as const;

const inputClass =
  "w-full px-3 py-2.5 rounded-md border border-gray-200 text-[16px] text-[#0B0F19] focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-[#2954E8] transition-all";

const textareaClass =
  "w-full px-3 py-2.5 rounded-md border border-gray-200 text-[16px] text-[#0B0F19] focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-[#2954E8] transition-all resize-none";

const StepIndicator = ({ currentStep }: { currentStep: number }) => (
  <div className="mb-8 sm:mb-10">
    <div className="flex items-center justify-center sm:justify-start gap-2 sm:gap-0 sm:max-w-[679px] sm:mx-auto">
      {STEPS.map(({ step, label }, i) => (
        <React.Fragment key={step}>
          <div className="flex items-center gap-2.5">
            <div
              className={`w-6 h-6 rounded-full flex items-center justify-center text-[11px] font-medium shrink-0 ${
                step < currentStep
                  ? "bg-[#2954E8] text-white"
                  : step === currentStep
                  ? "bg-[#2954E8] text-white"
                  : "bg-[#F1F2F5] text-[#8C95A6]"
              }`}
            >
              {step < currentStep ? <Check className="w-3.5 h-3.5" strokeWidth={3} /> : step}
            </div>
            <span
              className={`hidden sm:inline text-[16px] font-medium whitespace-nowrap ${
                step === currentStep ? "text-[#2954E8]" : "text-[#8C95A6]"
              }`}
            >
              {label}
            </span>
          </div>
          {i < STEPS.length - 1 && <div className="w-4 sm:flex-1 h-px bg-[#E5E7EB] sm:mx-4" />}
        </React.Fragment>
      ))}
    </div>
    <p className="sm:hidden text-center text-[13px] font-medium text-[#2954E8] mt-3">
      Step {currentStep} of {STEPS.length}: {STEPS[currentStep - 1].label}
    </p>
  </div>
);

const CONDITION_OPTIONS = [
  { value: "new", label: "New", desc: "(Unused, in original packaging)" },
  { value: "open", label: "Open", desc: "(Box opened, unused or like new)" },
  { value: "excellent", label: "Excellent", desc: "(Minimal signs of wear)" },
  { value: "good", label: "Good", desc: "(Minor scratches or scuffs)" },
  { value: "fair", label: "Fair", desc: "(Visible wear and marks)" },
  { value: "poor", label: "Poor", desc: "(Significant damage or defects)" },
] as const;

const ConditionSelector = ({
  value,
  onChange,
}: {
  value: string;
  onChange: (next: string) => void;
}) => (
  <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
    {CONDITION_OPTIONS.map((opt) => (
      <button
        key={opt.value}
        type="button"
        onClick={() => onChange(opt.value)}
        className={`text-left px-3 py-2.5 rounded-md border transition-colors ${
          value === opt.value
            ? "border-[#2954E8] bg-[#EEF2FF]"
            : "border-gray-200 hover:border-gray-300"
        }`}
      >
        <p className={`text-[16px] font-medium ${value === opt.value ? "text-[#2954E8]" : "text-[#0B0F19]"}`}>
          {opt.label}
        </p>
        <p className="text-[11px] text-[#686262] leading-snug mt-0.5">{opt.desc}</p>
      </button>
    ))}
  </div>
);

interface PictureItem {
  id: string;
  url: string;
  file?: File;
  isExisting?: boolean;
}

const PostAdView = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const editId = searchParams.get("edit");
  const isEditMode = Boolean(editId);

  const dispatch = useAppDispatch();
  const { user } = useAppSelector((state) => state.auth);
  const { profile } = useAppSelector((state) => state.profile);
  const { activeListing, isSubmitting, isDetailsLoading, error } = useAppSelector(
    (state) => state.listing
  );

  const currentSeller = profile || user;

  const [mounted, setMounted] = useState(false);
  const [currentStep, setCurrentStep] = useState(1);
  const [isAddedModalOpen, setIsAddedModalOpen] = useState(false);
  const [validationError, setValidationError] = useState<string | null>(null);
  const lastPrefilledListingId = useRef<string | null>(null);
  const hasPrefilledNewAd = useRef(false);

  // Step 1 state. New ads are prefilled from the logged-in seller (see effect below)
  const [step1, setStep1] = useState({
    category: "",
    firstName: "",
    lastName: "",
    email: "",
    phone: "",
    businessName: "",
    abn: "",
    address: "",
  });
  // Business location: always a real Australian locality (city + postcode + state), or none
  const [businessLocation, setBusinessLocation] = useState<AustralianLocality | null>(null);

  // Step 2 state
  const [step2, setStep2] = useState({
    title: "",
    description: "",
    manufacturer: "",
    modelNumber: "",
    workingCondition: "good",
    physicalCondition: "good",
    price: "",
    negotiable: "yes",
    reasonForSelling: "",
    accessoriesIncluded: "",
    optionalAccessories: "",
    detailedNotes: "",
  });

  // Step 3 state
  const [pictures, setPictures] = useState<PictureItem[]>([]);
  const [isDragging, setIsDragging] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Used-product category tree, flattened to "Main > Sub > Sub-Sub" options
  const [categoryOptions, setCategoryOptions] = useState<CategoryOption[]>([]);

  useEffect(() => {
    setMounted(true);
  }, []);

  // Fetch the used-products category tree (sellers can only post used products)
  useEffect(() => {
    let isMounted = true;
    getCategories({ navigation: "used", tree: true })
      .then((res) => {
        if (!isMounted) return;
        const rawTree = res.data?.data || res.data || [];
        const treeArray = Array.isArray(rawTree) ? rawTree : [rawTree];
        setCategoryOptions(extractCategoryOptions(treeArray));
      })
      .catch((err) => {
        console.error("Failed to load used product categories", err);
        if (isMounted) setValidationError("Failed to load categories. Please refresh the page.");
      });
    return () => {
      isMounted = false;
    };
  }, []);

  // Clean up active listing on unmount
  useEffect(() => {
    return () => {
      dispatch(clearActiveListing());
    };
  }, [dispatch]);

  // Reset tracking when editId changes
  useEffect(() => {
    lastPrefilledListingId.current = null;
  }, [editId]);

  // If user profile is not in state, fetch profile
  useEffect(() => {
    if (mounted && user && !profile) {
      dispatch(fetchProfile());
    }
  }, [mounted, user?.id, user?._id, profile, dispatch]);

  // If edit mode, fetch listing details
  useEffect(() => {
    if (mounted && editId) {
      dispatch(fetchListingById(editId));
    }
  }, [mounted, editId, dispatch]);

  // In edit mode, prefill all form fields and personal details
  useEffect(() => {
    if (!isEditMode || !activeListing) return;

    const currentId = String(activeListing.id || activeListing._id || "");
    if (editId && currentId !== String(editId)) return;

    const sellerObj = typeof activeListing.seller === "object" ? activeListing.seller : null;
    const sellerIdObj = typeof activeListing.sellerId === "object" ? activeListing.sellerId : null;
    const seller = profile || user;

    if (lastPrefilledListingId.current !== currentId) {
      lastPrefilledListingId.current = currentId;

      const catId =
        (typeof activeListing.categoryId === "object"
          ? activeListing.categoryId?._id || activeListing.categoryId?.id
          : activeListing.categoryId) ||
        activeListing.category?.id ||
        activeListing.category?._id ||
        "";

      setStep1({
        category: catId || "",
        firstName:
          activeListing.contactFirstName ||
          sellerObj?.firstName ||
          sellerIdObj?.firstName ||
          seller?.firstName ||
          "",
        lastName:
          activeListing.contactLastName ||
          sellerObj?.lastName ||
          sellerIdObj?.lastName ||
          seller?.lastName ||
          "",
        email:
          activeListing.contactEmail ||
          sellerObj?.email ||
          sellerIdObj?.email ||
          seller?.email ||
          "",
        phone:
          activeListing.contactPhone ||
          sellerObj?.phone ||
          sellerIdObj?.phone ||
          seller?.phone ||
          "",
        businessName:
          activeListing.businessName ||
          sellerObj?.businessName ||
          sellerIdObj?.businessName ||
          seller?.businessName ||
          seller?.companyName ||
          "",
        abn:
          activeListing.australianABN ||
          sellerObj?.australianABN ||
          sellerIdObj?.australianABN ||
          seller?.australianABN ||
          "",
        address:
          activeListing.businessAddress ||
          sellerObj?.businessAddress ||
          sellerIdObj?.businessAddress ||
          seller?.businessAddress ||
          seller?.address ||
          "",
      });
      setBusinessLocation(
        toAustralianLocality(activeListing.businessCity, activeListing.businessPostalCode, activeListing.businessState) ||
          toAustralianLocality(
            seller?.businessCity || seller?.city,
            seller?.businessPostalCode || seller?.postalCode || seller?.postcode,
            seller?.businessState || seller?.state
          )
      );

      setStep2({
        title: activeListing.title || "",
        description: activeListing.description || "",
        manufacturer: activeListing.manufacturer || activeListing.brand || "",
        modelNumber: activeListing.modelNumber || "",
        workingCondition: activeListing.workingCondition || "good",
        physicalCondition: activeListing.physicalCondition || "good",
        price: activeListing.price !== undefined ? String(activeListing.price) : "",
        negotiable: activeListing.isPriceNegotiable ? "yes" : "no",
        reasonForSelling: activeListing.reasonForSale || "",
        accessoriesIncluded: activeListing.accessoriesIncluded || "",
        optionalAccessories: activeListing.optionalAccessories || "",
        detailedNotes: activeListing.detailedNotes || "",
      });

      if (Array.isArray(activeListing.images) && activeListing.images.length > 0) {
        setPictures(
          activeListing.images.map((img: any, index: number) => {
            const url = typeof img === "string" ? img : img?.url || "";
            return {
              id: `existing-${index}-${url}`,
              url,
              isExisting: true,
            };
          })
        );
      }
    } else if (seller) {
      // If profile loaded after activeListing, backfill any empty contact/business fields
      setStep1((prev) => ({
        ...prev,
        firstName: prev.firstName || seller.firstName || "",
        lastName: prev.lastName || seller.lastName || "",
        email: prev.email || seller.email || "",
        phone: prev.phone || seller.phone || "",
        businessName: prev.businessName || seller.businessName || seller.companyName || "",
        abn: prev.abn || seller.australianABN || "",
        address: prev.address || seller.businessAddress || seller.address || "",
      }));
      setBusinessLocation(
        (prev) =>
          prev ||
          toAustralianLocality(
            seller.businessCity || seller.city,
            seller.businessPostalCode || seller.postalCode || seller.postcode,
            seller.businessState || seller.state
          )
      );
    }
  }, [isEditMode, activeListing, editId, profile, user]);

  // New ad: prefill contact details (and location, if the profile has a complete one) from the
  // logged-in seller, once. The seller can still change them for this listing.
  useEffect(() => {
    if (isEditMode || hasPrefilledNewAd.current || !currentSeller) return;
    hasPrefilledNewAd.current = true;

    setStep1((prev) => ({
      ...prev,
      firstName: prev.firstName || currentSeller.firstName || "",
      lastName: prev.lastName || currentSeller.lastName || "",
      email: prev.email || currentSeller.email || "",
      phone: prev.phone || currentSeller.phone || "",
    }));
    setBusinessLocation(
      (prev) =>
        prev ||
        toAustralianLocality(currentSeller.city, currentSeller.postalCode || currentSeller.postcode, currentSeller.state)
    );
  }, [isEditMode, currentSeller]);

  // Step 1 Validation (Category, Email, Phone, ABN, Postcode)
  const validateStep1 = (): boolean => {
    if (!step1.category) {
      setValidationError("Please select a product category.");
      return false;
    }

    const emailToValidate = step1.email.trim();
    if (emailToValidate) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(emailToValidate)) {
        setValidationError("Please enter a valid email address (e.g. name@example.com).");
        return false;
      }
    }

    const phoneError = step1.phone.trim() ? getPhoneError(step1.phone.trim()) : null;
    if (phoneError) {
      setValidationError(phoneError);
      return false;
    }

    const abnToValidate = step1.abn.trim();
    if (abnToValidate) {
      const abnDigits = abnToValidate.replace(/\D/g, "");
      if (abnDigits.length !== 11) {
        setValidationError("Australian ABN must contain exactly 11 digits (e.g. 51 824 753 556).");
        return false;
      }
    }

    setValidationError(null);
    return true;
  };

  // Step 2 Validation (Title, Price, Character Lengths)
  const validateStep2 = (): boolean => {
    if (!step2.title.trim()) {
      setValidationError("Product title is required.");
      return false;
    }
    if (step2.title.trim().length < 3) {
      setValidationError("Title must be at least 3 characters long.");
      return false;
    }
    // Older listings may have a long title; ask the seller to shorten it when editing
    if (step2.title.trim().length > TITLE_MAX) {
      setValidationError(`Title must be ${TITLE_MAX} characters or fewer. Move the extra detail into the description.`);
      return false;
    }
    if (!step2.description.trim()) {
      setValidationError("Product description is required.");
      return false;
    }
    if (!step2.price.trim() || isNaN(Number(step2.price))) {
      setValidationError("A valid price is required.");
      return false;
    }
    if (Number(step2.price) <= 0) {
      setValidationError("Price must be a number greater than $0.");
      return false;
    }
    setValidationError(null);
    return true;
  };

  // Handlers for Step 1
  const handleStep1Change =
    (field: keyof typeof step1) =>
    (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
      const value = e.target.value;

      // Numeric & format constraints on input
      if (field === "phone") {
        // Max 15 digits; only digits, spaces, ( ) - and a leading +
        if (!isAllowedPhoneInput(value)) return;
      } else if (field === "abn") {
        // Digits and spaces only, max 11 digits
        if (!/^[\d\s]*$/.test(value) || value.replace(/\D/g, "").length > 11) return;
      }

      setStep1((prev) => ({ ...prev, [field]: value }));
      setValidationError(null);
    };

  // Handlers for Step 2
  const handleStep2Change =
    (field: keyof typeof step2) =>
    (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
      const value = e.target.value;

      // Price: only allow positive numbers with up to 2 decimal places
      if (field === "price") {
        if (value !== "" && !/^\d*\.?\d{0,2}$/.test(value)) return;
      }

      setStep2((prev) => ({ ...prev, [field]: value }));
      setValidationError(null);
    };

  // Handlers for Step 3 files
  const addFiles = (files: FileList | null) => {
    if (!files) return;
    const remaining = MAX_PICTURES - pictures.length;
    if (remaining <= 0) {
      setValidationError("You can upload a maximum of 5 pictures.");
      return;
    }

    const next: PictureItem[] = Array.from(files)
      .slice(0, remaining)
      .map((file) => ({
        id: `${file.name}-${file.lastModified}-${Math.random()}`,
        url: URL.createObjectURL(file),
        file,
      }));

    setPictures((prev) => [...prev, ...next]);
    setValidationError(null);
  };

  const removePicture = (id: string) => {
    setPictures((prev) => prev.filter((p) => p.id !== id));
  };

  const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    setIsDragging(false);
    addFiles(e.dataTransfer.files);
  };

  // Final Submit
  const handleFinalSubmit = async () => {
    setValidationError(null);
    dispatch(clearListingError());

    if (!validateStep1()) {
      setCurrentStep(1);
      return;
    }

    if (!validateStep2()) {
      setCurrentStep(2);
      return;
    }

    const formData = new FormData();

    // Step 1: Category
    if (step1.category && /^[0-9a-fA-F]{24}$/.test(step1.category)) {
      formData.append("categoryId", step1.category);
    }

    // Step 1: Contact & Business Info:
    // If not filled by seller, fallback to current seller details
    const contactFirstName = step1.firstName.trim() || currentSeller?.firstName || "";
    const contactLastName = step1.lastName.trim() || currentSeller?.lastName || "";
    const contactEmail = step1.email.trim() || currentSeller?.email || "";
    const contactPhone = step1.phone.trim() || currentSeller?.phone || "";
    const businessName = step1.businessName.trim() || currentSeller?.businessName || "";
    const australianABN = step1.abn.trim() || currentSeller?.australianABN || "";
    const businessAddress =
      step1.address.trim() || currentSeller?.businessAddress || currentSeller?.address || "";
    // Location is sent only as a complete, picked Australian locality (validated by the API too)
    const location =
      businessLocation ||
      toAustralianLocality(
        currentSeller?.city,
        currentSeller?.postalCode || currentSeller?.postcode,
        currentSeller?.state
      );

    if (contactFirstName) formData.append("contactFirstName", contactFirstName);
    if (contactLastName) formData.append("contactLastName", contactLastName);
    if (contactEmail) formData.append("contactEmail", contactEmail);
    if (contactPhone) formData.append("contactPhone", contactPhone);
    if (businessName) formData.append("businessName", businessName);
    if (australianABN) formData.append("australianABN", australianABN);
    if (businessAddress) formData.append("businessAddress", businessAddress);
    if (location) {
      formData.append("businessCity", location.city);
      formData.append("businessState", location.state);
      formData.append("businessPostalCode", location.postcode);
      formData.append("businessCountry", AUSTRALIA);
    }

    // Step 2 fields
    formData.append("title", step2.title.trim());
    formData.append("description", step2.description.trim());
    if (step2.manufacturer) formData.append("manufacturer", step2.manufacturer.trim());
    if (step2.modelNumber) formData.append("modelNumber", step2.modelNumber.trim());
    formData.append("workingCondition", step2.workingCondition);
    formData.append("physicalCondition", step2.physicalCondition);
    formData.append("price", String(Number(step2.price)));
    // Seller listings are always priced in AUD (enforced by the API too)
    formData.append("currency", LISTING_CURRENCY);
    formData.append("isPriceNegotiable", String(step2.negotiable === "yes"));
    if (step2.reasonForSelling) formData.append("reasonForSale", step2.reasonForSelling.trim());
    if (step2.accessoriesIncluded) formData.append("accessoriesIncluded", step2.accessoriesIncluded.trim());
    if (step2.optionalAccessories) formData.append("optionalAccessories", step2.optionalAccessories.trim());
    if (step2.detailedNotes) formData.append("detailedNotes", step2.detailedNotes.trim());

    // Step 3 images
    const existingImages: string[] = [];
    pictures.forEach((pic) => {
      if (pic.file) {
        formData.append("images", pic.file);
      } else if (pic.isExisting && pic.url) {
        existingImages.push(pic.url);
      }
    });

    if (existingImages.length > 0) {
      existingImages.forEach((imgUrl) => {
        formData.append("relativePath", imgUrl);
      });
    }

    try {
      let actionResult: any;
      if (isEditMode && editId) {
        actionResult = await dispatch(
          updateExistingListing({ listingId: editId, data: formData })
        );
      } else {
        actionResult = await dispatch(createNewListing(formData));
      }

      if (
        createNewListing.fulfilled.match(actionResult) ||
        updateExistingListing.fulfilled.match(actionResult)
      ) {
        setIsAddedModalOpen(true);
      }
    } catch {
      setValidationError("An unexpected error occurred while saving the listing");
    }
  };

  const displayError = validationError || error;

  if (
    isEditMode &&
    (isDetailsLoading ||
      !activeListing ||
      (editId && String(activeListing.id || activeListing._id) !== String(editId)))
  ) {
    return (
      <div className="bg-white min-h-[60vh] flex items-center justify-center">
        <div className="flex flex-col items-center gap-3">
          <Loader2 className="w-8 h-8 animate-spin text-[#2954E8]" />
          <p className="text-[14px] text-[#6B7A99]">Loading listing details...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white min-h-screen">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-10 pt-8 pb-16">
        <p className="text-[13px] text-[#6B7A99] mb-4">
          {isEditMode ? "Edit Ad" : "Post an Ad"}
        </p>
        <h1 className="font-helvetica text-[24px] leading-[32px] font-medium text-[#000000] mb-8">
          {isEditMode ? "Edit Listing" : "Post an Ad"}
        </h1>

        <div className="max-w-[1096px] sm:pl-10">
          <StepIndicator currentStep={currentStep} />

          {displayError && (
            <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg text-red-700 text-[13px] font-medium">
              {displayError}
            </div>
          )}

          {/* STEP 1: Personal & Business Info */}
          {currentStep === 1 && (
            <form
              onSubmit={(e) => {
                e.preventDefault();
                if (!validateStep1()) return;
                setCurrentStep(2);
              }}
            >
              <p className="text-[18px] font-medium text-[#0B0F19] mb-4">
                Category &amp; Personal Info
              </p>

              <div className="space-y-1.5 mb-4">
                <label className="text-[16px] font-medium text-[#0B0F19]">Category *</label>
                <select
                  value={step1.category}
                  onChange={handleStep1Change("category")}
                  className={inputClass}
                >
                  <option value="">Select Category</option>
                  {step1.category &&
                    !categoryOptions.some((c) => c.id === String(step1.category)) && (
                      <option value={step1.category}>
                        {activeListing?.categoryName ||
                          activeListing?.category?.name ||
                          "Selected Category"}
                      </option>
                    )}
                  {categoryOptions.map((c) => (
                    <option key={c.id} value={c.id}>
                      {c.name}
                    </option>
                  ))}
                </select>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-4">
                <div className="space-y-1.5">
                  <label className="text-[16px] font-medium text-[#0B0F19]">First Name</label>
                  <input
                    value={step1.firstName}
                    onChange={handleStep1Change("firstName")}
                    maxLength={50}
                    placeholder={currentSeller?.firstName || "First Name"}
                    className={inputClass}
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[16px] font-medium text-[#0B0F19]">Last Name</label>
                  <input
                    value={step1.lastName}
                    onChange={handleStep1Change("lastName")}
                    maxLength={50}
                    placeholder={currentSeller?.lastName || "Last Name"}
                    className={inputClass}
                  />
                </div>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-8">
                <div className="space-y-1.5">
                  <label className="text-[16px] font-medium text-[#0B0F19]">Your E-Mail</label>
                  <input
                    type="email"
                    value={step1.email}
                    onChange={handleStep1Change("email")}
                    maxLength={100}
                    placeholder={currentSeller?.email || "Your E-Mail"}
                    className={inputClass}
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[16px] font-medium text-[#0B0F19]">Your Phone</label>
                  <input
                    type="tel"
                    inputMode="tel"
                    value={step1.phone}
                    onChange={handleStep1Change("phone")}
                    placeholder={currentSeller?.phone || "Your Phone (e.g. 0412 345 678)"}
                    className={inputClass}
                  />
                </div>
              </div>

              <p className="text-[18px] font-medium text-[#0B0F19] mb-4">
                Business Details (Optional)
              </p>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-4">
                <div className="space-y-1.5">
                  <label className="text-[16px] font-medium text-[#0B0F19]">Business Name</label>
                  <input
                    value={step1.businessName}
                    onChange={handleStep1Change("businessName")}
                    maxLength={100}
                    placeholder={currentSeller?.businessName || "e.g. Outback Trading Co"}
                    className={inputClass}
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[16px] font-medium text-[#0B0F19]">Australian ABN</label>
                  <input
                    inputMode="numeric"
                    value={step1.abn}
                    onChange={handleStep1Change("abn")}
                    maxLength={20}
                    placeholder={currentSeller?.australianABN || "e.g. 51 824 753 556"}
                    className={inputClass}
                  />
                </div>
              </div>

              <div className="space-y-1.5 mb-4">
                <label className="text-[16px] font-medium text-[#0B0F19]">Address</label>
                <input
                  value={step1.address}
                  onChange={handleStep1Change("address")}
                  maxLength={150}
                  placeholder={
                    currentSeller?.businessAddress ||
                    currentSeller?.address ||
                    "e.g. 42 Wallaby Way, Sydney"
                  }
                  className={inputClass}
                />
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-4">
                <div className="space-y-1.5">
                  <label htmlFor="post-ad-location-input" className="text-[16px] font-medium text-[#0B0F19]">City / Town</label>
                  <AustralianLocationSelect
                    instanceId="post-ad-location"
                    size="md"
                    value={businessLocation}
                    onChange={(locality) => {
                      setBusinessLocation(locality);
                      setValidationError(null);
                    }}
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[16px] font-medium text-[#0B0F19]">State / Territory</label>
                  <input
                    value={businessLocation?.state || ""}
                    readOnly
                    tabIndex={-1}
                    placeholder="Auto-filled"
                    className={inputClass + " bg-[#F7F8FA] text-[#686262] cursor-not-allowed"}
                  />
                </div>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-8">
                <div className="space-y-1.5">
                  <label className="text-[16px] font-medium text-[#0B0F19]">Postcode</label>
                  <input
                    value={businessLocation?.postcode || ""}
                    readOnly
                    tabIndex={-1}
                    placeholder="Auto-filled"
                    aria-label="Postcode (filled from the selected suburb)"
                    className={inputClass + " bg-[#F7F8FA] text-[#686262] cursor-not-allowed"}
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[16px] font-medium text-[#0B0F19]">Country</label>
                  <input
                    value={AUSTRALIA}
                    readOnly
                    tabIndex={-1}
                    className={inputClass + " bg-[#F7F8FA] text-[#686262] cursor-not-allowed"}
                  />
                </div>
              </div>

              <div className="flex items-center justify-end gap-3">
                <button
                  type="button"
                  onClick={() => router.push(routes.profile)}
                  className="px-5 py-2.5 text-[16px] font-medium text-[#0B0F19] bg-white border border-gray-200 rounded-md hover:bg-gray-50 transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-5 py-2.5 text-[16px] font-medium text-white bg-[#2954E8] rounded-md hover:bg-[#1f42c2] transition-colors"
                >
                  Save &amp; Next
                </button>
              </div>
            </form>
          )}

          {/* STEP 2: Product Details */}
          {currentStep === 2 && (
            <form
              onSubmit={(e) => {
                e.preventDefault();
                if (!validateStep2()) return;
                setCurrentStep(3);
              }}
            >
              <p className="text-[18px] font-medium text-[#0B0F19] mb-4">Product Details</p>

              <div className="space-y-1.5 mb-4">
                <div className="flex items-center justify-between">
                  <label className="text-[16px] font-medium text-[#0B0F19]">Product Title *</label>
                  <span className="text-[11px] text-[#8C95A6]">
                    {step2.title.length}/{TITLE_MAX}
                  </span>
                </div>
                <input
                  value={step2.title}
                  onChange={handleStep2Change("title")}
                  maxLength={TITLE_MAX}
                  placeholder="e.g. Canon EOS R5 Camera Kit"
                  className={inputClass}
                  required
                />
              </div>

              <div className="space-y-1.5 mb-4">
                <div className="flex items-center justify-between">
                  <label className="text-[16px] font-medium text-[#0B0F19]">Product Description *</label>
                  <span className="text-[11px] text-[#8C95A6]">
                    {step2.description.length}/{DESCRIPTION_MAX}
                  </span>
                </div>
                <textarea
                  value={step2.description}
                  onChange={handleStep2Change("description")}
                  maxLength={DESCRIPTION_MAX}
                  rows={4}
                  placeholder="Describe the item: what it is, how it's been used, its history and anything a buyer should know."
                  className={textareaClass}
                  required
                />
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-4">
                <div className="space-y-1.5">
                  <label className="text-[16px] font-medium text-[#0B0F19]">Manufacturer</label>
                  <input
                    value={step2.manufacturer}
                    onChange={handleStep2Change("manufacturer")}
                    maxLength={60}
                    placeholder="e.g. Canon"
                    className={inputClass}
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[16px] font-medium text-[#0B0F19]">Model Number</label>
                  <input
                    value={step2.modelNumber}
                    onChange={handleStep2Change("modelNumber")}
                    maxLength={60}
                    placeholder="e.g. EOS R5"
                    className={inputClass}
                  />
                </div>
              </div>

              <div className="space-y-1.5 mb-4">
                <label className="text-[16px] font-medium text-[#0B0F19]">Working Condition</label>
                <ConditionSelector
                  value={step2.workingCondition}
                  onChange={(v) => setStep2((prev) => ({ ...prev, workingCondition: v }))}
                />
              </div>

              <div className="space-y-1.5 mb-4">
                <label className="text-[16px] font-medium text-[#0B0F19]">Physical Condition</label>
                <ConditionSelector
                  value={step2.physicalCondition}
                  onChange={(v) => setStep2((prev) => ({ ...prev, physicalCondition: v }))}
                />
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-4">
                <div className="space-y-1.5">
                  <label className="text-[16px] font-medium text-[#0B0F19]">Budget / Price *</label>
                  <input
                    value={step2.price}
                    onChange={handleStep2Change("price")}
                    placeholder="e.g. 2500"
                    type="text"
                    inputMode="decimal"
                    maxLength={12}
                    className={inputClass}
                    required
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[16px] font-medium text-[#0B0F19]">Currency</label>
                  <input
                    value={LISTING_CURRENCY}
                    readOnly
                    tabIndex={-1}
                    aria-label="Currency (Australian dollars only)"
                    className={inputClass + " bg-[#F7F8FA] text-[#686262] cursor-not-allowed"}
                  />
                </div>
              </div>

              <div className="space-y-1.5 mb-8">
                <label className="text-[16px] font-medium text-[#0B0F19]">Is Price Negotiable?</label>
                <div className="flex items-center gap-6">
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="radio"
                      name="negotiable"
                      checked={step2.negotiable === "yes"}
                      onChange={() => setStep2((prev) => ({ ...prev, negotiable: "yes" }))}
                      className="w-3.5 h-3.5 accent-[#2954E8]"
                    />
                    <span className="text-[16px] text-[#0B0F19]">Yes, open to reasonable offers</span>
                  </label>
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="radio"
                      name="negotiable"
                      checked={step2.negotiable === "no"}
                      onChange={() => setStep2((prev) => ({ ...prev, negotiable: "no" }))}
                      className="w-3.5 h-3.5 accent-[#2954E8]"
                    />
                    <span className="text-[16px] text-[#0B0F19]">No, firm price</span>
                  </label>
                </div>
              </div>

              <p className="text-[18px] font-medium text-[#0B0F19] mb-4">
                Additional Information &amp; Notes
              </p>

              <div className="space-y-1.5 mb-4">
                <div className="flex items-center justify-between">
                  <label className="text-[16px] font-medium text-[#0B0F19]">Reason for Selling</label>
                  <span className="text-[11px] text-[#8C95A6]">{step2.reasonForSelling.length}/500</span>
                </div>
                <textarea
                  value={step2.reasonForSelling}
                  onChange={handleStep2Change("reasonForSelling")}
                  maxLength={500}
                  rows={3}
                  placeholder="Write here.."
                  className={textareaClass}
                />
              </div>

              <div className="space-y-1.5 mb-4">
                <div className="flex items-center justify-between">
                  <label className="text-[16px] font-medium text-[#0B0F19]">Accessories Included</label>
                  <span className="text-[11px] text-[#8C95A6]">{step2.accessoriesIncluded.length}/1000</span>
                </div>
                <textarea
                  value={step2.accessoriesIncluded}
                  onChange={handleStep2Change("accessoriesIncluded")}
                  maxLength={1000}
                  rows={3}
                  placeholder="Write here.."
                  className={textareaClass}
                />
              </div>

              <div className="space-y-1.5 mb-4">
                <div className="flex items-center justify-between">
                  <label className="text-[16px] font-medium text-[#0B0F19]">Optional Accessories</label>
                  <span className="text-[11px] text-[#8C95A6]">{step2.optionalAccessories.length}/1000</span>
                </div>
                <textarea
                  value={step2.optionalAccessories}
                  onChange={handleStep2Change("optionalAccessories")}
                  maxLength={1000}
                  rows={3}
                  placeholder="Write here.."
                  className={textareaClass}
                />
              </div>

              <div className="space-y-1.5 mb-8">
                <div className="flex items-center justify-between">
                  <label className="text-[16px] font-medium text-[#0B0F19]">
                    Detailed Notes / Specifications
                  </label>
                  <span className="text-[11px] text-[#8C95A6]">{step2.detailedNotes.length}/2000</span>
                </div>
                <textarea
                  value={step2.detailedNotes}
                  onChange={handleStep2Change("detailedNotes")}
                  maxLength={2000}
                  rows={3}
                  placeholder="e.g. Sensor size, recording formats, firmware version, hours used..."
                  className={textareaClass}
                />
              </div>

              <div className="flex items-center justify-end gap-3">
                <button
                  type="button"
                  onClick={() => setCurrentStep(1)}
                  className="px-5 py-2.5 text-[16px] font-medium text-[#0B0F19] bg-white border border-gray-200 rounded-md hover:bg-gray-50 transition-colors"
                >
                  Back
                </button>
                <button
                  type="submit"
                  className="px-5 py-2.5 text-[16px] font-medium text-white bg-[#2954E8] rounded-md hover:bg-[#1f42c2] transition-colors"
                >
                  Save &amp; Next
                </button>
              </div>
            </form>
          )}

          {/* STEP 3: Upload Pictures & Submit */}
          {currentStep === 3 && (
            <div>
              <p className="text-[18px] font-medium text-[#0B0F19] mb-4">Upload Pictures</p>

              <div
                onClick={() => fileInputRef.current?.click()}
                onDragOver={(e) => {
                  e.preventDefault();
                  setIsDragging(true);
                }}
                onDragLeave={() => setIsDragging(false)}
                onDrop={handleDrop}
                className={`flex flex-col items-center justify-center text-center py-10 px-6 rounded-lg border-2 border-dashed cursor-pointer transition-colors ${
                  isDragging
                    ? "border-[#2954E8] bg-[#EEF2FF]"
                    : "border-gray-300 bg-[#F7F8FA] hover:bg-[#F1F2F5]"
                }`}
              >
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/png,image/jpeg,image/jpg"
                  multiple
                  className="hidden"
                  onChange={(e) => addFiles(e.target.files)}
                />
                <Upload className="w-6 h-6 text-[#2954E8] mb-3" strokeWidth={2} />
                <p className="text-[16px] font-medium text-[#2954E8] mb-1">
                  Click to upload or drag and drop
                </p>
                <p className="text-[11px] text-[#8C95A6]">
                  Maximum {MAX_PICTURES} pictures. Supports PNG, JPG or JPEG up to 2MB each.
                </p>
              </div>

              {pictures.length > 0 && (
                <div className="flex flex-wrap gap-3 mt-4">
                  {pictures.map((pic) => (
                    <div
                      key={pic.id}
                      className="relative w-24 h-24 rounded-lg overflow-hidden border border-gray-200 bg-gray-50"
                    >
                      <img
                        src={pic.url}
                        alt="Upload preview"
                        className="w-full h-full object-cover"
                      />
                      <button
                        type="button"
                        onClick={() => removePicture(pic.id)}
                        aria-label="Remove picture"
                        className="absolute top-1.5 right-1.5 w-5 h-5 rounded-full bg-black/70 text-white flex items-center justify-center hover:bg-black transition-colors"
                      >
                        <X className="w-3 h-3" strokeWidth={2.5} />
                      </button>
                    </div>
                  ))}
                </div>
              )}

              <div className="flex items-center justify-end gap-3 mt-8">
                <button
                  type="button"
                  onClick={() => setCurrentStep(2)}
                  className="px-5 py-2.5 text-[16px] font-medium text-[#0B0F19] bg-white border border-gray-200 rounded-md hover:bg-gray-50 transition-colors"
                >
                  Back
                </button>
                <button
                  type="button"
                  onClick={handleFinalSubmit}
                  disabled={isSubmitting}
                  className="inline-flex items-center gap-2 px-6 py-2.5 text-[16px] font-medium text-white bg-[#2954E8] rounded-md hover:bg-[#1f42c2] transition-colors disabled:bg-gray-400 cursor-pointer"
                >
                  {isSubmitting && <Loader2 className="w-4 h-4 animate-spin" />}
                  {isSubmitting
                    ? "Submitting..."
                    : isEditMode
                    ? "Update Listing"
                    : "Submit Listing"}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>

      <ProfileUpdatedModal
        isOpen={isAddedModalOpen}
        onClose={() => {
          setIsAddedModalOpen(false);
          // After adding or updating, land on the seller's ads list
          router.push(routes.myListings);
        }}
        title={isEditMode ? "Product Updated Successfully" : "Product Added Successfully"}
        message={
          <>
            {isEditMode
              ? "Your listing updates have been saved successfully."
              : "Your product has been listed successfully and is now live."}
            <br />
            You can view and manage it anytime in your profile under My Ads.
          </>
        }
      />
    </div>
  );
};

export default PostAdView;
