"use client";

import { useRef, useState } from "react";
import { useRouter } from "next/navigation";
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 UploadImage from "@/components/rental-contracts/UploadImage";
import { buildingCodeOptions, propertyServices, propertyTypes } from "@/data/listingForm";

type FlowType = "has_license" | "no_license" | "need_brokers_license";

export default function CreateAdvertisementPage() {
  const router = useRouter();
  const [flowType, setFlowType] = useState<FlowType | null>(null);
  const [step, setStep] = useState<1 | 2 | 3>(1);
  const [listingKind, setListingKind] = useState<"unit" | "projects">("unit");
  const [selectedServices, setSelectedServices] = useState<string[]>([]);
  const [advertiserIdType, setAdvertiserIdType] = useState<"national_id" | "commercial_register">("national_id");

  const formRef = useRef<HTMLFormElement | null>(null);

  const onNext = () => {
    if (!formRef.current) return;
    const valid = formRef.current.reportValidity();
    if (!valid) return;

    if (flowType === "has_license") {
      if (step === 1) setStep(2);
      return;
    }
    if (flowType === "need_brokers_license") {
      if (step === 1) setStep(2);
      return;
    }
    if (flowType === "no_license") {
      if (step === 1) setStep(2);
      if (step === 2) setStep(3);
      return;
    }
  };

  const onBack = () => {
    if (flowType === "has_license") {
      if (step === 2) {
        setStep(1);
        return;
      }

      setFlowType(null);
      return;
    }

    if (flowType === "need_brokers_license") {
      if (step === 2) setStep(1);
      if (step === 1) setFlowType(null);
      return;
    }

    if (flowType === "no_license") {
      if (step === 3) setStep(2);
      if (step === 2) setStep(1);
      if (step === 1) setFlowType(null);
      return;
    }
  };

  const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    const data = Object.fromEntries(formData.entries());
    console.log("Advertisements form submitted:", { flowType, listingKind, advertiserIdType, selectedServices, data });
    router.push("/advertisements");
  };

  const renderFlowChoice = () => {
    return (
      <div dir="rtl" className="max-w-2xl mx-auto space-y-6 md:p-4">
        <h1 className="text-2xl font-bold text-center text-[#1D293D] mb-8">إضافة إعلان جديد</h1>
        <div className="grid grid-cols-1 gap-4">
          <button
            type="button"
            className="w-full text-right p-6 rounded-xl border-2 border-[#CAD5E2] hover:border-[#052531] hover:bg-[#F8FAFC] transition-all"
            onClick={() => {
              setFlowType("has_license");
              setStep(1);
            }}
          >
            <span className="text-lg font-medium">هل تملك ترخيص إعلاني</span>
          </button>

          <button
            type="button"
            className="w-full text-right p-6 rounded-xl border-2 border-[#CAD5E2] hover:border-[#052531] hover:bg-[#F8FAFC] transition-all"
            onClick={() => {
              setFlowType("no_license");
              setStep(1);
            }}
          >
            <span className="text-lg font-medium">لا تملك ترخيص إعلاني</span>
          </button>

          <button
            type="button"
            className="w-full text-right p-6 rounded-xl border-2 border-[#CAD5E2] hover:border-[#052531] hover:bg-[#F8FAFC] transition-all"
            onClick={() => {
              setFlowType("need_brokers_license");
              setStep(1);
            }}
          >
            <span className="text-lg font-medium">أحتاج ترخيص إعلاني من قبل الوسطاء</span>
          </button>
        </div>

        <div className="flex justify-center mt-8">
          <Button type="button" className="min-w-[140px] font-normal rounded-full bg-[#FEF2F2] hover:bg-[#FADDDD] text-[#E7000B]" onClick={() => router.back()}>
            إلغاء
          </Button>
        </div>
      </div>
    );
  };

  const renderHasLicenseForm = () => {
    return (
      <div dir="rtl" className="max-w-4xl mx-auto space-y-6 md:p-4">
        <div className="bg-white border border-[#CAD5E2] p-6 rounded-2xl shadow-sm overflow-hidden">
          <div className="bg-[#E2E8F0] p-4 -mx-6 -mt-6 mb-6">
            <h4 className="text-xl font-semibold text-[#1D293D]">بيانات الترخيص</h4>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <Field
              name="licenseNumberOrLink"
              label="رقم رخصة فال أو رابط معلومات الترخيص"
              type="text"
              placeholder="القيمة هنا"
              required
            />

            <Field
              name="advertiserIdType"
              label="نوع هوية المعلن"
              type="select"
              placeholder="اختر نوع الهوية"
              required
              options={[
                { label: "بطاقة الأحوال", value: "national_id" },
                { label: "سجل تجاري", value: "commercial_register" },
              ]}
              value={advertiserIdType}
              onChange={(e) => setAdvertiserIdType(e.target.value as "national_id" | "commercial_register")}
            />

            {advertiserIdType === "national_id" ? (
              <Field
                className="md:col-span-2"
                name="nationalIdNumber"
                label="رقم بطاقة الأحوال"
                type="number"
                placeholder="القيمة هنا"
                required
                formatThousands={false}
              />
            ) : (
              <Field
                className="md:col-span-2"
                name="commercialRegisterNumber"
                label="رقم السجل التجاري"
                type="number"
                placeholder="القيمة هنا"
                required
                formatThousands={false}
              />
            )}
          </div>
        </div>

        <div className="flex justify-center gap-4 mt-8">
          <Button
            type="button"
            onClick={onBack}
            className="min-w-[160px] h-12 text-lg font-normal rounded-full bg-[#FEF2F2] hover:bg-[#FADDDD] text-[#E7000B]"
          >
            السابق
          </Button>

          <Button type="button" onClick={onNext} className="min-w-[160px] h-12 text-lg font-normal rounded-full bg-[#052531] hover:bg-[#052531]/90 text-white">
            التالي
          </Button>
        </div>
      </div>
    );
  };

  const renderHasLicenseFlow = () => {
    return (
      <div className="max-w-4xl mx-auto space-y-6 md:p-4" dir="rtl">
        {step === 1 && renderHasLicenseForm()}

        {step === 2 && (
          <>
            {renderListingForm()}

            <div className="flex justify-center gap-4 mt-8">
              <Button
                type="button"
                onClick={onBack}
                className="min-w-[160px] h-12 text-lg font-normal rounded-full bg-[#FEF2F2] hover:bg-[#FADDDD] text-[#E7000B]"
              >
                السابق
              </Button>

              <Button type="submit" className="min-w-[160px] h-12 text-lg font-normal rounded-full bg-[#052531] hover:bg-[#052531]/90 text-white">
                حفظ
              </Button>
            </div>
          </>
        )}
      </div>
    );
  };

  const renderListingForm = () => {
    return (
      <div className="w-full space-y-6" dir="rtl">
        <div className="bg-white p-6 rounded-2xl border border-[#CAD5E2] shadow-sm">
          <Field
            name="propertyType"
            label="نوع العقار"
            required
            type="select"
            placeholder="اختر نوع العقار"
            options={propertyTypes}
            value={listingKind}
            onChange={(e) => setListingKind(e.target.value as "unit" | "projects")}
          />
        </div>

        <div className="w-full">
          {listingKind === "projects" ? (
            <ProjectListingFormCard licenseSource="us" section="details" />
          ) : (
            <PropertyListingFormCard licenseSource="us" section="details" />
          )}
        </div>
      </div>
    );
  };

  const renderDeedAndOwnerForm = () => {
    return (
      <div className="bg-white border border-[#CAD5E2] p-6 rounded-2xl shadow-sm" dir="rtl">
        <div className="bg-[#E2E8F0] p-4 rounded-xl -mx-6 -mt-6 mb-6">
          <h4 className="text-xl font-semibold text-[#1D293D]">بيانات الصك والمالك</h4>
        </div>

        <div className="space-y-6">
          <UploadImage title="صورة من الصك" name="deedImage" />
          <UploadImage title="صورة الهوية من المالك/الوكيل" name="ownerIdImage" />

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <Field name="ownerName" label="اسم المالك/الوكيل" type="text" placeholder="القيمة هنا" required />
            <Field name="ownerIdNumber" label="رقم الهوية" type="number" placeholder="القيمة هنا" required />
            <Field
              className="md:col-span-2"
              name="ownerPhone"
              label="رقم الجوال"
              type="tel"
              placeholder="05xxxxxxxx"
              required
            />
          </div>

          <div>
            <label className="px-2 block text-sm font-medium text-gray-700 mb-2">خدمات العقار</label>
            <Field
              name="propertyServices"
              type="multi-select"
              placeholder="اختر الخدمات"
              options={propertyServices}
              multiValue={selectedServices}
              onMultiChange={setSelectedServices}
            />
          </div>

          <Field
            name="buildingCode"
            label="مطابقة كود البناء السعودي"
            type="select"
            placeholder="القيمة هنا"
            options={buildingCodeOptions}
          />

          <Field
            name="warrantiesAuthorityText"
            label="الضمانات ومدتها (هيئة العقار)"
            type="textarea"
            placeholder="اذكر الضمانات ومدتها..."
          />

          <Field
            name="obligations"
            label="الالتزامات على العقار (أن وجد)"
            type="textarea"
            placeholder="اذكر الالتزامات..."
          />

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <Field
              name="facade"
              label="الواجهة"
              type="select"
              placeholder="القيمة هنا"
              options={[
                { label: "شرقي", value: "east" },
                { label: "غربي", value: "west" },
                { label: "شمالي", value: "north" },
                { label: "جنوبي", value: "south" },
              ]}
            />
            <Field name="streetNumber" label="الشارع" type="number" placeholder="القيمة هنا" />
          </div>
        </div>
      </div>
    );
  };

  const renderNoLicenseFlow = () => {
    return (
      <div className="max-w-4xl mx-auto space-y-6 md:p-4" dir="rtl">
        {step === 1 && renderListingForm()}
        {step === 2 && renderDeedAndOwnerForm()}
        {step === 3 && (
          <div className="bg-white border border-[#CAD5E2] p-8 rounded-2xl shadow-sm" dir="rtl">
            <div className="bg-[#E2E8F0] p-4 rounded-xl -mx-8 -mt-8 mb-6">
              <h4 className="text-xl font-semibold text-[#1D293D]">مراجعة</h4>
            </div>
            <p className="text-[#45556C] text-lg">اضغط حفظ لإرسال الإعلان.</p>
          </div>
        )}

        <div className="flex justify-center gap-4 mt-8">
          <Button
            type="button"
            onClick={onBack}
            className="min-w-[160px] h-12 text-lg font-normal rounded-full bg-[#FEF2F2] hover:bg-[#FADDDD] text-[#E7000B]"
          >
            {step === 1 ? "رجوع" : "السابق"}
          </Button>

          {step === 3 ? (
            <Button type="submit" className="min-w-[160px] h-12 text-lg font-normal rounded-full bg-[#052531] hover:bg-[#052531]/90 text-white">
              حفظ
            </Button>
          ) : (
            <Button type="button" onClick={onNext} className="min-w-[160px] h-12 text-lg font-normal rounded-full bg-[#052531] hover:bg-[#052531]/90 text-white">
              التالي
            </Button>
          )}
        </div>
      </div>
    );
  };

  const renderNeedBrokersLicenseFlow = () => {
    return (
      <div className="max-w-4xl mx-auto space-y-6 md:p-4" dir="rtl">
        {step === 1 && renderListingForm()}
        {step === 2 && (
          <div className="bg-white border border-[#CAD5E2] p-8 rounded-2xl shadow-sm" dir="rtl">
            <div className="bg-[#E2E8F0] p-4 rounded-xl -mx-8 -mt-8 mb-6">
              <h4 className="text-xl font-semibold text-[#1D293D]">مراجعة</h4>
            </div>
            <p className="text-[#45556C] text-lg">اضغط حفظ لإرسال الإعلان.</p>
          </div>
        )}

        <div className="flex justify-center gap-4 mt-8">
          <Button
            type="button"
            onClick={onBack}
            className="min-w-[160px] h-12 text-lg font-normal rounded-full bg-[#FEF2F2] hover:bg-[#FADDDD] text-[#E7000B]"
          >
            {step === 1 ? "رجوع" : "السابق"}
          </Button>

          {step === 2 ? (
            <Button type="submit" className="min-w-[160px] h-12 text-lg font-normal rounded-full bg-[#052531] hover:bg-[#052531]/90 text-white">
              حفظ
            </Button>
          ) : (
            <Button type="button" onClick={onNext} className="min-w-[160px] h-12 text-lg font-normal rounded-full bg-[#052531] hover:bg-[#052531]/90 text-white">
              التالي
            </Button>
          )}
        </div>
      </div>
    );
  };

  const renderPageBody = () => {
    if (!flowType) return renderFlowChoice();

    if (flowType === "has_license") return renderHasLicenseFlow();
    if (flowType === "no_license") return renderNoLicenseFlow();
    return renderNeedBrokersLicenseFlow();
  };

  return (
    <div className="min-h-screen bg-[#F8FAFC] py-12">
      <div className="container mx-auto px-4">
        <form ref={formRef} onSubmit={onSubmit} className="w-full">
          {renderPageBody()}
        </form>
      </div>
    </div>
  );
}
