'use client';

import { useState, useRef, useEffect } from 'react';
import { useTranslations } from 'next-intl';
import { Link } from '@/i18n/navigation';
import { motion, useInView } from 'framer-motion';
import {
  Ship,
  BookOpen,
  Calendar,
  Clock,
  User,
  ArrowRight,
  Search,
  TrendingUp,
  Globe,
  FileText,
  Anchor,
  type LucideIcon,
} from 'lucide-react';
import { LandingHeader, LandingFooter } from '@/components/layout';
import { getBlogPosts, type BlogPost, type BlogPostCategory } from '@/lib/api/blog';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000';
function resolveUrl(url: string | null | undefined): string | undefined {
  if (!url) return undefined;
  if (url.startsWith('http')) return url;
  return `${API_BASE_URL}${url}`;
}

type CategoryKey = 'all' | BlogPostCategory;

const CATEGORIES: { key: CategoryKey; icon: LucideIcon }[] = [
  { key: 'all', icon: BookOpen },
  { key: 'industry', icon: Ship },
  { key: 'technology', icon: TrendingUp },
  { key: 'guides', icon: FileText },
  { key: 'news', icon: Globe },
];

const containerVariants = {
  hidden: { opacity: 0, y: 50 },
  visible: {
    opacity: 1,
    y: 0,
    transition: { duration: 0.6, staggerChildren: 0.1 },
  },
};

const itemVariants = {
  hidden: { opacity: 0, y: 20 },
  visible: { opacity: 1, y: 0, transition: { duration: 0.5 } },
};

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('fr-FR', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  });
}

export default function BlogPage() {
  const t = useTranslations('marketing.blog');
  const [selectedCategory, setSelectedCategory] = useState<CategoryKey>('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [posts, setPosts] = useState<BlogPost[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [featuredPost, setFeaturedPost] = useState<BlogPost | null>(null);

  const heroRef = useRef(null);
  const articlesRef = useRef(null);
  const categoriesRef = useRef(null);

  const isHeroInView = useInView(heroRef, { once: true });
  const isArticlesInView = useInView(articlesRef, { once: true });
  const isCategoriesInView = useInView(categoriesRef, { once: true });

  useEffect(() => {
    let cancelled = false;

    const load = async () => {
      setLoading(true);
      try {
        const res = await getBlogPosts({
          category: selectedCategory !== 'all' ? selectedCategory : undefined,
          search: searchQuery || undefined,
          limit: 50,
        });
        if (!cancelled) {
          const featured = res.posts.find(p => p.isFeatured) ?? res.posts[0] ?? null;
          const rest = res.posts.filter(p => p !== featured);
          setFeaturedPost(featured);
          setPosts(rest);
          setTotal(res.total);
        }
      } catch {
        if (!cancelled) {
          setPosts([]);
          setFeaturedPost(null);
          setTotal(0);
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    };

    load();
    return () => {
      cancelled = true;
    };
  }, [selectedCategory, searchQuery]);

  return (
    <div className="min-h-screen bg-white">
      <LandingHeader activePage="blog" />

      {/* Hero Section */}
      <section
        ref={heroRef}
        className="relative pt-32 pb-20 bg-gradient-to-br from-brand-navy to-brand-navy/95 overflow-hidden"
      >
        <div className="absolute inset-0 opacity-10">
          <div className="absolute top-20 left-20 w-96 h-96 bg-brand-turquoise rounded-full blur-3xl" />
          <div className="absolute bottom-20 right-20 w-96 h-96 bg-brand-green rounded-full blur-3xl" />
        </div>

        <div className="relative z-10 max-w-7xl mx-auto px-6 lg:px-8">
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            animate={isHeroInView ? { opacity: 1, y: 0 } : {}}
            transition={{ duration: 0.8 }}
            className="text-center"
          >
            <motion.div
              initial={{ scale: 0.8, opacity: 0 }}
              animate={isHeroInView ? { scale: 1, opacity: 1 } : {}}
              transition={{ duration: 0.6, delay: 0.2 }}
              className="inline-flex items-center space-x-2 bg-white/10 backdrop-blur-sm px-4 py-2 rounded-full mb-8 border border-white/20"
            >
              <BookOpen className="w-5 h-5 text-brand-turquoise" />
              <span className="text-white/90 text-sm font-medium">{t('badge')}</span>
            </motion.div>

            <h1 className="text-4xl lg:text-6xl font-bold text-white mb-6 leading-tight">
              {t('title1')}
              <br />
              <span className="text-transparent bg-clip-text bg-gradient-to-r from-brand-turquoise to-brand-green">
                {t('title2')}
              </span>
            </h1>

            <p className="text-xl text-white/80 mb-10 max-w-3xl mx-auto leading-relaxed">
              {t('intro')}
            </p>

            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={isHeroInView ? { opacity: 1, y: 0 } : {}}
              transition={{ duration: 0.6, delay: 0.4 }}
              className="max-w-xl mx-auto"
            >
              <div className="relative">
                <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                <input
                  type="text"
                  placeholder={t('searchPlaceholder')}
                  value={searchQuery}
                  onChange={e => setSearchQuery(e.target.value)}
                  className="w-full pl-12 pr-4 py-4 rounded-xl bg-white text-gray-900 placeholder-gray-400 focus:ring-2 focus:ring-brand-turquoise focus:outline-none"
                />
              </div>
            </motion.div>
          </motion.div>
        </div>

        <div className="absolute bottom-0 left-0 right-0">
          <svg className="w-full h-16" viewBox="0 0 1440 60" preserveAspectRatio="none">
            <path
              d="M0,30 C240,50 480,10 720,30 C960,50 1200,10 1440,30 L1440,60 L0,60 Z"
              fill="white"
            />
          </svg>
        </div>
      </section>

      {/* Categories */}
      <section ref={categoriesRef} className="py-8 border-b border-gray-200">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={isCategoriesInView ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: 0.6 }}
          className="max-w-7xl mx-auto px-6 lg:px-8"
        >
          <div className="flex flex-wrap items-center justify-center gap-4">
            {CATEGORIES.map(category => {
              const IconComponent = category.icon;
              const isActive = selectedCategory === category.key;
              return (
                <button
                  key={category.key}
                  onClick={() => setSelectedCategory(category.key)}
                  className={`flex items-center space-x-2 px-4 py-2 rounded-full transition-all ${
                    isActive
                      ? 'bg-brand-turquoise text-white'
                      : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                  }`}
                >
                  <IconComponent className="w-4 h-4" />
                  <span className="font-medium">{t(`categories.${category.key}`)}</span>
                </button>
              );
            })}
          </div>
        </motion.div>
      </section>

      {/* Featured Article */}
      {!loading && featuredPost && (
        <section className="py-16">
          <div className="max-w-7xl mx-auto px-6 lg:px-8">
            <motion.div
              initial={{ opacity: 0, y: 30 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true }}
              transition={{ duration: 0.8 }}
            >
              <Link href={`/blog/${featuredPost.slug}`}>
                <div className="relative bg-gradient-to-br from-brand-navy to-brand-navy/90 rounded-3xl overflow-hidden group cursor-pointer">
                  <div className="absolute inset-0 bg-gradient-to-r from-brand-navy via-brand-navy/80 to-transparent z-10" />
                  {featuredPost.coverImageUrl ? (
                    <div
                      className="absolute right-0 top-0 bottom-0 w-1/2 bg-cover bg-center"
                      style={{ backgroundImage: `url(${resolveUrl(featuredPost.coverImageUrl)})` }}
                    />
                  ) : (
                    <div className="absolute right-0 top-0 bottom-0 w-1/2 bg-brand-turquoise/20 flex items-center justify-center">
                      <Anchor className="w-48 h-48 text-white/10" />
                    </div>
                  )}

                  <div className="relative z-20 p-8 lg:p-12">
                    <div className="max-w-2xl">
                      <div className="flex items-center space-x-2 mb-4">
                        <span className="px-3 py-1 bg-brand-turquoise text-white text-sm font-medium rounded-full">
                          {t('featuredBadge')}
                        </span>
                        <span className="px-3 py-1 bg-white/20 text-white text-sm font-medium rounded-full">
                          {t(`categories.${featuredPost.category}`)}
                        </span>
                      </div>

                      <h2 className="text-3xl lg:text-4xl font-bold text-white mb-4 group-hover:text-brand-turquoise transition-colors">
                        {featuredPost.title}
                      </h2>

                      <p className="text-lg text-white/80 mb-6">{featuredPost.excerpt}</p>

                      <div className="flex items-center space-x-6 text-white/60 text-sm">
                        <div className="flex items-center space-x-2">
                          <User className="w-4 h-4" />
                          <span>{featuredPost.authorName}</span>
                        </div>
                        {featuredPost.publishedAt && (
                          <div className="flex items-center space-x-2">
                            <Calendar className="w-4 h-4" />
                            <span>{formatDate(featuredPost.publishedAt)}</span>
                          </div>
                        )}
                      </div>

                      <div className="flex items-center space-x-2 mt-6 text-brand-turquoise font-medium opacity-0 group-hover:opacity-100 transition-opacity">
                        <span>{t('readArticle')}</span>
                        <ArrowRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
                      </div>
                    </div>
                  </div>
                </div>
              </Link>
            </motion.div>
          </div>
        </section>
      )}

      {/* Articles Grid */}
      <section ref={articlesRef} className="py-16 bg-gray-50">
        <div className="max-w-7xl mx-auto px-6 lg:px-8">
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            animate={isArticlesInView ? { opacity: 1, y: 0 } : {}}
            transition={{ duration: 0.8 }}
            className="flex items-center justify-between mb-12"
          >
            <h2 className="text-3xl font-bold text-brand-navy">{t('allTitle')}</h2>
            <span className="text-gray-500">{t('articlesCount', { count: posts.length })}</span>
          </motion.div>

          {loading ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
              {[1, 2, 3].map(i => (
                <div
                  key={i}
                  className="bg-white rounded-2xl shadow-lg overflow-hidden animate-pulse"
                >
                  <div className="aspect-video bg-gray-200" />
                  <div className="p-6 space-y-3">
                    <div className="h-4 bg-gray-200 rounded w-3/4" />
                    <div className="h-3 bg-gray-200 rounded" />
                    <div className="h-3 bg-gray-200 rounded w-5/6" />
                  </div>
                </div>
              ))}
            </div>
          ) : posts.length === 0 ? (
            <div className="text-center py-12">
              <Search className="w-16 h-16 text-gray-300 mx-auto mb-4" />
              <h3 className="text-xl font-medium text-gray-600">{t('noResults.title')}</h3>
              <p className="text-gray-500">{t('noResults.body')}</p>
            </div>
          ) : (
            <motion.div
              variants={containerVariants}
              initial="hidden"
              animate={isArticlesInView ? 'visible' : 'hidden'}
              className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8"
            >
              {posts.map(post => (
                <motion.div key={post.id} variants={itemVariants}>
                  <Link href={`/blog/${post.slug}`}>
                    <div className="bg-white rounded-2xl shadow-lg overflow-hidden group hover:shadow-xl transition-all h-full flex flex-col">
                      <div className="aspect-video bg-gradient-to-br from-brand-navy/10 to-brand-turquoise/10 flex items-center justify-center relative overflow-hidden">
                        {post.coverImageUrl ? (
                          <img
                            src={resolveUrl(post.coverImageUrl)}
                            alt={post.title}
                            className="w-full h-full object-cover"
                          />
                        ) : (
                          <Ship className="w-16 h-16 text-brand-navy/20" />
                        )}
                        <div className="absolute top-4 left-4">
                          <span className="px-3 py-1 bg-white/90 text-brand-navy text-xs font-medium rounded-full">
                            {t(`categories.${post.category}`)}
                          </span>
                        </div>
                      </div>

                      <div className="p-6 flex-1 flex flex-col">
                        <h3 className="text-xl font-bold text-brand-navy mb-3 group-hover:text-brand-turquoise transition-colors line-clamp-2">
                          {post.title}
                        </h3>

                        <p className="text-gray-600 mb-4 line-clamp-2 flex-1">{post.excerpt}</p>

                        <div className="flex flex-wrap gap-2 mb-4">
                          {post.tags.map(tag => (
                            <span
                              key={tag}
                              className="px-2 py-1 bg-gray-100 text-gray-600 text-xs rounded-full"
                            >
                              {tag}
                            </span>
                          ))}
                        </div>

                        <div className="flex items-center justify-between text-sm text-gray-500 pt-4 border-t border-gray-100">
                          <div className="flex items-center space-x-2">
                            <div className="w-8 h-8 bg-brand-turquoise/10 rounded-full flex items-center justify-center">
                              <User className="w-4 h-4 text-brand-turquoise" />
                            </div>
                            <span>{post.authorName}</span>
                          </div>
                          {post.publishedAt && (
                            <div className="flex items-center space-x-1">
                              <Clock className="w-4 h-4" />
                              <span>{formatDate(post.publishedAt)}</span>
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  </Link>
                </motion.div>
              ))}
            </motion.div>
          )}
        </div>
      </section>

      {/* Newsletter Section */}
      <section className="py-20 bg-gradient-to-br from-brand-navy to-brand-navy/95">
        <div className="max-w-4xl mx-auto px-6 lg:px-8 text-center">
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.8 }}
          >
            <h2 className="text-4xl font-bold text-white mb-6">{t('newsletter.title')}</h2>
            <p className="text-xl text-white/80 mb-10">{t('newsletter.body')}</p>
            <form className="flex flex-col sm:flex-row items-center justify-center space-y-4 sm:space-y-0 sm:space-x-4">
              <input
                type="email"
                placeholder={t('newsletter.emailPlaceholder')}
                className="w-full sm:w-96 px-6 py-4 rounded-lg bg-white text-gray-900 placeholder-gray-400 focus:ring-2 focus:ring-brand-turquoise focus:outline-none"
              />
              <button
                type="submit"
                className="w-full sm:w-auto px-8 py-4 bg-brand-turquoise text-white rounded-lg hover:bg-brand-turquoise/90 transition-all font-semibold flex items-center justify-center space-x-2"
              >
                <span>{t('newsletter.subscribe')}</span>
                <ArrowRight className="w-5 h-5" />
              </button>
            </form>
            <p className="text-white/50 text-sm mt-4">{t('newsletter.disclaimer')}</p>
          </motion.div>
        </div>
      </section>

      <LandingFooter />
    </div>
  );
}
