import CardProperty from "@/components/properties/CardProperty";
import HeroImage from "@/components/HeroImage";
import { fetchPropertyDetail, fetchPropertySuggestion } from "@/services/payload/property";
import { RichText } from "@payloadcms/richtext-lexical/react";
import { headers } from "next/headers";
import Image from "next/image";
import { notFound } from "next/navigation";
import FilterProperty from "@/components/properties/FilterProperty";
import { getDefaultMetadata } from "@/utils/metadata";
import { sanitizeBlogContentIntoStringPreview } from "@/utils/sanitize";
import { Metadata } from "next";
import { State } from "country-state-city";

export async function generateMetadata(props: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const metadata = await getDefaultMetadata();
  const params = await props.params;

  let title = "Page";
  let description = "Page";
  let publishedAt = "";
  let updatedAt = "";
  let imgUrl = "";
  let createdByName = "";

  const property = await fetchPropertyDetail({ slug: params.slug });
  if (!!property) {
    // check for property data
    title = `${!!property.data?.name ? property.data?.name : ""} - ${metadata.openGraph?.siteName}`;
    description = sanitizeBlogContentIntoStringPreview(property.data.aboutGroup.description, 50);
    imgUrl = property.formattedData.images.length > 0 ? property.formattedData.images[0].url : "";
    publishedAt = property.data.createdAt;
    updatedAt = property.data.updatedAt;
    if (!!property?.data?.createdBy && typeof property.data.createdBy !== "number") {
      createdByName = property.data.createdBy?.name ?? "";
    }
  }

  metadata.title = title;
  metadata.description = description;
  if (!!metadata.openGraph) {
    // @ts-ignore
    metadata.openGraph.type = "article";
    metadata.openGraph.title = title;
    metadata.openGraph.description = description;
    metadata.openGraph.images = !!imgUrl ? [imgUrl] : undefined;
  }
  metadata.twitter = {
    card: "summary_large_image",
    title: title,
    description: description,
    images: !!imgUrl ? [imgUrl] : undefined,
  };
  metadata.other = {
    "article:published_time": publishedAt,
    "article:modified_time": updatedAt,
    "twitter:label1": "Written by",
    "twitter:data1": !!createdByName ? createdByName : "Admin",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "3 minutes",
  };

  return metadata;
}

export default async function PropertyDetail({ params }: { params: Promise<{ slug: string }> }) {
  const slug = (await params).slug;
  const propertyDetail = await fetchPropertyDetail({ slug });
  if (!propertyDetail) return notFound();

  const { data, formattedData } = propertyDetail;
  const stateName = !!data?.addressGroup.state_code
    ? State.getStateByCodeAndCountry(data.addressGroup.state_code, "US")?.name
    : "";
  const isEmbedMapUrlValid = !!data?.embed_map_url && data.embed_map_url.includes("www.google.com/maps/embed");
  const headersList = await headers();
  const fullUrl = headersList.get("x-full-url");
  const shareUrl = {
    facebook: `https://www.facebook.com/sharer/sharer.php?u=${fullUrl}`,
    linkedin: `https://www.linkedin.com/sharing/share-offsite/?url=${fullUrl}`,
    twitter: `https://twitter.com/intent/tweet?url=${fullUrl}`,
  };

  const similarPropertiesData = await fetchPropertySuggestion();

  return (
    <>
      <HeroImage title={data.name} />

      <section className="section section-md bg-gray-12">
        <div className="container">
          <div className="row row-50">
            <div className="col-lg-7 col-xl-8">
              <div className="slick-slider-1">
                <div className="slick-slider-price bg-colorPriceTag/90!">
                  {formattedData.price}
                  {data.property_type === "rent" && "/mo"}
                </div>
                <div
                  className="slick-slider carousel-parent"
                  id="parent-carousel"
                  data-arrows="true"
                  data-loop="true"
                  data-dots="false"
                  data-swipe="true"
                  data-fade="true"
                  data-items="1"
                  data-child="#child-carousel"
                  data-for="#child-carousel"
                >
                  {formattedData.images.map((img, idx) => (
                    <div key={idx} className="item">
                      <div className="bg-colorImgPlaceholder/90 w-full! h-[443px]! relative">
                        <Image src={img.url} alt={img.alt} fill />
                      </div>
                    </div>
                  ))}
                </div>
                <div
                  className="slick-slider carousel-child"
                  id="child-carousel"
                  data-arrows="true"
                  data-loop="true"
                  data-dots="false"
                  data-swipe="true"
                  data-items="1"
                  data-sm-items="3"
                  data-md-items="4"
                  data-lg-items="4"
                  data-xl-items="5"
                  data-slide-to-scroll="1"
                  data-for="#parent-carousel"
                >
                  {formattedData.images.map((img, idx) => (
                    <div key={idx}>
                      <div className="bg-colorImgPlaceholder/90 w-[135px]! h-[89px]! relative">
                        <Image src={img.url} alt={img.alt} fill />
                      </div>
                    </div>
                  ))}
                </div>
              </div>
              <div className="features-block">
                <div className="features-block-inner">
                  <div className="features-block-item">
                    <ul className="features-block-list">
                      {!!data?.aboutGroup?.bathrooms_count && (
                        <li>
                          <span className="icon hotel-icon-10"></span>
                          <span>{data.aboutGroup.bathrooms_count} Bathrooms</span>
                        </li>
                      )}
                      {!!data?.aboutGroup?.bedrooms_count && (
                        <li>
                          <span className="icon hotel-icon-05"></span>
                          <span>{data.aboutGroup.bedrooms_count} Bedrooms</span>
                        </li>
                      )}
                      {!!data?.aboutGroup?.area && (
                        <li>
                          <span className="icon mdi mdi-vector-square"></span>
                          <span>{data.aboutGroup.area} Sq Ft</span>
                        </li>
                      )}
                    </ul>
                  </div>
                  <div className="features-block-item">
                    {/* <a className="link link-1" href="#">
                      <span className="icon mdi mdi-heart-outline"></span>Add to Favorites
                    </a> */}
                  </div>
                </div>
              </div>

              <div className="mt-4">
                <RichText data={data.aboutGroup.description} />
              </div>

              <div
                className="card-group-custom card-group-corporate"
                id="accordion1"
                role="tablist"
                aria-multiselectable="false"
              >
                <article className="card card-custom card-corporate">
                  <div className="card-header" id="accordion1-heading-1" role="tab">
                    <div className="card-title">
                      <a
                        className="card-link"
                        role="button"
                        data-toggle="collapse"
                        href="#accordion1-collapse-1"
                        aria-controls="accordion1-collapse-1"
                        aria-expanded="true"
                      >
                        <span>Address</span>
                        <div className="card-arrow"></div>
                      </a>
                    </div>
                  </div>
                  <div
                    className="show visible!"
                    id="accordion1-collapse-1"
                    role="tabpanel"
                    aria-labelledby="accordion1-heading-1"
                    data-parent="#accordion1"
                  >
                    <div className="card-body">
                      <div className="layout-1">
                        <dl className="list-terms-inline">
                          <dt>Address:</dt>
                          <dd>{data?.addressGroup?.address ?? ""}</dd>
                        </dl>
                        <dl className="list-terms-inline">
                          <dt>State:</dt>
                          <dd>{stateName}</dd>
                        </dl>
                        <dl className="list-terms-inline">
                          <dt>City:</dt>
                          <dd>{data?.addressGroup?.city_code ?? ""}</dd>
                        </dl>
                        <dl className="list-terms-inline">
                          <dt>Zip:</dt>
                          <dd>{data?.addressGroup?.zip_code ?? ""}</dd>
                        </dl>
                      </div>
                    </div>
                  </div>
                </article>
              </div>
              <div
                className="card-group-custom card-group-corporate"
                id="accordion2"
                role="tablist"
                aria-multiselectable="false"
              >
                <article className="card card-custom card-corporate">
                  <div className="card-header" id="accordion2-heading-1" role="tab">
                    <div className="card-title">
                      <a
                        className="card-link"
                        role="button"
                        data-toggle="collapse"
                        href="#accordion2-collapse-1"
                        aria-controls="accordion2-collapse-1"
                        aria-expanded="true"
                      >
                        <span>Features</span>
                        <div className="card-arrow"></div>
                      </a>
                    </div>
                  </div>
                  <div
                    className="show visible!"
                    id="accordion2-collapse-1"
                    role="tabpanel"
                    aria-labelledby="accordion2-heading-1"
                    data-parent="#accordion2"
                  >
                    <div className="card-body">
                      <ul className="list-marked-2 layout-2">
                        {Array.isArray(data.features) &&
                          data.features.length > 0 &&
                          data.features.map((ft, idx) => <li key={idx}>{typeof ft !== "number" && ft.name}</li>)}
                      </ul>
                    </div>
                  </div>
                </article>
              </div>

              {data.property_type === "rent" && (
                <div
                  className="card-group-custom card-group-corporate"
                  id="accordion0"
                  role="tablist"
                  aria-multiselectable="false"
                >
                  <article className="card card-custom card-corporate">
                    <div className="card-header" id="accordion0-heading-0" role="tab">
                      <div className="card-title">
                        <a
                          className="card-link"
                          role="button"
                          data-toggle="collapse"
                          href="#accordion0-collapse-0"
                          aria-controls="accordion0-collapse-0"
                          aria-expanded="true"
                        >
                          <span>Pricing Detail</span>
                          <div className="card-arrow"></div>
                        </a>
                      </div>
                    </div>
                    <div
                      className="show visible!"
                      id="accordion0-collapse-0"
                      role="tabpanel"
                      aria-labelledby="accordion0-heading-0"
                      data-parent="#accordion0"
                    >
                      <div className="card-body">
                        <div className="layout-1 columns-1!">
                          <dl className="list-terms-inline w-full flex justify-between">
                            <dt>Base Rent</dt>
                            <dd>{formattedData.price}</dd>
                          </dl>
                        </div>

                        {formattedData.additionalPrice.map((p, idx) => (
                          <div className="layout-1 columns-1!" key={idx}>
                            <dl className="list-terms-inline w-full flex justify-between">
                              <dt>{p.name}</dt>
                              <dd>{p.price}</dd>
                            </dl>
                          </div>
                        ))}
                        <div className="layout-1 columns-1! mt-2">
                          <dl className="list-terms-inline w-full flex justify-between">
                            <dd className="font-semibold!">Est. total monthly*</dd>
                            <dd className="font-semibold!">{formattedData.totalPrice}</dd>
                          </dl>
                        </div>
                      </div>
                    </div>
                  </article>
                </div>
              )}

              {isEmbedMapUrlValid && (
                <div className="block-group-item">
                  <h3>Property Map</h3>
                  <div className="row row-30">
                    <div className="col-12">
                      <iframe
                        src={data.embed_map_url ?? ""}
                        width={"100%"}
                        height={450}
                        style={{ border: 0 }}
                        loading="lazy"
                        referrerPolicy="no-referrer-when-downgrade"
                      />
                    </div>
                  </div>
                </div>
              )}

              <div className="blog-post-solo-footer mt-20">
                <div className="blog-post-solo-footer-left">
                  <ul className="blog-post-solo-footer-list">
                    <li>
                      <span className="icon mdi mdi-clock"></span>
                      <a href="#">{formattedData.postedAt}</a>
                    </li>
                  </ul>
                </div>
                <div className="blog-post-solo-footer-right">
                  <ul className="blog-post-solo-footer-list-1">
                    <li>
                      <span>Share this post</span>
                    </li>
                    <li>
                      <ul className="list-inline-1">
                        <li>
                          <a target="_blank" className="icon link-default fa-facebook" href={shareUrl.facebook}></a>
                        </li>
                        <li>
                          <a target="_blank" className="icon link-default fa-twitter" href={shareUrl.twitter}></a>
                        </li>
                        <li>
                          <a target="_blank" className="icon link-default fa-linkedin" href={shareUrl.linkedin}></a>
                        </li>
                      </ul>
                    </li>
                  </ul>
                </div>
              </div>

              {similarPropertiesData.formattedData.length > 0 && (
                <div className="block-group-item">
                  <h3>Other Properties</h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    {similarPropertiesData.formattedData.map((p, idx) => (
                      <CardProperty key={idx} data={p} />
                    ))}
                  </div>
                </div>
              )}
            </div>
            <div className="col-lg-5 col-xl-4">
              <div className="row row-50">
                <div className="col-md-6 col-lg-12">
                  <FilterProperty propertyType={data.property_type} />
                </div>
                <div className="col-md-6 col-lg-12">
                  <article className="block-callboard">
                    <div className="block-callboard-body">
                      <h3 className="block-callboard-title">Request a Showing</h3>
                      <form
                        className="rd-form rd-mailform"
                        data-form-output="form-output-global"
                        data-form-type="contact"
                        method="post"
                        action="bat/rd-mailform.php"
                      >
                        <div className="row row-20">
                          <div className="col-12">
                            <div className="form-wrap">
                              <input
                                className="form-input"
                                id="contact-name"
                                type="text"
                                name="name"
                                data-constraints="@Required"
                              />
                              <label className="form-label" htmlFor="contact-name">
                                Your Name
                              </label>
                            </div>
                          </div>
                          <div className="col-12">
                            <div className="form-wrap">
                              <input
                                className="form-input"
                                id="contact-email"
                                type="email"
                                name="email"
                                data-constraints="@Email @Required"
                              />
                              <label className="form-label" htmlFor="contact-email">
                                E-mail
                              </label>
                            </div>
                          </div>
                          <div className="col-12">
                            <div className="form-wrap">
                              <input
                                className="form-input"
                                id="contact-phone"
                                type="text"
                                name="phone"
                                data-constraints="@PhoneNumber"
                              />
                              <label className="form-label" htmlFor="contact-phone">
                                Phone
                              </label>
                            </div>
                          </div>
                          <div className="col-12">
                            <div className="form-wrap">
                              <label className="form-label" htmlFor="contact-message">
                                Message
                              </label>
                              <textarea
                                className="form-input"
                                id="contact-message"
                                name="message"
                                data-constraints="@Required"
                              ></textarea>
                            </div>
                          </div>
                          <div className="col-12">
                            <button className="button button-block button-secondary" type="submit">
                              Send message
                            </button>
                          </div>
                        </div>
                      </form>
                    </div>
                  </article>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}
