"use client";

import { useRef } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Flame, Clock, ChefHat, Search } from "lucide-react";
import type { RecipeResult } from "@/app/(app)/explore/page";

const DIFFICULTY_COLORS: Record<string, string> = {
  easy: "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",
  medium: "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200",
  hard: "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200",
};

function RecipeCard({ recipe }: { recipe: RecipeResult }) {
  const totalMins = (recipe.prepMins ?? 0) + (recipe.cookMins ?? 0);
  return (
    <Link
      href={`/recipes/${recipe.id}`}
      className="group block rounded-lg border bg-card p-4 shadow-sm transition-shadow hover:shadow-md min-w-[200px]"
    >
      <div className="flex items-start justify-between gap-2">
        <h3 className="font-semibold text-card-foreground group-hover:text-primary line-clamp-2 flex-1">
          {recipe.title}
        </h3>
        {recipe.difficulty && (
          <Badge
            variant="secondary"
            className={`shrink-0 capitalize text-xs ${DIFFICULTY_COLORS[recipe.difficulty] ?? ""}`}
          >
            {recipe.difficulty}
          </Badge>
        )}
      </div>
      <div className="mt-3 flex items-center gap-3 text-xs text-muted-foreground">
        {totalMins > 0 && (
          <span className="flex items-center gap-1">
            <Clock className="h-3.5 w-3.5" />
            {totalMins}m
          </span>
        )}
        {recipe.authorName && (
          <span className="flex items-center gap-1">
            <ChefHat className="h-3.5 w-3.5" />
            {recipe.authorName}
          </span>
        )}
      </div>
    </Link>
  );
}

function HorizontalScroll({ children }: { children: React.ReactNode }) {
  return (
    <div className="flex gap-4 overflow-x-auto pb-2 -mx-4 px-4 snap-x snap-mandatory">
      {children}
    </div>
  );
}

type Props = {
  trending: RecipeResult[];
  recent: RecipeResult[];
};

export function ExplorePageContent({ trending, recent }: Props) {
  const router = useRouter();
  const inputRef = useRef<HTMLInputElement>(null);

  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const q = inputRef.current?.value.trim();
    if (q) router.push(`/search?q=${encodeURIComponent(q)}`);
    else router.push("/search");
  };

  return (
    <div className="max-w-5xl mx-auto space-y-10">
      {/* Search bar */}
      <div>
        <h1 className="text-3xl font-bold mb-6">Explore</h1>
        <form onSubmit={handleSearchSubmit} className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground pointer-events-none" />
          <Input
            ref={inputRef}
            placeholder="Search recipes..."
            className="pl-10 h-12 text-base"
          />
        </form>
      </div>

      {/* Trending this week */}
      <section>
        <div className="flex items-center gap-2 mb-4">
          <Flame className="h-5 w-5 text-orange-500" />
          <h2 className="text-xl font-semibold">Trending this week</h2>
        </div>
        {trending.length === 0 ? (
          <p className="text-muted-foreground text-sm py-8 text-center">
            No trending recipes yet. Be the first to share one!
          </p>
        ) : (
          <HorizontalScroll>
            {trending.map((recipe) => (
              <div key={recipe.id} className="snap-start shrink-0 w-56">
                <RecipeCard recipe={recipe} />
              </div>
            ))}
          </HorizontalScroll>
        )}
      </section>

      {/* Recently added */}
      <section>
        <div className="flex items-center gap-2 mb-4">
          <Clock className="h-5 w-5 text-blue-500" />
          <h2 className="text-xl font-semibold">Recently added</h2>
        </div>
        {recent.length === 0 ? (
          <p className="text-muted-foreground text-sm py-8 text-center">
            No public recipes yet.
          </p>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
            {recent.map((recipe) => (
              <RecipeCard key={recipe.id} recipe={recipe} />
            ))}
          </div>
        )}
      </section>
    </div>
  );
}
