import React, { useMemo } from 'react';
import { Head, Link, usePage } from '@inertiajs/react';
import { useLocalizedRoutes } from '@/hooks/useLocalizedRoutes';
import { useTranslation } from 'react-i18next';
import MarketingLayout from '@/layouts/mainWebsite';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Button } from '@/components/ui/button';
import { Alert, AlertDescription } from '@/components/ui/alert';

interface PostSummary {
  id: number;
  slug: string;
  title: string;
  excerpt?: string;
  excerpt_html?: string;
  featured_image?: string;
  published_at?: string;
  author?: { name?: string } | string;
}

interface PaginationLink {
  url: string | null;
  label: string;
  active: boolean;
}

interface Props {
  posts: {
    data: PostSummary[];
    links: PaginationLink[];
    current_page: number;
    last_page: number;
  };
}

const MarkdownPreview: React.FC<{ html?: string; fallback?: string; className?: string }> = ({ html, fallback, className }) => {
  if (html && html.trim().length > 0) {
    return <div className={className} dangerouslySetInnerHTML={{ __html: html }} />;
  }

  if (!fallback) {
    return null;
  }

  return <p className={className}>{fallback}</p>;
};

const Blog: React.FC<Props> = ({ posts }) => {
  const { localizedPath } = useLocalizedRoutes();
  const { props } = usePage<{ supportedLocales?: string[] }>();
  const supportedLocales = useMemo(
    () => (props.supportedLocales && props.supportedLocales.length > 0 ? props.supportedLocales : ['de', 'en']),
    [props.supportedLocales]
  );
  const { t, i18n } = useTranslation('marketing');
  const locale = i18n.language || 'de';
  const articles = posts?.data ?? [];
  const isLandingLayout = posts.current_page === 1;
  const featuredPost = isLandingLayout ? articles[0] : null;
  const gridPosts = isLandingLayout ? articles.slice(1, 4) : [];
  const listPosts = isLandingLayout ? [] : articles;
  const dateLocale = locale === 'en' ? 'en-US' : 'de-DE';

  const buildArticleHref = React.useCallback(
    (slug?: string | null) => {
      if (!slug) {
        return '#';
      }

      return localizedPath(`/blog/${encodeURIComponent(slug)}`);
    },
    [localizedPath]
  );

  const formatPublishedDate = React.useCallback(
    (raw?: string) => {
      if (!raw) {
        return '';
      }

      try {
        return new Date(raw).toLocaleDateString(dateLocale, {
          day: 'numeric',
          month: 'long',
          year: 'numeric',
        });
      } catch (error) {
        console.warn('[Marketing Blog] Unable to parse date', { raw, error });
        return raw;
      }
    },
    [dateLocale]
  );

  const resolvePaginationHref = React.useCallback(
    (raw?: string | null) => {
      if (!raw) {
        return null;
      }

      try {
        const parsed = new URL(
          raw,
          typeof window !== 'undefined' ? window.location.origin : 'http://localhost'
        );

        const normalized = `${parsed.pathname}${parsed.search}`;
        const localePrefixRegex = new RegExp(`^/(${supportedLocales.join('|')})(/|$)`);

        if (localePrefixRegex.test(parsed.pathname)) {
          return normalized;
        }

        return localizedPath(normalized);
      } catch (error) {
        console.warn('[Marketing Blog] Fallback resolving pagination link', { raw, error });
        return localizedPath(raw);
      }
    },
    [localizedPath, supportedLocales]
  );

  const renderPagination = () => {
    if (!posts.links || posts.links.length <= 3) {
      return null;
    }

    return (
      <div className="mt-12">
        <Card className="p-4 md:p-6">
          <div className="flex justify-center">
            <div className="flex flex-wrap justify-center gap-2">
              {posts.links.map((link, index) => {
                const href = resolvePaginationHref(link.url);
                const labelText = link.label?.trim() || '…';

                if (!href) {
                  return (
                    <Button
                      key={index}
                      variant={link.active ? 'default' : 'outline'}
                      disabled
                      className={link.active ? 'bg-[#FFB6C1] hover:bg-[#FF69B4]' : ''}
                    >
                      {labelText}
                    </Button>
                  );
                }

                return (
                  <Button
                    key={index}
                    asChild
                    variant={link.active ? 'default' : 'outline'}
                    className={link.active ? 'bg-[#FFB6C1] hover:bg-[#FF69B4]' : ''}
                  >
                    <Link href={href} aria-label={labelText}>
                      {labelText}
                    </Link>
                  </Button>
                );
              })}
            </div>
          </div>
        </Card>
      </div>
    );
  };

  const renderPostMeta = (post: PostSummary) => (
    <div className="flex flex-col gap-2 text-sm text-gray-600 dark:text-gray-300 sm:flex-row sm:items-center sm:gap-4">
      <span>
        {t('blog.by')} {typeof post.author === 'string' ? post.author : post.author?.name || t('blog.team')}
      </span>
      <Separator orientation="vertical" className="hidden h-4 sm:block" />
      <span>
        {t('blog.published_at')} {formatPublishedDate(post.published_at)}
      </span>
    </div>
  );

  const renderLandingGrid = () => {
    if (!featuredPost) {
      return (
        <Alert className="bg-white shadow-sm dark:bg-gray-950">
          <AlertDescription className="text-gray-600 dark:text-gray-300">
            {t('blog.empty')}
          </AlertDescription>
        </Alert>
      );
    }

    return (
      <div className="space-y-16">
        <div className="grid gap-8 lg:grid-cols-12 lg:items-center">
          <div className="order-2 space-y-6 rounded-3xl border border-gray-200 bg-white p-8 shadow-xl dark:border-gray-800 dark:bg-gray-950 lg:order-1 lg:col-span-6">
            <Badge variant="outline" className="w-fit border-pink-200 text-pink-600 dark:border-pink-500 dark:text-pink-300">
              {t('blog.posts_title')}
            </Badge>
            <h2 className="text-3xl font-bold text-gray-900 dark:text-gray-50">
              {featuredPost.title || 'Untitled'}
            </h2>
            <MarkdownPreview
              html={featuredPost.excerpt_html}
              fallback={featuredPost.excerpt}
              className="text-lg leading-relaxed text-gray-600 dark:text-gray-300"
            />
            {renderPostMeta(featuredPost)}
            <Button asChild size="lg" className="bg-[#FFB6C1] hover:bg-[#FF69B4] text-white">
              <Link href={buildArticleHref(featuredPost.slug)}>
                {t('blog.read_more')}
              </Link>
            </Button>
          </div>
          <div className="order-1 lg:order-2 lg:col-span-6">
            <div className="relative overflow-hidden rounded-3xl border border-gray-200 bg-gradient-to-br from-pink-200 via-white to-amber-100 shadow-2xl dark:border-gray-800 dark:from-pink-900/40 dark:via-gray-900 dark:to-gray-950">
              {featuredPost.featured_image && (
                <img
                  src={featuredPost.featured_image}
                  alt={featuredPost.title}
                  className="h-full w-full object-cover"
                />
              )}
              {!featuredPost.featured_image && (
                <div className="aspect-[5/4] p-8 text-3xl font-semibold text-gray-900 dark:text-gray-50">
                  Fotospiel Stories
                </div>
              )}
            </div>
          </div>
        </div>

        {gridPosts.length > 0 && (
          <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
            {gridPosts.map((post) => (
              <Card key={post.id} className="flex h-full flex-col overflow-hidden border-gray-200 shadow-sm transition hover:-translate-y-1 hover:shadow-lg dark:border-gray-800">
                {post.featured_image && (
                  <div className="aspect-video">
                    <img src={post.featured_image} alt={post.title} className="h-full w-full object-cover" />
                  </div>
                )}
                <CardContent className="flex flex-1 flex-col space-y-4 p-6">
                  <div className="space-y-2">
                    <h3 className="text-xl font-semibold text-gray-900 dark:text-gray-50">
                      {post.title || 'Untitled'}
                    </h3>
                    <MarkdownPreview
                      html={post.excerpt_html}
                      fallback={post.excerpt}
                      className="text-sm leading-relaxed text-gray-600 dark:text-gray-300"
                    />
                  </div>
                  <div className="flex-1" />
                  {renderPostMeta(post)}
                  <Button asChild variant="ghost" className="justify-start p-0 text-pink-600 hover:text-pink-700">
                    <Link href={buildArticleHref(post.slug)}>
                      {t('blog.read_more')}
                    </Link>
                  </Button>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>
    );
  };

  const renderListView = () => (
    <div className="space-y-6">
      {listPosts.map((post) => (
        <Card key={post.id} className="overflow-hidden border-gray-200 shadow-sm hover:shadow-lg dark:border-gray-800">
          <div className="grid gap-0 md:grid-cols-3">
            {post.featured_image && (
              <img
                src={post.featured_image}
                alt={post.title}
                className="h-full w-full object-cover"
              />
            )}
            <CardContent className="md:col-span-2">
              <div className="space-y-4 py-6">
                <h3 className="text-2xl font-semibold text-gray-900 dark:text-gray-50">
                  {post.title || 'Untitled'}
                </h3>
                <MarkdownPreview
                  html={post.excerpt_html}
                  fallback={post.excerpt}
                  className="text-gray-600 dark:text-gray-300"
                />
                {renderPostMeta(post)}
                <Button asChild variant="outline" className="w-fit border-pink-200 text-pink-600 hover:bg-pink-50 dark:border-pink-500/40 dark:text-pink-200">
                  <Link href={buildArticleHref(post.slug)}>
                    {t('blog.read_more')}
                  </Link>
                </Button>
              </div>
            </CardContent>
          </div>
        </Card>
      ))}
      {listPosts.length === 0 && (
        <Card className="p-8 text-center text-gray-600 dark:text-gray-300">{t('blog.empty')}</Card>
      )}
    </div>
  );

  return (
    <MarketingLayout title={t('blog.title')}>
      <Head title={t('blog.title')} />

      <section className="bg-gradient-to-br from-pink-50 via-white to-amber-50 px-4 py-10 dark:from-gray-950 dark:via-gray-900 dark:to-gray-950 md:py-12">
        <div className="container mx-auto max-w-3xl space-y-5 text-center">
          <Badge variant="outline" className="border-pink-200 text-pink-600 dark:border-pink-500/50 dark:text-pink-200">
            Fotospiel Blog
          </Badge>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-gray-50 md:text-4xl">{t('blog.hero_title')}</h1>
          <p className="text-base leading-relaxed text-gray-600 dark:text-gray-300 md:text-lg">{t('blog.hero_description')}</p>
          <div className="flex flex-wrap justify-center gap-2.5">
            <Button asChild className="bg-[#FFB6C1] hover:bg-[#FF69B4] text-white px-6 py-2.5 text-base">
              <Link href={localizedPath('/packages')}>{t('home.cta_explore')}</Link>
            </Button>
            <Button asChild variant="outline" className="border-gray-300 text-gray-800 hover:bg-gray-100 px-6 py-2.5 text-base dark:border-gray-700 dark:text-gray-50 dark:hover:bg-gray-800">
              <Link href="#articles">{t('blog.hero_cta')}</Link>
            </Button>
          </div>
        </div>
      </section>

      <section id="articles" className="bg-white px-4 py-16 dark:bg-gray-950">
        <div className="container mx-auto max-w-6xl space-y-12">
          <div className="text-center">
            <h2 className="text-3xl font-bold text-gray-900 dark:text-gray-50">{t('blog.posts_title')}</h2>
            <Separator className="mx-auto mt-4 w-24" />
          </div>

          {isLandingLayout ? renderLandingGrid() : renderListView()}

          {renderPagination()}
        </div>
      </section>
    </MarketingLayout>
  );
};

Blog.layout = (page: React.ReactNode) => page;

export default Blog;
