"use client";

import { useEffect, useMemo, useState } from "react";
import { motion, AnimatePresence, useReducedMotion } from "motion/react";
import { CitySelect, Chip } from "@/components/life/Controls";
import { LifeNotice, LifeSkeleton } from "@/components/life/LifeStatus";
import PlaceCard from "@/components/life/PlaceCard";
import { useCitiesStore } from "@/store/cities";
import { useDealsStore } from "@/store/deals";

const date = new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "Asia/Damascus" });
export const dealDate = (iso: string | null) => (iso ? date.format(new Date(iso)) : null);
export const percent = (v: string | null) => (v ? `${Number(v)}% off` : null);

/** Travel deals from the API. City and type filters run on the loaded list; the type chips come from the data itself. */
export default function DealDirectory() {
  const reduce = useReducedMotion();
  const store = useDealsStore();
  const cities = useCitiesStore((s) => s.items);
  const [cityId, setCityId] = useState<number | undefined>();
  const [typeId, setTypeId] = useState<number | undefined>();

  useEffect(() => {
    if (store.status === "idle") void store.load();
  }, [store.status, store.load]);

  const types = useMemo(() => {
    const seen = new Map<number, string>();
    for (const d of store.items) if (d.deal_type) seen.set(d.deal_type.id, d.deal_type.name);
    return [...seen];
  }, [store.items]);

  const shown = store.items.filter((d) => (!cityId || d.city_id === cityId) && (!typeId || d.deal_type_id === typeId));
  const loading = store.status === "idle" || store.status === "loading";
  const filtered = Boolean(cityId || typeId);
  const clear = () => {
    setCityId(undefined);
    setTypeId(undefined);
  };

  return (
    <div className="lf">
      <div className="lf-toolbar">
        {types.length > 0 && (
          <div className="lf-group" role="group" aria-label="Deal type">
            <Chip pressed={!typeId} onClick={() => setTypeId(undefined)}>
              All deals
            </Chip>
            {types.map(([id, name]) => (
              <Chip key={id} pressed={typeId === id} onClick={() => setTypeId(typeId === id ? undefined : id)}>
                {name}
              </Chip>
            ))}
          </div>
        )}
        <div className="lf-tools">
          <CitySelect value={cityId} onChange={setCityId} />
        </div>
      </div>

      <LifeNotice status={store.status} error={store.error} hasFallback={false} onRetry={() => void store.load()} />

      <p className="lf-count" aria-live="polite">{loading ? "Loading" : `${shown.length} ${shown.length === 1 ? "deal" : "deals"}`}</p>

      {loading && store.items.length === 0 ? (
        <LifeSkeleton />
      ) : shown.length > 0 ? (
        <motion.div layout className="lf-grid">
          <AnimatePresence mode="popLayout">
            {shown.map((d, i) => (
              <PlaceCard
                key={d.id}
                index={reduce ? 0 : Math.min(i, 6)}
                item={{
                  key: `d-${d.id}`,
                  name: d.title,
                  meta: [cities.find((c) => c.id === d.city_id)?.name, dealDate(d.ends_at) && `Until ${dealDate(d.ends_at)}`].filter(Boolean).join(", "),
                  tags: [percent(d.discount_percent), d.deal_type?.name].filter((t): t is string => Boolean(t)),
                  src: d.cover?.url ?? null,
                  href: `/deals/details?id=${d.id}`,
                }}
              />
            ))}
          </AnimatePresence>
        </motion.div>
      ) : (
        store.status === "ready" && (
          <div className="lf-empty">
            <p>{filtered ? "No deals match these filters." : "No deals are listed yet."}</p>
            {filtered && (
              <Chip pressed={false} onClick={clear}>
                Clear filters
              </Chip>
            )}
          </div>
        )
      )}
    </div>
  );
}
