import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useMemo, useState } from "react";
import { Product, formatRWF } from "@/data/products";
import { apiUrl } from "@/lib/api";
import { resolveProductImage } from "@/lib/productImages";
import { ProductCard } from "@/components/ProductCard";

export const Route = createFileRoute("/shop")({
  head: () => ({
    meta: [
      { title: "Shop Fresh Tomatoes — Igiciro" },
      {
        name: "description",
        content:
          "Browse this week's tomato harvest from Rwandan farmers. Filter by location, price, and variety.",
      },
      { property: "og:title", content: "Shop Fresh Tomatoes — Igiciro" },
      {
        property: "og:description",
        content: "Browse this week's tomato harvest from Rwandan farmers.",
      },
    ],
  }),
  component: ShopPage,
});

const sorts = ["Featured", "Price: low to high", "Price: high to low"] as const;

function mapRawProduct(row: any): Product {
  return {
    id: String(row.id),
    name: row.name,
    variety: row.variety,
    image: resolveProductImage(row.image),
    pricePerKg: Number(row.price_per_kg),
    unit: row.unit as Product["unit"],
    location: row.location,
    district: row.district,
    available: row.status !== "unavailable" && Number(row.stock_kg) > 0,
    stockKg: Number(row.stock_kg),
    harvestDate: row.harvest_date,
    farmer: row.source_person_name,
    description: row.description,
    metaDescription: row.meta_description ?? "",
    sourceFarm: row.source_farm,
    delivery: row.delivery,
    status: row.status,
    sourcePersonName: row.source_person_name,
    sourcePersonNote: row.source_person_note ?? "",
    isDraft: Boolean(row.is_draft),
    isHidden: Boolean(row.is_hidden),
  };
}

function ShopPage() {
  const [district, setDistrict] = useState("All");
  const [sort, setSort] = useState<(typeof sorts)[number]>("Featured");
  const [inStock, setInStock] = useState(false);
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchProducts = async () => {
      setLoading(true);
      setError(null);
      try {
        const response = await fetch(apiUrl("/api/products?public=true"));
        const data = await response.json();
        if (!response.ok) {
          setError(data.message || "Unable to load shop products.");
          setProducts([]);
          return;
        }
        setProducts((data.products ?? []).map(mapRawProduct));
      } catch (error) {
        console.error(error);
        setError("Unable to load shop products.");
      } finally {
        setLoading(false);
      }
    };

    fetchProducts();
  }, []);

  const districts = useMemo(
    () => ["All", ...Array.from(new Set(products.map((p) => p.district)))],
    [products],
  );

  const list = useMemo(() => {
    let l = [...products];
    if (district !== "All") l = l.filter((p) => p.district === district);
    if (inStock) l = l.filter((p) => p.available);
    if (sort === "Price: low to high") l.sort((a, b) => a.pricePerKg - b.pricePerKg);
    if (sort === "Price: high to low") l.sort((a, b) => b.pricePerKg - a.pricePerKg);
    return l;
  }, [district, sort, inStock, products]);

  return (
    <>
      <section className="container-editorial pt-12 md:pt-20 pb-10">
        <p className="text-xs uppercase tracking-widest text-tomato">The shop</p>
        <h1 className="mt-3 font-display text-5xl md:text-6xl text-balance max-w-3xl">
          This week's harvest, ready to ship.
        </h1>
        <p className="mt-5 max-w-xl text-muted-foreground">
          Listings are curated and posted by our team after collecting from
          partner farmers. Quantities update daily.
        </p>
      </section>

      <section className="container-editorial pb-24">
        <div className="flex flex-wrap items-center gap-3 border-y border-border py-4 mb-10">
          <div className="flex items-center gap-2">
            <span className="text-xs uppercase tracking-widest text-muted-foreground">Location</span>
            <select
              value={district}
              onChange={(e) => setDistrict(e.target.value)}
              className="rounded-full border border-border bg-background px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
            >
              {districts.map((d) => (
                <option key={d}>{d}</option>
              ))}
            </select>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-xs uppercase tracking-widest text-muted-foreground">Sort</span>
            <select
              value={sort}
              onChange={(e) => setSort(e.target.value as (typeof sorts)[number])}
              className="rounded-full border border-border bg-background px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
            >
              {sorts.map((s) => (
                <option key={s}>{s}</option>
              ))}
            </select>
          </div>
          <label className="ml-auto inline-flex items-center gap-2 text-sm">
            <input
              type="checkbox"
              checked={inStock}
              onChange={(e) => setInStock(e.target.checked)}
              className="h-4 w-4 rounded border-border text-tomato focus:ring-tomato"
            />
            In stock only
          </label>
        </div>

        {loading ? (
          <p className="text-muted-foreground py-20 text-center">Loading products...</p>
        ) : error ? (
          <p className="text-destructive py-20 text-center">{error}</p>
        ) : list.length === 0 ? (
          <p className="text-muted-foreground py-20 text-center">
            No tomatoes match these filters. Try broadening your search.
          </p>
        ) : (
          <div className="grid gap-8 sm:grid-cols-2 lg:grid-cols-3">
            {list.map((p) => (
              <ProductCard key={p.id} p={p} />
            ))}
          </div>
        )}
      </section>
    </>
  );
}
