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

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

const Blog: React.FC<Props> = ({ posts }) => {
  const { localizedPath } = useLocalizedRoutes();
  const { t, i18n } = useTranslation('marketing');
  const locale = i18n.language || 'de'; // Fallback to 'de' if no locale

  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}`;
        return localizedPath(normalized);
      } catch (error) {
        console.warn('[Marketing Blog] Fallback resolving pagination link', { raw, error });
        return localizedPath(raw);
      }
    },
    [localizedPath]
  );

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

    return (
      <div className="mt-12">
        <Card className="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);

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

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

  return (
    <MarketingLayout title={t('blog.title')}>
      <Head title={t('blog.title')} />
      {/* Hero Section */}
      <section className="bg-aurora-enhanced py-20 px-4">
        <div className="container mx-auto max-w-4xl">
          <Card className="bg-white/10 backdrop-blur-sm border-white/20 shadow-xl">
            <CardContent className="p-8 md:p-12 text-center">
              <h1 className="text-4xl md:text-6xl font-bold mb-6 font-display text-gray-900 dark:text-gray-100">{t('blog.hero_title')}</h1>
              <p className="text-xl md:text-2xl mb-8 max-w-3xl mx-auto font-sans-marketing text-gray-800 dark:text-gray-200">{t('blog.hero_description')}</p>
              <Button
                asChild
                size="lg"
                className="bg-white text-[#FFB6C1] hover:bg-gray-100 px-8 py-4 rounded-full font-semibold text-lg font-sans-marketing"
              >
                <Link href="#posts">
                  {t('blog.hero_cta')}
                </Link>
              </Button>
            </CardContent>
          </Card>
        </div>
      </section>

      {/* Posts Section */}
      <section id="posts" className="py-20 px-4 bg-white dark:bg-gray-900">
        <div className="container mx-auto max-w-6xl">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold font-display text-gray-900 dark:text-gray-100 mb-4">{t('blog.posts_title')}</h2>
            <Separator className="w-24 mx-auto" />
          </div>

          {posts.data.length > 0 ? (
            <>
              <div className="grid md:grid-cols-2 gap-8">
                {posts.data.map((post) => (
                  <Card key={post.id} className="overflow-hidden hover:shadow-lg transition-shadow duration-300">
                    {post.featured_image && (
                      <div className="aspect-video overflow-hidden">
                        <img
                          src={post.featured_image}
                          alt={post.title}
                          className="w-full h-full object-cover hover:scale-105 transition-transform duration-300"
                        />
                      </div>
                    )}
                    <CardContent className="p-6">
                      <CardTitle className="text-xl font-semibold mb-3 font-sans-marketing">
                        <Link
                          href={`${localizedPath(`/blog/${post.slug}`)}`}
                          className="hover:text-[#FFB6C1] transition-colors"
                        >
                          {post.title?.[locale] || post.title?.de || post.title || 'No Title'}
                        </Link>
                      </CardTitle>

                      <p className="text-gray-700 dark:text-gray-300 font-serif-custom mb-4 leading-relaxed">
                        {post.excerpt?.[locale] || post.excerpt?.de || post.excerpt || 'No Excerpt'}
                      </p>

                      <div className="flex flex-col sm:flex-row items-start sm:items-center gap-3 mb-4">
                        <Badge variant="secondary" className="bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300">
                          {t('blog.by')} {post.author?.name?.[locale] || post.author?.name?.de || post.author?.name || t('blog.team')}
                        </Badge>
                        <Separator orientation="vertical" className="hidden sm:block h-4" />
                        <Badge variant="outline" className="text-gray-500">
                          {t('blog.published_at')} {new Date(post.published_at).toLocaleDateString('de-DE', {
                            day: 'numeric',
                            month: 'long',
                            year: 'numeric'
                          })}
                        </Badge>
                      </div>

                      <Button asChild variant="ghost" className="p-0 h-auto text-[#FFB6C1] hover:text-[#FF69B4] hover:bg-transparent">
                        <Link href={`${localizedPath(`/blog/${post.slug}`)}`} className="font-semibold">
                          {t('blog.read_more')}
                        </Link>
                      </Button>
                    </CardContent>
                  </Card>
                ))}
              </div>
              {renderPagination()}
            </>
          ) : (
            <Card className="p-8 text-center">
              <p className="text-gray-600 dark:text-gray-400 font-serif-custom">{t('blog.empty')}</p>
            </Card>
          )}
        </div>
      </section>
    </MarketingLayout>
  );
};

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

export default Blog;
