"use client";
import { useState, useEffect } from "react";
import { useTranslations } from "next-intl";
import Link from "next/link";
import { Clock, Users, ChefHat, Flame, Heart } from "lucide-react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { useLocale } from "@/lib/i18n/provider";

type FeedRecipe = {
  id: string;
  title: string;
  description: string | null;
  baseServings: number;
  prepMins: number | null;
  cookMins: number | null;
  difficulty: string | null;
  aiGenerated: boolean;
  createdAt: string;
  authorId: string;
  authorName: string;
  authorUsername: string | null;
  authorAvatarUrl: string | null;
  visibility: string;
  favoriteCount?: number;
};

type Props = {
  followedCount: number;
  feedRecipes: FeedRecipe[];
};

function RecipeCard({ recipe, locale }: { recipe: FeedRecipe; locale: string }) {
  return (
    <article className="rounded-xl border p-4 hover:shadow-sm transition-shadow">
      <div className="flex items-center gap-3 mb-3">
        <Avatar className="h-7 w-7">
          <AvatarImage src={recipe.authorAvatarUrl ?? ""} />
          <AvatarFallback className="text-xs">{recipe.authorName.slice(0, 2).toUpperCase()}</AvatarFallback>
        </Avatar>
        <div className="flex items-baseline gap-2 text-sm">
          <Link href={`/u/${recipe.authorUsername ?? recipe.authorId}`} className="font-medium hover:underline">
            {recipe.authorName}
          </Link>
          <span className="text-muted-foreground text-xs">
            {new Date(recipe.createdAt).toLocaleDateString(locale, { month: "short", day: "numeric" })}
          </span>
        </div>
        <div className="ml-auto flex items-center gap-2">
          {recipe.favoriteCount !== undefined && recipe.favoriteCount > 0 && (
            <span className="flex items-center gap-1 text-xs text-muted-foreground">
              <Heart className="h-3 w-3 fill-rose-500 text-rose-500" />
              {recipe.favoriteCount}
            </span>
          )}
          {recipe.aiGenerated && <Badge variant="secondary" className="text-xs">AI</Badge>}
        </div>
      </div>

      <Link href={`/r/${recipe.id}`} className="group block space-y-2">
        <h2 className="font-semibold text-lg group-hover:text-primary transition-colors">{recipe.title}</h2>
        {recipe.description && (
          <p className="text-sm text-muted-foreground line-clamp-2">{recipe.description}</p>
        )}
        <div className="flex items-center gap-3 text-xs text-muted-foreground">
          {recipe.difficulty && <Badge variant="outline" className="text-xs">{recipe.difficulty}</Badge>}
          <span className="flex items-center gap-1"><Users className="h-3 w-3" />{recipe.baseServings}</span>
          {recipe.prepMins && <span className="flex items-center gap-1"><Clock className="h-3 w-3" />{recipe.prepMins}m</span>}
          {recipe.cookMins && <span className="flex items-center gap-1"><ChefHat className="h-3 w-3" />{recipe.cookMins}m</span>}
        </div>
      </Link>
    </article>
  );
}

function TrendingTab() {
  const { locale } = useLocale();
  const t = useTranslations("feed");
  const [recipes, setRecipes] = useState<FeedRecipe[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/v1/feed/trending")
      .then((r) => r.json() as Promise<{ data: FeedRecipe[] }>)
      .then(({ data }) => setRecipes(data))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <p className="text-sm text-muted-foreground">{t("loading")}</p>;
  if (recipes.length === 0) return <p className="text-sm text-muted-foreground">{t("trendingEmpty")}</p>;

  return (
    <div className="space-y-4">
      {recipes.map((recipe) => (
        <RecipeCard key={recipe.id} recipe={recipe} locale={locale} />
      ))}
    </div>
  );
}

export function FeedPageContent({ followedCount, feedRecipes }: Props) {
  const t = useTranslations("feed");
  const { locale } = useLocale();
  const [tab, setTab] = useState<"following" | "trending">("following");

  return (
    <div className="space-y-6 max-w-2xl">
      <h1 className="text-3xl font-bold tracking-tight">{t("title")}</h1>

      {/* Tabs */}
      <div className="flex gap-1 border-b">
        <button
          onClick={() => setTab("following")}
          className={`pb-2 px-1 text-sm font-medium border-b-2 transition-colors ${
            tab === "following"
              ? "border-primary text-foreground"
              : "border-transparent text-muted-foreground hover:text-foreground"
          }`}
        >
          {t("following")}
        </button>
        <button
          onClick={() => setTab("trending")}
          className={`pb-2 px-1 text-sm font-medium border-b-2 transition-colors flex items-center gap-1.5 ${
            tab === "trending"
              ? "border-primary text-foreground"
              : "border-transparent text-muted-foreground hover:text-foreground"
          }`}
        >
          <Flame className="h-3.5 w-3.5" />
          {t("trending")}
        </button>
      </div>

      {tab === "following" ? (
        followedCount === 0 ? (
          <div className="flex flex-col items-center justify-center h-64 border-2 border-dashed rounded-xl gap-4">
            <p className="text-muted-foreground text-sm">{t("followEmpty")}</p>
          </div>
        ) : feedRecipes.length === 0 ? (
          <p className="text-muted-foreground text-sm">{t("noNew")}</p>
        ) : (
          <div className="space-y-4">
            {feedRecipes.map((recipe) => (
              <RecipeCard key={recipe.id} recipe={recipe} locale={locale} />
            ))}
          </div>
        )
      ) : (
        <TrendingTab />
      )}
    </div>
  );
}
