import { createFileRoute, Link, notFound } from "@tanstack/react-router";
import { useState } from "react";
import { ArrowLeft, MapPin, Calendar, Truck, Minus, Plus, MessageSquare } from "lucide-react";
import { apiUrl } from "@/lib/api";
import { Product, formatRWF } from "@/data/products";
import { resolveProductImage } from "@/lib/productImages";

export const Route = createFileRoute("/product/$productId")({
  loader: async ({ params }) => {
    const response = await fetch(apiUrl(`/api/products/${params.productId}?public=true`));
    const data = await response.json();
    if (!response.ok || !data.success || !data.product) {
      throw notFound();
    }

    return {
      product: mapRawProduct(data.product),
    };
  },
  head: ({ loaderData }) => ({
    meta: loaderData
      ? [
          { title: `${loaderData.product.name} — Igiciro` },
          { name: "description", content: loaderData.product.metaDescription || loaderData.product.description },
          { property: "og:title", content: `${loaderData.product.name} — Igiciro` },
          { property: "og:description", content: loaderData.product.metaDescription || loaderData.product.description },
          { property: "og:image", content: loaderData.product.image },
        ]
      : [],
  }),
  notFoundComponent: () => (
    <div className="container-editorial py-32 text-center">
      <h1 className="font-display text-4xl">Product not found</h1>
      <Link to="/shop" className="mt-6 inline-block text-tomato underline">
        Back to shop
      </Link>
    </div>
  ),
  component: ProductPage,
});

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 ProductPage() {
  const { product: p } = Route.useLoaderData();
  const [qty, setQty] = useState(1);

  return (
    <section className="container-editorial pt-16 md:pt-24 pb-24">
      <Link
        to="/shop"
        className="inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground"
      >
        <ArrowLeft className="h-4 w-4" /> Back to shop
      </Link>

      <div className="mt-8 grid gap-12 md:grid-cols-2 md:items-start">
        <div className="aspect-square overflow-hidden rounded-3xl bg-muted">
          <img
            src={p.image}
            alt={p.name}
            width={1024}
            height={1024}
            className="h-full w-full object-cover"
          />
        </div>

        <div>
          <p className="text-xs uppercase tracking-widest text-tomato">
            {p.variety} · {p.location}
          </p>
          <h1 className="mt-3 font-display text-5xl md:text-6xl leading-[1.05] text-balance">
            {p.name}
          </h1>
          <p className="mt-6 font-display text-3xl text-tomato">
            {formatRWF(p.pricePerKg)} <span className="text-sm text-muted-foreground font-sans">/ {p.unit}</span>
          </p>

          <p className="mt-6 text-base text-muted-foreground leading-relaxed">{p.description}</p>

          <dl className="mt-8 grid grid-cols-2 gap-4">
            <Detail icon={MapPin} label="Source farm" value={p.sourceFarm} />
            <Detail icon={Calendar} label="Harvested" value={fmtDate(p.harvestDate)} />
            <Detail icon={Truck} label="Delivery" value={p.delivery} />
            <Detail icon={MapPin} label="Available" value={p.available ? `${p.stockKg} kg ready` : "0 kg"} />
          </dl>

          <div className="mt-8 rounded-2xl border border-border bg-muted/40 p-4">
            <p className="text-xs uppercase tracking-widest text-muted-foreground">Sourced from</p>
            <p className="mt-1 font-display text-lg">{p.sourcePersonName}</p>
            <p className="mt-2 text-sm text-muted-foreground">{p.sourcePersonNote}</p>
          </div>

          <div className="mt-8 flex flex-wrap items-center gap-4">
            <div className="inline-flex items-center rounded-full border border-border">
              <button
                onClick={() => setQty((q) => Math.max(1, q - 1))}
                className="h-12 w-12 grid place-items-center hover:bg-muted rounded-l-full"
                aria-label="Decrease"
                disabled={!p.available}
              >
                <Minus className="h-4 w-4" />
              </button>
              <span className="min-w-12 text-center font-display text-lg">{qty}</span>
              <button
                onClick={() => setQty((q) => q + 1)}
                className="h-12 w-12 grid place-items-center hover:bg-muted rounded-r-full"
                aria-label="Increase"
                disabled={!p.available}
              >
                <Plus className="h-4 w-4" />
              </button>
            </div>
            <a
              href={getWhatsAppUrl(p, qty)}
              target="_blank"
              rel="noopener noreferrer"
              className={`flex-1 min-w-[200px] inline-flex items-center justify-center gap-2 rounded-full px-8 py-4 text-sm font-medium transition-colors ${
                p.available
                  ? "bg-foreground text-background hover:bg-foreground/90"
                  : "cursor-not-allowed bg-slate-200 text-slate-500"
              }`}
            >
              <MessageSquare className="h-4 w-4" />
              {p.available ? `Order via WhatsApp · ${formatRWF(p.pricePerKg * qty)}` : "Currently sold out"}
            </a>
          </div>
          {p.available ? (
            <p className="mt-3 text-sm text-slate-500">
              You'll be redirected to WhatsApp to place your order and confirm delivery.
            </p>
          ) : null}
        </div>
      </div>
    </section>
  );
}

function Detail({
  icon: Icon,
  label,
  value,
}: {
  icon: React.ComponentType<{ className?: string }>;
  label: string;
  value: string;
}) {
  return (
    <div className="rounded-2xl border border-border p-4">
      <div className="flex items-center gap-2 text-xs uppercase tracking-widest text-muted-foreground">
        <Icon className="h-3.5 w-3.5" /> {label}
      </div>
      <p className="mt-1.5 font-display text-base">{value}</p>
    </div>
  );
}

function getWhatsAppUrl(product: Product, qty: number) {
  const phone = "250790217818";
  const message = `Hello Igiciro! I would like to order ${qty} ${product.unit}${qty > 1 ? "s" : ""} of ${product.name} (${product.variety}) for delivery. Please let me know the next steps.`;
  return `https://wa.me/${phone}?text=${encodeURIComponent(message)}`;
}

function fmtDate(iso: string) {
  return new Date(iso).toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
  });
}
