"use client";

import { useEffect } from "react";
import Link from "next/link";
import { Gallery, InfoRow } from "@/components/life/Detail";
import { dealDate, percent } from "./DealDirectory";
import type { DealDetail } from "@/lib/api/deals";
import { useCitiesStore } from "@/store/cities";

/** Backend model classes that have a detail page on the site. */
const OFFER_PAGE: Record<string, { href: string; label: string }> = {
  "App\\Models\\Accommodation": { href: "/stays/details?id=", label: "View the stay" },
};

export default function DealBody({ item }: { item: DealDetail }) {
  const city = useCitiesStore((s) => s.items.find((c) => c.id === item.city_id));
  const { status, load } = useCitiesStore();
  useEffect(() => {
    if (status === "idle") void load();
  }, [status, load]);
  const offer = item.offerable_type && item.offerable_id ? OFFER_PAGE[item.offerable_type] : undefined;
  const from = dealDate(item.starts_at);
  const to = dealDate(item.ends_at);

  return (
    <div className="lfd-split">
      <div className="lfd-media">
        <Gallery name={item.title} media={item.media} />
      </div>
      <div className="lfd-body">
        <section className="lfd-card" aria-label="Deal details">
          {percent(item.discount_percent) && <span className="deal-off">{percent(item.discount_percent)}</span>}
          <ul className="lfd-info">
            {(from || to) && <InfoRow icon="event">{from && to ? `${from} to ${to}` : from ? `From ${from}` : `Until ${to}`}</InfoRow>}
            {city && <InfoRow icon="apartment">{city.name}</InfoRow>}
          </ul>
          {offer && (
            <Link className="btn btn-rose lfd-map" href={`${offer.href}${item.offerable_id}`}>
              {offer.label}
            </Link>
          )}
        </section>
        {item.description && <p className="lfd-lead">{item.description}</p>}
      </div>
    </div>
  );
}
