// 'use clinet'
// import { Button } from '@/components/ui/button'
// import { Input } from '@/components/ui/input'
// import { Textarea } from '@/components/ui/textarea'
// import Image from 'next/image'
// import React from 'react'

// export default function AgentContactInfo() {
//   return (
//     <div className="mt-[50px]">
//           <h1 className="font-semibold text-xl lg:text-2xl text-black">
//             Agent Contact Info
//           </h1>
//           <div className="grid grid-cols-1 w-full shadow-xl rounded-xl mt-[20px]">
//             <div className="m-[20px]">
//               <div className=" bg-skin h-[70px] rounded-lg flex">
//                 <div className="flex items-center justify-center">
//                   <Image
//                     src="/icons/listingDetailPageIcons/Avatar Image.png"
//                     width={40}
//                     height={40}
//                     alt="sadu-logo"
//                     className="rounded-full"
//                   />
//                   <h1 className="pl-[10px] text-sm font-medium">
//                     Muhammad Ahmad
//                   </h1>
//                 </div>
//               </div>
//               <div>
//                 <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2">
//                   {/* Form Column 1 */}
//                   <Input
//                     placeholder="Name"
//                     className="bg-transparent border h-[40px] lg:h-[55px]   text-[13px] lg:text-[15px]"
//                   />
//                   {/* Form Column 2 */}
//                   <Input
//                     placeholder="Email"
//                     className="bg-transparent border h-[40px] lg:h-[55px]   text-[13px] lg:text-[15px]"
//                   />
//                   {/* Form Column 3 */}
//                   <Input
//                     placeholder="Phone"
//                     className="bg-transparent border   h-[40px] lg:h-[55px]   text-[13px] lg:text-[15px]"
//                   />
//                 </div>
//               </div>
//               <div className="grid grid-cols-1 mt-[20px]">
//                 <Textarea
//                   id="message"
//                   placeholder="Hello, I am interested in…"
//                   className="min-h-[120px] text-[13px] lg:text-[15px]"
//                 />
//               </div>
//               <div className="flex justify-end items-center my-[10px] mt-[24px] ">
//                 <Button className="px-[36px] h-[56px] text-[16px]">
//                   Submit
//                 </Button>
//               </div>
//             </div>
//           </div>
//         </div>
//   )
// }

"use client";
import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import Image from "next/image";
import Link from "next/link";
import { useTranslation } from "react-i18next";

export default function AgentContactInfo({ property_id, property }) {
          const { t } = useTranslation("propertyDetail"); 
  
  const [form, setForm] = useState({
    name: "",
    email: "",
    phone: "",
    message: "",
  });
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState({});
  const [token, setToken] = useState(null);

  useEffect(() => {
    const storedToken = localStorage.getItem("sadu_auth_token");
    if (storedToken) {
      setToken(storedToken);
    }
  }, []);

  const validate = () => {
    const newErrors = {};
    if (!form.name.trim()) newErrors.name = t("Name is required");
    if (!form.email.trim()) {
      newErrors.email = t("Email is required");
    } else if (!/^\S+@\S+\.\S+$/.test(form.email)) {
      newErrors.email = t("Invalid email");
    }
    if (!form.phone.trim()) newErrors.phone = t("Phone is required");
    if (!form.message.trim()) newErrors.message = t("Message is required");
    return newErrors;
  };

  const handleChange = (field, value) => {
    setForm((prev) => ({ ...prev, [field]: value }));
  };

  const handleSubmit = async () => {
    const validationErrors = validate();
    setErrors(validationErrors);

    if (Object.keys(validationErrors).length > 0) return;

    setLoading(true);
    try {
      const res = await fetch("https://sadu.reownlogics.com/api/property-query", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ ...form, property_id }),
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.message || "Submission failed");

      setForm({ name: "", email: "", phone: "", message: "" });
      setErrors({});
    } catch (err) {
      console.log(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="mt-[50px] relative">
      {!token && (
        <div className="absolute inset-0 bg-white/80 z-10 flex items-center justify-center flex-col gap-3 rounded-xl">
          <p className="text-lg font-medium">{t("You must be logged in to contact the agent")}</p>
          <Link href="/login">
            <Button>{t("Login")}</Button>
          </Link>
        </div>
      )}

      <h1 className="font-semibold text-xl lg:text-2xl text-black">
        {t("Agent Contact Info")}
      </h1>
      <div className="grid grid-cols-1 w-full shadow-xl rounded-xl mt-[20px]">
        <div className="m-[20px]">
          <div className="bg-skin h-[70px] rounded-lg flex">
            <div className="flex items-center justify-center">
              <Image
                src="/icons/listingDetailPageIcons/Avatar Image.png"
                width={40}
                height={40}
                alt="agent-avatar"
                className="rounded-full"
              />
              <h1 className="pl-[10px] text-sm font-medium">
              {property?.user?.name}
              </h1>
            </div>
          </div>

          {/* Inputs */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2 mt-4">
            <div>
              <Input
                placeholder={t("Name")}
                value={form.name}
                onChange={(e) => handleChange("name", e.target.value)}
                className="bg-transparent border h-[40px] lg:h-[55px] text-[13px] lg:text-[15px]"
              />
              {errors.name && <p className="text-red-500 text-sm">{errors.name}</p>}
            </div>
            <div>
              <Input
                placeholder={t("Email")}
                value={form.email}
                onChange={(e) => handleChange("email", e.target.value)}
                className="bg-transparent border h-[40px] lg:h-[55px] text-[13px] lg:text-[15px]"
              />
              {errors.email && <p className="text-red-500 text-sm">{errors.email}</p>}
            </div>
            <div>
              <Input
                placeholder={t("Phone")}
                value={form.phone}
                onChange={(e) => handleChange("phone", e.target.value)}
                className="bg-transparent border h-[40px] lg:h-[55px] text-[13px] lg:text-[15px]"
              />
              {errors.phone && <p className="text-red-500 text-sm">{errors.phone}</p>}
            </div>
          </div>

          <div className="grid grid-cols-1 mt-[20px]">
            <Textarea
              id="message"
              placeholder={t("Hello, I am interested in…")}
              value={form.message}
              onChange={(e) => handleChange("message", e.target.value)}
              className="min-h-[120px] text-[13px] lg:text-[15px]"
            />
            {errors.message && <p className="text-red-500 text-sm">{errors.message}</p>}
          </div>

          <div className="flex justify-end items-center my-[10px] mt-[24px]">
            <Button
              className="px-[36px] h-[56px] text-[16px]"
              onClick={handleSubmit}
              disabled={loading || !token}
            >
              {loading ? t("Sending...") : t("Submit")}
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}
