"use client";
import { useState, useEffect, useCallback } from "react";
import { useTranslations } from "next-intl";
import Link from "next/link";
import { Clock, Users, ChefHat, Flame, Heart, Sparkles, Rss, UserPlus } from "lucide-react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { EmptyState } from "@/components/shared/empty-state";
import { useLocale } from "@/lib/i18n/provider";

const PAGE_SIZE = 20;

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 FeedResponse = {
  data: FeedRecipe[];
  total: number;
  limit: number;
  offset: number;
};

type Props = {
  followedCount: number;
};

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 ?? ""} alt={recipe.authorName} />
          <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={`/recipes/${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>
  );
}

/** Shared paginated tab: fetches `endpoint`, supports "load more", and surfaces network
 * failures as a real error state (with retry) instead of silently rendering an empty list. */
function PaginatedFeedTab({
  endpoint,
  emptyMessage,
}: {
  endpoint: string;
  emptyMessage: string;
}) {
  const { locale } = useLocale();
  const t = useTranslations("feed");
  const [recipes, setRecipes] = useState<FeedRecipe[]>([]);
  const [total, setTotal] = useState(0);
  const [offset, setOffset] = useState(0);
  const [loading, setLoading] = useState(true);
  const [loadingMore, setLoadingMore] = useState(false);
  const [error, setError] = useState(false);

  const fetchPage = useCallback(
    async (off: number, append: boolean) => {
      if (append) setLoadingMore(true);
      else setLoading(true);
      setError(false);
      try {
        const res = await fetch(`${endpoint}?limit=${PAGE_SIZE}&offset=${off}`);
        if (!res.ok) throw new Error("Request failed");
        const json = (await res.json()) as FeedResponse;
        setRecipes((prev) => (append ? [...prev, ...json.data] : json.data));
        setTotal(json.total);
        setOffset(off + json.data.length);
      } catch {
        setError(true);
      } finally {
        setLoading(false);
        setLoadingMore(false);
      }
    },
    [endpoint]
  );

  useEffect(() => {
    void fetchPage(0, false);
  }, [fetchPage]);

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

  if (error && recipes.length === 0) {
    return (
      <div className="flex flex-col items-start gap-2">
        <p className="text-sm text-destructive">{t("loadFailed")}</p>
        <Button variant="outline" size="sm" onClick={() => void fetchPage(0, false)}>
          {t("retry")}
        </Button>
      </div>
    );
  }

  if (recipes.length === 0) return <EmptyState icon={Rss} title={emptyMessage} compact />;

  const hasMore = recipes.length < total;

  return (
    <div className="space-y-4">
      {recipes.map((recipe) => (
        <RecipeCard key={recipe.id} recipe={recipe} locale={locale} />
      ))}
      {error && (
        <p className="text-sm text-destructive">{t("loadFailed")}</p>
      )}
      {hasMore || error ? (
        <div className="flex justify-center pt-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() => void fetchPage(offset, true)}
            disabled={loadingMore}
          >
            {loadingMore ? t("loading") : error ? t("retry") : t("loadMore")}
          </Button>
        </div>
      ) : null}
    </div>
  );
}

export function FeedPageContent({ followedCount }: Props) {
  const t = useTranslations("feed");
  const [tab, setTab] = useState<"following" | "trending" | "forYou">("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>
        <button
          onClick={() => setTab("forYou")}
          className={`pb-2 px-1 text-sm font-medium border-b-2 transition-colors flex items-center gap-1.5 ${
            tab === "forYou"
              ? "border-primary text-foreground"
              : "border-transparent text-muted-foreground hover:text-foreground"
          }`}
        >
          <Sparkles className="h-3.5 w-3.5" />
          {t("forYou")}
        </button>
      </div>

      {tab === "following" ? (
        followedCount === 0 ? (
          <EmptyState
            icon={UserPlus}
            title={t("followEmpty")}
            description={t("followEmptyDescription")}
            action={{ label: t("findPeople"), href: "/explore?tab=people" }}
          />
        ) : (
          <PaginatedFeedTab endpoint="/api/v1/feed" emptyMessage={t("noNew")} />
        )
      ) : tab === "trending" ? (
        <PaginatedFeedTab endpoint="/api/v1/feed/trending" emptyMessage={t("trendingEmpty")} />
      ) : (
        <PaginatedFeedTab endpoint="/api/v1/feed/for-you" emptyMessage={t("forYouEmpty")} />
      )}
    </div>
  );
}
