"use client";

import { useState, useEffect } from "react";
import Field from "@/components/ui/Field";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/context/AuthContext";
import { createPropertyRequest } from "@/services/userPanelService";
import { getCities, getDistrictsByCity, getCategories } from "@/lib/api";
import { toast } from "sonner";
import {
  requestTypes,
  rentDurationOptions,
} from "@/data/propertyRequestForm";

export default function AddPropertyRequestPage() {
  const { token } = useAuth();
  const [city, setCity] = useState("");
  const [requestType, setRequestType] = useState("");
  const [budgetType, setBudgetType] = useState<"market" | "specific">("market");
  const [isLoading, setIsLoading] = useState(false);

  const [citiesList, setCitiesList] = useState<{ label: string; value: string }[]>([]);
  const [districtsList, setDistrictsList] = useState<{ label: string; value: string }[]>([]);
  const [categoriesList, setCategoriesList] = useState<{ label: string; value: string }[]>([]);

  useEffect(() => {
    async function initData() {
      const [citiesData, categoriesData] = await Promise.all([
        getCities(),
        getCategories()
      ]);
      setCitiesList(citiesData.map(c => ({ label: c.name, value: String(c.id) })));
      setCategoriesList(categoriesData.map(c => ({ label: c.title, value: String(c.id) })));
    }
    initData();
  }, []);

  useEffect(() => {
    async function fetchDistricts() {
      if (!city) {
        setDistrictsList([]);
        return;
      }
      const data = await getDistrictsByCity(city);
      setDistrictsList(data.map(d => ({ label: d.name, value: String(d.id) })));
    }
    fetchDistricts();
  }, [city]);

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

    setIsLoading(true);
    try {
      const formData = new FormData(e.currentTarget);
      const rawData = Object.fromEntries(formData.entries());

      // Data Mapper: Translate frontend to backend payload
      const payload = {
        city_id: parseInt(String(rawData.city)),
        district_ids: rawData.neighborhood ? [parseInt(String(rawData.neighborhood))] : [],
        description: String(rawData.details || ""),
        section: rawData.requestType === "rent" ? "rent" : "sale",
        category_id: parseInt(String(rawData.propertyType)),
        rooms: parseInt(String(rawData.bedrooms)) || 0,
        bathrooms: parseInt(String(rawData.bathrooms)) || 0,
        space: parseInt(String(rawData.areaMin)) || 0,
        to_space: parseInt(String(rawData.areaMax)) || 0,
        price: budgetType === "market" ? 0 : (parseInt(String(rawData.budget)) || 0),
        to_price: budgetType === "market" ? 0 : (parseInt(String(rawData.budget)) || 0),
        property_age: String(rawData.propertyAge || ""),
        contract_type: String(rawData.rentDuration || "annual"),
        // TODO: Include features_ids in payload once the backend implements the features table
      };

      console.log("Mapped Property request payload:", payload);

      const response = await createPropertyRequest(token, payload);
      if (response.success) {
        toast.success(response.message || "تم إضافة الطلب بنجاح");
        (e.target as HTMLFormElement).reset();
        setCity("");
        setRequestType("");
        setBudgetType("market");
      } else {
        toast.error(response.message || "حدث خطأ أثناء إضافة الطلب");
      }
    } catch (error) {
      console.error("Submission error:", error);
      toast.error("حدث خطأ غير متوقع");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="w-full md:w-2/3 lg:w-1/2 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"
      >
        {/* البيانات الأساسية */}
        <div className="bg-white border border-[#CAD5E2] p-4 rounded-xl">
          <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="pt-2 grid grid-cols-1 md:grid-cols-2 gap-4">
            <Field
              name="city"
              label="المدينة"
              required
              type="select"
              placeholder="اختر المدينة"
              options={citiesList}
              value={city}
              onChange={(e) => setCity(e.target.value)}
            />

            <Field
              name="neighborhood"
              label="الأحياء"
              type="select"
              className={`${city ? "" : "text-[#90A1B9]"}`}
              placeholder={
                city ? "اختر الحي" : "اختر المدينة أولاً"
              }
              options={districtsList}
            />

            <Field
              className="md:col-span-2 mt-3"
              name="details"
              label="التفاصيل"
              type="textarea"
              placeholder="أضف تفاصيل إضافية عن طلبك..."
            />
          </div>
        </div>

        {/* نوع الطلب والعقار */}
        <div className="bg-white border border-[#CAD5E2] p-4 rounded-xl">
          <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="pt-2 grid grid-cols-1 md:grid-cols-2 gap-4">
            <Field
              name="requestType"
              label="نوع الطلب"
              required
              type="select"
              placeholder="اختر نوع الطلب"
              options={requestTypes}
              value={requestType}
              onChange={(e) => setRequestType(e.target.value)}
            />

            <Field
              name="propertyType"
              label="نوع العقار"
              required
              type="select"
              placeholder="اختر نوع العقار"
              options={categoriesList}
            />

            {/* الفئة - شهري/سنوي و عائلي/عزاب */}
            <div className="md:col-span-2 space-y-4">
              {requestType === "rent" && (
                <Field
                  name="rentDuration"
                  label="نوع الإيجار"
                  type="radio"
                  radioDirection="row"
                  options={rentDurationOptions}
                />
              )}
            </div>
          </div>
        </div>

        {/* مواصفات العقار */}
        <div className="bg-white border border-[#CAD5E2] p-4 rounded-xl">
          <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="pt-2 grid grid-cols-1 md:grid-cols-2 gap-4">
            <Field
              name="bedrooms"
              label="غرف النوم"
              type="number"
              placeholder="عدد غرف النوم"
            />

            <Field
              name="bathrooms"
              label="الحمامات"
              type="number"
              placeholder="عدد الحمامات"
            />

            <Field
              name="areaMin"
              label="المساحة - الحد الأدنى (م²)"
              type="number"
              placeholder="الحد الأدنى"
              formatThousands={false}
            />

            <Field
              name="areaMax"
              label="المساحة - الحد الأقصى (م²)"
              type="number"
              placeholder="الحد الأقصى"
              formatThousands={false}
            />

            <Field
              name="propertyAge"
              label="عمر العقار"
              type="text"
              placeholder="مثال: أقل من 5 سنوات"
            />
          </div>
        </div>

        {/* الميزانية */}
        <div className="bg-white border border-[#CAD5E2] p-4 rounded-xl overflow-hidden">
          <div className="bg-[#E2E8F0] p-4 -mx-4 -mt-4 mb-4">
            <h4 className="text-lg font-semibold text-[#1D293D]">
              الميزانية
            </h4>
          </div>

          <div className="pt-2 flex flex-col gap-4">
            <Field
              name="budgetType"
              label="تحديد الميزانية"
              type="select"
              value={budgetType}
              onChange={(e) => setBudgetType(e.target.value as "market" | "specific")}
              options={[
                { label: "سعر السوق", value: "market" },
                { label: "سعر محدد", value: "specific" },
              ]}
            />

            {budgetType === "specific" && (
              <Field
                name="budget"
                label="الميزانية (ر.س)"
                type="number"
                placeholder="أدخل السعر المحدد"
                required
              />
            )}
          </div>
        </div>

        {/* أزرار الإجراءات */}
        <div className="flex justify-center gap-4 flex-wrap">
          <Button
            type="submit"
            disabled={isLoading}
            className="min-w-[140px] font-normal rounded-full bg-[#052531] hover:bg-[#052531]/90"
          >
            {isLoading ? "جاري الإضافة..." : "إضافة الطلب"}
          </Button>
          <Button
            type="button"
            className="min-w-[140px] font-normal rounded-full bg-[#FEF2F2] hover:bg-[#FADDDD] text-[#E7000B]"
          >
            إلغاء
          </Button>
        </div>
      </form>
    </div>
  );
}