import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
import { ListingCard } from "@/components/ListingCard";
import { fetchFavoriteIds, fetchListings, toggleFavorite, type Listing } from "@/lib/listings";
import { CATEGORIES, CONDITIONS, PROVINCES } from "@/lib/catalog";
import { useI18n } from "@/lib/i18n";
import { useAuth } from "@/lib/auth";
import { formatKz } from "@/lib/format";

type HomeSearch = {
  q?: string | undefined;
  category?: string | undefined;
  province?: string | undefined;
  condition?: string | undefined;
  min?: number | undefined;
  max?: number | undefined;
  sort?: "recent" | "cheap" | "expensive" | "viewed" | undefined;
};

export const Route = createFileRoute("/")({
  validateSearch: (search: Record<string, unknown>): HomeSearch => ({
    q: typeof search["q"] === "string" && search["q"] ? search["q"] : undefined,
    category: typeof search["category"] === "string" ? search["category"] : undefined,
    province: typeof search["province"] === "string" ? search["province"] : undefined,
    condition: typeof search["condition"] === "string" ? search["condition"] : undefined,
    min: search["min"] != null && !Number.isNaN(Number(search["min"])) ? Number(search["min"]) : undefined,
    max: search["max"] != null && !Number.isNaN(Number(search["max"])) ? Number(search["max"]) : undefined,
    sort: ["recent", "cheap", "expensive", "viewed"].includes(String(search["sort"]))
      ? (search["sort"] as HomeSearch["sort"])
      : undefined,
  }),
  head: () => ({
    meta: [
      { title: "KUYA — Compra e vende em todo o Angola" },
      {
        name: "description",
        content:
          "Milhares de anúncios em Angola: imóveis, viaturas, tecnologia, moda e serviços. Compra instantânea com pagamento seguro em Kwanzas.",
      },
      { property: "og:title", content: "KUYA — Compra e vende em todo o Angola" },
      {
        property: "og:description",
        content: "Imóveis, viaturas, tecnologia e moda com vendedores verificados e pagamento seguro.",
      },
    ],
  }),
  component: HomePage,
});

function HomePage() {
  const search = Route.useSearch();
  const navigate = useNavigate({ from: "/" });
  const { t, lang } = useI18n();
  const { user } = useAuth();
  const queryClient = useQueryClient();

  const [minDraft, setMinDraft] = useState(search.min ? String(search.min) : "");
  const [maxDraft, setMaxDraft] = useState(search.max ? String(search.max) : "");

  const listingsQuery = useQuery({
    queryKey: ["listings", search],
    queryFn: () =>
      fetchListings({
        search: search.q,
        category: search.category ?? null,
        province: search.province ?? null,
        condition: search.condition ?? null,
        minPrice: search.min ?? null,
        maxPrice: search.max ?? null,
        sort: search.sort ?? "recent",
      }),
  });

  const favoritesQuery = useQuery({
    queryKey: ["favorites", user?.id],
    queryFn: () => fetchFavoriteIds(user!.id),
    enabled: Boolean(user),
  });

  const savedIds = new Set(favoritesQuery.data ?? []);

  const onToggleSave = async (listing: Listing) => {
    if (!user) {
      toast.info(t("signInToContinue"));
      return;
    }
    const on = !savedIds.has(listing.id);
    await toggleFavorite(user.id, listing.id, on);
    toast.success(on ? t("saved") : t("remove"));
    queryClient.invalidateQueries({ queryKey: ["favorites"] });
  };

  const setSearch = (patch: Partial<HomeSearch>) =>
    navigate({ search: (prev) => ({ ...prev, ...patch }) });

  const listings = listingsQuery.data ?? [];
  const promoted = listings.find((l) => l.is_promoted) ?? null;
  const rest = (promoted ? listings.filter((l) => l.id !== promoted.id) : listings).slice(0, 12);

  const sortOptions: Array<{ key: NonNullable<HomeSearch["sort"]>; label: string }> = [
    { key: "recent", label: t("sortRecent") },
    { key: "cheap", label: t("sortCheap") },
    { key: "expensive", label: t("sortExpensive") },
    { key: "viewed", label: t("sortViewed") },
  ];

  return (
    <div className="mx-auto max-w-[1200px] px-4 sm:px-6">
      <div className="grid items-start gap-6 pt-6 lg:grid-cols-[220px_1fr]">
        <aside className="kuya-card hidden space-y-5 p-5 lg:sticky lg:top-36 lg:block">
          <div className="flex items-center justify-between">
            <h2 className="font-display text-lg font-bold">{t("filters")}</h2>
            <button
              type="button"
              className="text-xs font-semibold text-teal"
              onClick={() => navigate({ search: {} })}
            >
              {t("clear")}
            </button>
          </div>

          <div>
            <p className="mb-2 font-display text-sm font-semibold">{t("category")}</p>
            <div className="space-y-1.5 text-sm">
              {CATEGORIES.map((cat) => (
                <label key={cat.slug} className="flex cursor-pointer items-center gap-2">
                  <input
                    type="radio"
                    className="size-4 accent-[var(--teal)]"
                    checked={search.category === cat.slug}
                    onChange={() => setSearch({ category: cat.slug })}
                  />
                  {lang === "pt" ? cat.pt : cat.en}
                </label>
              ))}
            </div>
          </div>

          <div>
            <p className="mb-2 font-display text-sm font-semibold">{t("province")}</p>
            <select
              className="kuya-field"
              value={search.province ?? ""}
              onChange={(e) => setSearch({ province: e.target.value || undefined })}
            >
              <option value="">{t("all")}</option>
              {PROVINCES.map((p) => (
                <option key={p} value={p}>
                  {p}
                </option>
              ))}
            </select>
          </div>

          <div>
            <p className="mb-2 font-display text-sm font-semibold">{t("price")}</p>
            <div className="flex items-center gap-2">
              <input
                className="kuya-field"
                inputMode="numeric"
                placeholder={t("min")}
                value={minDraft}
                onChange={(e) => setMinDraft(e.target.value)}
              />
              <input
                className="kuya-field"
                inputMode="numeric"
                placeholder={t("max")}
                value={maxDraft}
                onChange={(e) => setMaxDraft(e.target.value)}
              />
            </div>
          </div>

          <div>
            <p className="mb-2 font-display text-sm font-semibold">{t("condition")}</p>
            <div className="flex gap-2">
              {CONDITIONS.map((c) => (
                <button
                  key={c.slug}
                  type="button"
                  onClick={() =>
                    setSearch({ condition: search.condition === c.slug ? undefined : c.slug })
                  }
                  className={`kuya-chip ${search.condition === c.slug ? "kuya-chip-active" : ""}`}
                >
                  {lang === "pt" ? c.pt : c.en}
                </button>
              ))}
            </div>
          </div>

          <button
            type="button"
            className="kuya-btn kuya-btn-primary w-full"
            onClick={() =>
              setSearch({
                min: minDraft ? Number(minDraft) : undefined,
                max: maxDraft ? Number(maxDraft) : undefined,
              })
            }
          >
            {t("apply")}
          </button>
        </aside>

        <section>
          <div className="mb-4 flex flex-wrap items-end justify-between gap-3">
            <div>
              <h1 className="font-display text-2xl leading-none font-bold sm:text-3xl">
                {t("marketTitle")}
              </h1>
              <p className="mt-1 text-sm text-muted-foreground">
                {listings.length} {t("resultsCount")} · {t("updatedToday")}
              </p>
            </div>
            <div className="flex gap-2 overflow-x-auto">
              {sortOptions.map((opt) => (
                <button
                  key={opt.key}
                  type="button"
                  onClick={() => setSearch({ sort: opt.key })}
                  className={`kuya-chip ${(search.sort ?? "recent") === opt.key ? "kuya-chip-active" : ""}`}
                >
                  {opt.label}
                </button>
              ))}
            </div>
          </div>

          {listingsQuery.isLoading ? <p className="py-10 text-sm">{t("loading")}</p> : null}

          {!listingsQuery.isLoading && listings.length === 0 ? (
            <p className="kuya-card p-8 text-center text-sm">{t("noResults")}</p>
          ) : null}

          {promoted ? (
            <>
              <div className="mb-3">
                <span className="rounded-full bg-gold px-2.5 py-0.5 font-display text-xs font-bold text-ink">
                  {t("featured")}
                </span>
              </div>
              <Link
                to="/listing/$id"
                params={{ id: promoted.id }}
                className="kuya-card group mb-4 block transition-transform hover:-translate-y-1"
              >
                <div className="relative aspect-[16/9] bg-mint md:aspect-[2.4/1]">
                  {promoted.images[0] ? (
                    <img
                      src={promoted.images[0]}
                      alt={promoted.title}
                      className="h-full w-full object-cover"
                      width={1200}
                      height={640}
                    />
                  ) : null}
                  {promoted.seller_verified ? (
                    <span className="absolute top-3 left-3 rounded-full bg-ink/80 px-3 py-1 text-xs font-bold text-cream">
                      {t("verifiedSeller")}
                    </span>
                  ) : null}
                </div>
                <div className="flex flex-col gap-3 p-4 sm:flex-row sm:items-center">
                  <div className="flex-1">
                    <h2 className="font-display text-lg leading-tight font-bold">{promoted.title}</h2>
                    <p className="mt-0.5 text-sm text-muted-foreground">
                      {promoted.municipality} · {promoted.province}
                    </p>
                  </div>
                  <div className="sm:text-right">
                    <p className="font-display text-2xl leading-none font-extrabold text-teal">
                      {formatKz(promoted.price)}
                    </p>
                    <p className="mt-1 text-xs text-muted-foreground">{t("securePayment")}</p>
                  </div>
                </div>
              </Link>
            </>
          ) : null}

          <div className="grid grid-cols-2 gap-3 md:grid-cols-3">
            {rest.map((listing) => (
              <ListingCard
                key={listing.id}
                listing={listing}
                saved={savedIds.has(listing.id)}
                onToggleSave={onToggleSave}
              />
            ))}
          </div>
        </section>
      </div>
    </div>
  );
}
