"use client";

import { useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import Field from "@/components/ui/Field";
import PropertyListingFormCard from "@/components/listings/PropertyListingFormCard";
import ProjectListingFormCard from "@/components/listings/ProjectListingFormCard";
import { propertyTypes } from "@/data/listingForm";
import { useAuth } from "@/context/AuthContext";
import { createMarketingProperty } from "@/services/userPanelService";
import { toast } from "sonner";

export default function ListingsPage() {
  const { token } = useAuth();
  const [step, setStep] = useState<1 | 2 | 3>(1);
  const [licenseSource, setLicenseSource] = useState<"us" | "broker" | "">("");
  const [listingKind, setListingKind] = useState<"unit" | "projects">("unit");
  const [isLoading, setIsLoading] = useState(false);
  // Store city/district labels for building the address string
  const [cityLabel, setCityLabel] = useState("");
  const [districtLabel, setDistrictLabel] = useState("");

  const showMarketingStep = useMemo(() => licenseSource === "us", [licenseSource]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!token) {
      toast.error("يرجى تسجيل الدخول لإضافة إعلان");
      return;
    }

    setIsLoading(true);
    try {
      const formEl = e.currentTarget as HTMLFormElement;
      // Since components now stay in DOM with display: none, FormData will contain ALL fields
      const currentFormData = new FormData(formEl);
      const adaptedFormData = new FormData();

      // Fields that have no backend column yet — strip from payload
      const unsupportedFields = [
        "videoLink", "deedImage", "idImage", "propertyServices", "features",
        "buildingCode", "warrantiesAuthorityText", "obligations", "facade",
        "streetNumber", "halls", "licenseSource", "listingKind",
        "saiSource", "saiPercentage", "saiAmount", "projectPdfFile", "projectPdfLink",
        "developerLogo",
      ];

      // Mapping logic: Translate frontend FormData into backend expectations
      for (const [key, value] of currentFormData.entries()) {
        let adaptedKey = key;
        let adaptedValue = value;

        if (key === "city") adaptedKey = "city_id";
        if (key === "neighborhood") adaptedKey = "districts_id";
        if (key === "governorate") adaptedKey = "governorate_id";
        if (key === "details") adaptedKey = "description";
        if (key === "area" || key === "areaFrom") adaptedKey = "spaces";
        if (key === "areaTo") adaptedKey = "to_space";
        if (key === "bedrooms" || key === "bedroomsFrom") adaptedKey = "room";
        if (key === "bathrooms" || key === "bathroomsFrom") adaptedKey = "bathroom";
        if (key === "floors") adaptedKey = "floor";
        if (key === "priceFrom") adaptedKey = "price";
        if (key === "priceTo") adaptedKey = "price_to";
        if (key === "requestType") adaptedKey = "section";
        if (key === "googleMapsLink") adaptedKey = "location_link";
        if (key === "deedImage") adaptedKey = "instrument_image";
        if (key === "idImage") adaptedKey = "national_image";

        if (key === "propertyType") continue;

        if (unsupportedFields.includes(key) || key.includes("features") || key.includes("propertyServices") || key.startsWith("subUnits")) {
          // Skip unsupported fields but allow our mapped ones
          if (adaptedKey !== "instrument_image" && adaptedKey !== "national_image") {
            continue;
          }
        }

        // Section translation
        if (adaptedKey === "section") {
          if (value === "buy") adaptedValue = "for sale";
          if (value === "rent") adaptedValue = "for rent";
        }

        // Numeric Sanitization: Remove commas/spaces and ensures valid numeric strings
        const numericKeys = ["price", "price_to", "spaces", "to_space", "room", "floor", "bathroom"];
        if (numericKeys.includes(adaptedKey) && typeof adaptedValue === "string") {
          const sanitizedValue = adaptedValue.replace(/[, ]/g, "");
          adaptedValue = sanitizedValue && !isNaN(Number(sanitizedValue)) ? sanitizedValue : "0";
        }

        // Filter out empty File objects to avoid backend validation issues
        if (adaptedValue instanceof File && adaptedValue.size === 0) {
          continue;
        }

        adaptedFormData.append(adaptedKey, adaptedValue);
      }

      // Fix: Auto-generate required 'address' from saved or current labels
      let finalCity = cityLabel;
      let finalDist = districtLabel;
      if (!finalCity || !finalDist) {
        const cityId = currentFormData.get("city");
        const distId = currentFormData.get("neighborhood");
        const cityOpt = formEl.querySelector(`select[name="city"] option[value="${cityId}"]`) as HTMLOptionElement;
        const distOpt = formEl.querySelector(`select[name="neighborhood"] option[value="${distId}"]`) as HTMLOptionElement;
        if (cityOpt?.text) finalCity = cityOpt.text;
        if (distOpt?.text) finalDist = distOpt.text;
      }
      const addressString = [finalDist, finalCity].filter(Boolean).join("، ") || "المملكة العربية السعودية";
      adaptedFormData.set("address", addressString);

      // Set type_of_property
      if (listingKind === "projects") {
        adaptedFormData.set("type_of_property", "project");
      } else {
        const pType = currentFormData.get("propertyType");
        adaptedFormData.set("type_of_property", String(pType || "apartment"));
      }

      // Required backend defaults for missing optional fields
      if (!adaptedFormData.has("ad_number") || !adaptedFormData.get("ad_number")) adaptedFormData.set("ad_number", "AUTO");
      if (!adaptedFormData.has("handover") || !adaptedFormData.get("handover")) adaptedFormData.set("handover", "N/A");
      if (!adaptedFormData.has("price_of_meter") || !adaptedFormData.get("price_of_meter")) adaptedFormData.set("price_of_meter", "0");
      if (!adaptedFormData.has("payment") || !adaptedFormData.get("payment")) adaptedFormData.set("payment", "cash");
      if (!adaptedFormData.has("advertiser_type") || !adaptedFormData.get("advertiser_type")) adaptedFormData.set("advertiser_type", "owner");

      const response = await createMarketingProperty(token, adaptedFormData);
      if (response.success) {
        toast.success("تم إرسال الإعلان بنجاح");
        setStep(1);
        setLicenseSource("");
        setListingKind("unit");
        setCityLabel("");
        setDistrictLabel("");
        formEl.reset();
      } else {
        console.error("Submission failed with status:", response.status);
        console.error("Error details:", JSON.stringify(response.data, null, 2));

        let errorMessage = "حدث خطأ أثناء إرسال الإعلان - يرجى التأكد من ملء جميع الحقول المطلوبة";
        if (response.status === 422 && response.data?.errors) {
          const firstError = Object.values(response.data.errors)[0];
          if (Array.isArray(firstError) && firstError[0]) {
            errorMessage = String(firstError[0]);
          }
        } else if (response.data?.error) {
          errorMessage = response.data.error;
        }
        toast.error(errorMessage);
      }
    } catch (error) {
      console.error("Listing submission error:", error);
      toast.error("حدث خطأ غير متوقع");
    } finally {
      setIsLoading(false);
    }
  };

  const onNext = () => {
    if (step === 1) {
      if (!licenseSource) return;
      setStep(2);
      return;
    }

    if (step === 2) {
      const formEl = document.querySelector("form") as HTMLFormElement;
      if (formEl) {
        const fd = new FormData(formEl);
        // Save city/district labels for building the address string
        const cityId = fd.get("city");
        const distId = fd.get("neighborhood");
        const cityOpt = formEl.querySelector(`select[name="city"] option[value="${cityId}"]`) as HTMLOptionElement;
        const distOpt = formEl.querySelector(`select[name="neighborhood"] option[value="${distId}"]`) as HTMLOptionElement;
        if (cityOpt?.text) setCityLabel(cityOpt.text);
        if (distOpt?.text) setDistrictLabel(distOpt.text);
      }

      if (showMarketingStep) setStep(3);
      return;
    }
  };

  const onBack = () => {
    if (step === 3) {
      setStep(2);
      return;
    }
    if (step === 2) {
      setStep(1);
      return;
    }
  };

  return (
    <div className="w-full md:w-3/4 lg:w-2/3 mx-auto mt-8 md:mt-14 px-4" dir="rtl">
      <div className="mb-6 text-center">
        <h1 className="text-2xl md:text-4xl font-semibold text-[#1D293D]">
          سوق عقارك
        </h1>
        <p className="mt-2 text-[#45556C] text-md md:text-lg">
          ارسل بيانات عقارك وسوف يتواصل معك فريق العمل للتسويق والوصول لافضل صفقات البيع
        </p>
      </div>

      <form onSubmit={handleSubmit} className="flex flex-col gap-6 bg-[#F1F5F9] p-2 md:p-6 rounded-lg">
        <input type="hidden" name="licenseSource" value={licenseSource} />
        <input type="hidden" name="listingKind" value={listingKind} />
        {step === 1 && (
          <div className="bg-white border border-[#CAD5E2] p-4 rounded-xl" dir="rtl">
            <div className="bg-[#E2E8F0] p-4 rounded-md -mx-4 -mt-4 mb-4">
              <h4 className="text-lg font-semibold text-[#1D293D]">اختيار نوع الترخيص</h4>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <button
                type="button"
                onClick={() => setLicenseSource("us")}
                className={`text-right border rounded-xl p-4 transition-colors ${licenseSource === "us" ? "border-[#052531] bg-[#EFF6FF]" : "border-[#CAD5E2] bg-white"
                  }`}
              >
                <div className="font-semibold text-[#1D293D]">الترخيص من قبلنا</div>
                <div className="mt-1 text-sm text-[#45556C]">سنقوم بعمل ترخيص وتسويق للعقار (تظهر خطوة التسويق)</div>
              </button>

              <button
                type="button"
                onClick={() => setLicenseSource("broker")}
                className={`text-right border rounded-xl p-4 transition-colors ${licenseSource === "broker" ? "border-[#052531] bg-[#EFF6FF]" : "border-[#CAD5E2] bg-white"
                  }`}
              >
                <div className="font-semibold text-[#1D293D]">الترخيص من قبل الوسطاء</div>
                <div className="mt-1 text-sm text-[#45556C]">ترخيص جاهز من وسيط (سيتم إخفاء خطوة التسويق)</div>
              </button>
            </div>

            {licenseSource === "us" && (
              <div className="mt-4 bg-white border border-[#CAD5E2] rounded-xl p-4">
                <p className="font-medium text-[#1D293D]">
                  ( بإمكانك اصدار ترخيص إعلاني من قبل منصة أمتار لتتمكن من نشر الاعلان)
                </p>
                <div className="mt-3 text-sm text-[#45556C]">
                  <div className="font-medium text-[#1D293D]">المتطلبات:-</div>
                  <div className="mt-2 space-y-1">
                    <div>1-تعبئة نموذج العقار</div>
                    <div>2- توفير بيانات المالك/ الوكيل</div>
                    <div>3- توفير وثيقة التملك للعقار</div>
                    <div>4- دفع الترخيص والتسويق</div>
                  </div>
                </div>
                <div className="mt-4 text-sm text-[#45556C] space-y-1">
                  <div>تكلفة ترخيص الاعلان: 300 ريال لمدة 3 شهور</div>
                  <div>تكلفة رسوم التسويق: 300 ريال لمدة 3 شهور</div>
                </div>
              </div>
            )}

            {licenseSource === "broker" && (
              <div className="mt-4 bg-white border border-[#CAD5E2] rounded-xl p-4">
                <p className="font-medium text-[#1D293D]">
                  ( بإمكانك اصدار ترخيص إعلاني من قبل الوسطاء لتتمكن من نشر الاعلان)
                </p>
                <div className="mt-4 text-sm text-[#45556C]">
                  <div>تكلفة التسويق: 300 ريال لمدة 3 شهور فقط</div>
                </div>
              </div>
            )}
          </div>
        )}

        {step === 2 && (
          <div className="w-full" dir="rtl">
            <div className=" bg-white py-4 px-2 rounded-md">
              <Field
                name="propertyType"
                label="نوع العقار"
                required
                type="select"
                placeholder="اختر نوع العقار"
                options={propertyTypes}
                value={listingKind}
                onChange={(e) => setListingKind(e.target.value as "unit" | "projects")}
              />
            </div>
          </div>
        )}

        {step !== 1 && (
          <div className="w-full" dir="rtl">
            {listingKind === "projects" ? (
              <ProjectListingFormCard
                licenseSource={licenseSource as "us" | "broker"}
                section={step === 3 ? "marketing" : "details"}
              />
            ) : (
              <PropertyListingFormCard
                licenseSource={licenseSource as "us" | "broker"}
                section={step === 3 ? "marketing" : "details"}
              />
            )}
          </div>
        )}

        <div className="flex justify-center gap-4">
          <Button
            type="button"
            onClick={onBack}
            disabled={step === 1}
            className="min-w-[140px] font-normal rounded-full bg-[#FEF2F2] hover:bg-[#FADDDD] text-[#E7000B] disabled:opacity-50"
          >
            السابق
          </Button>

          {step === 3 || (step === 2 && !showMarketingStep) ? (
            <Button
              type="submit"
              disabled={isLoading}
              className="min-w-[140px] font-normal rounded-full bg-[#052531] hover:bg-[#052531]/90"
            >
              {isLoading ? "جاري الإرسال..." : "حفظ و ارسال"}
            </Button>
          ) : (
            <Button
              type="button"
              onClick={onNext}
              disabled={step === 1 && !licenseSource}
              className="min-w-[140px] font-normal rounded-full bg-[#052531] hover:bg-[#052531]/90 disabled:opacity-50"
            >
              التالي
            </Button>
          )}
        </div>
      </form>
    </div>
  );
}