import { useEffect, useState } from "react";
import axios from "axios";
import Markdown from "react-markdown";
import { useLanguageStore } from "@/stores/languageStore";
import { useTranslation } from 'react-i18next';

type TranslatedField = string | Record<string, string>;

type NewsPost = {
  id: number;
  slug: string;
  title: TranslatedField;
  excerpt: TranslatedField | null;
  content: TranslatedField;
  published_at: string;
};

type PaginatedResponse<T> = {
  data: T[];
};

function resolveTranslation(
  field: TranslatedField | null | undefined,
  locale: string
): string {
  if (!field) return "";

  if (typeof field === "string") {
    return field;
  }

  if (field[locale]) return field[locale];
  if (field["en"]) return field["en"];

  const first = Object.values(field)[0];
  return first ?? "";
}

function formatDate(value: string | null | undefined, locale: string): string {
  if (!value) return "";

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";

  return new Intl.DateTimeFormat(locale, {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
  }).format(date);
}

type NewsListProps = {
  initialLimit?: number;
};

export default function NewsList({ initialLimit = 3 }: NewsListProps) {
  const locale = useLanguageStore((s) => s.locale);
  const { t } = useTranslation("common");
  const [items, setItems] = useState<NewsPost[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [limit, setLimit] = useState(initialLimit);

  useEffect(() => {
    let active = true;

    (async () => {
      try {
        setLoading(true);
        setError(null);

        const res = await axios.get<PaginatedResponse<NewsPost> | NewsPost[]>(
          "/api/news",
          {
            withCredentials: true,
            headers: { Accept: "application/json" },
            params: { lang: locale, limit }, // <<<< tady se pošle jazyk na backend
          }
        );

        if (!active) return;

        const data = Array.isArray(res.data)
          ? res.data
          : (res.data as PaginatedResponse<NewsPost>).data;

        setItems(data);
      } catch {
        if (!active) return;
        setError("Nepodařilo se načíst novinky.");
      } finally {
        if (active) setLoading(false);
      }
    })();

    return () => {
      active = false;
    };
    // <<<< refetch při změně jazyka
  }, [locale, limit]);

  if (loading) return <div>Načítám novinky…</div>;
  if (error) return <div className="text-red-600 text-sm">{error}</div>;

  if (items.length === 0) {
    return;
  }

  return (
    <div className="space-y-8">
      {items.map((post) => {
        const title = resolveTranslation(post.title, locale);
        const content = resolveTranslation(post.content, locale);

        return (
          <article
            key={post.id}
            className="border-b border-gray-200 dark:border-gray-700 pb-6"
          >
            <h2 className="text-xl font-semibold mb-1">{title}</h2>

            {post.published_at && (
              <p className="text-xs text-gray-500 mb-3">
                {formatDate(post.published_at, locale)}
              </p>
            )}

            <div className="prose dark:prose-invert max-w-none text-sm">
              <Markdown>{content}</Markdown>
            </div>
          </article>
        );
      })}

      {items.length >= limit && (
        <div className="flex justify-end">
          <button
            type="button"
            className="text-primary underline text-sm"
            onClick={() => setLimit((prev) => prev + 3)}
          >
            {t("news_show_more") ?? "Zobrazit další"}
          </button>
        </div>
      )}
    </div>
  );
}
