"use client";

import React, { useState, useEffect, Suspense } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import LesseeInfoCard from "@/components/rental-contracts/LesseeInfoCard";
import LessorInfoCard from "@/components/rental-contracts/LessorInfoCard";
import PropertyInfoCard from "@/components/rental-contracts/PropertyInfoCard";
import { Button } from "@/components/ui/button";
import { createTawtheeqContract, TawtheeqContractData } from "@/lib/api";

function RequestForm() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const initialType = (searchParams.get("type") as "residential" | "commercial") || "residential";

  const [formState, setFormState] = useState<TawtheeqContractData>({
    type: initialType,
    property_type: "apartment",
    payment_cycle: "yearly",
  });

  const [loading, setLoading] = useState(false);
  const [token, setToken] = useState<string | null>(null);

  useEffect(() => {
    const savedToken = localStorage.getItem("amtar_auth_token");
    if (!savedToken) {
      alert("يجب تسجيل الدخول أولاً");
      router.push("/auth/signin");
      return;
    }
    setToken(savedToken);
  }, [router]);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormState((prev) => ({ ...prev, [name]: value }));
  };

  const handleFileChange = (name: string, file: File | null) => {
    setFormState((prev) => ({ ...prev, [name]: file }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!token) return;

    setLoading(true);
    try {
      const response = await createTawtheeqContract(formState, token);
      if (response.success || response.message.includes('بنجاح')) {
        alert(response.message || "تم إنشاء طلب توثيق العقد بنجاح");
        // Redirect to payment or success page
        router.push("/rental-contracts/success");
      } else {
        alert(response.message || "حدث خطأ أثناء إنشاء الطلب");
        if (response.errors) {
          console.error("Validation errors:", response.errors);
        }
      }
    } catch (error) {
      console.error("Error submitting contract:", error);
      alert("فشل الاتصال بالخادم");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="w-full md:w-1/2 mx-auto mt-8 md:mt-14">
      <div className="mb-6 text-center">
        <h1 className="text-2xl md:text-3xl font-semibold">طلب توثيق عقد ايجار</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-4 md:p-6 rounded-lg mb-10">
        <LessorInfoCard
          values={formState}
          onChange={handleInputChange}
          onFileChange={(file) => handleFileChange("property_document", file)}
        />
        <LesseeInfoCard
          values={formState}
          onChange={handleInputChange}
          onFileChange={(file) => handleFileChange("lessee_id_image", file)}
        />
        <PropertyInfoCard
          values={formState}
          onChange={handleInputChange}
        />

        <div className="flex justify-center gap-4 mt-4">
          <Button
            type="submit"
            className="w-40 font-normal rounded-full transition-all disabled:opacity-70"
            disabled={loading}
          >
            {loading ? "جاري الإرسال..." : "اذهب الى الدفع"}
          </Button>
          <Button
            type="button"
            className="w-30 font-normal rounded-full bg-[#FEF2F2] hover:bg-[#FADDDD] text-[#E7000B]"
            onClick={() => router.back()}
          >
            الغاء
          </Button>
        </div>
      </form>
    </div>
  );
}

export default function RentalContractsRequest() {
  return (
    <Suspense fallback={<div className="text-center py-20">جاري التحميل...</div>}>
      <RequestForm />
    </Suspense>
  );
}
