'use client';

import { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import { Link } from '@/i18n/navigation';
import { motion } from 'framer-motion';
import { ArrowLeft, Calendar, User, Tag, Anchor } from 'lucide-react';
import { LandingHeader, LandingFooter } from '@/components/layout';
import { getBlogPost, type BlogPost } 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}`;
}

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

const CATEGORY_LABELS: Record<string, string> = {
  industry: 'Industrie',
  technology: 'Technologie',
  guides: 'Guides',
  news: 'Actualités',
};

export default function BlogPostPage() {
  const params = useParams();
  const slug = params?.slug as string;

  const [post, setPost] = useState<BlogPost | null>(null);
  const [loading, setLoading] = useState(true);
  const [notFound, setNotFound] = useState(false);

  useEffect(() => {
    if (!slug) return;

    let cancelled = false;

    getBlogPost(slug)
      .then(p => {
        if (!cancelled) setPost(p);
      })
      .catch(() => {
        if (!cancelled) setNotFound(true);
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });

    return () => {
      cancelled = true;
    };
  }, [slug]);

  if (loading) {
    return (
      <div className="min-h-screen bg-white">
        <LandingHeader />
        <div className="max-w-4xl mx-auto px-6 pt-32 pb-20">
          <div className="animate-pulse space-y-4">
            <div className="h-8 bg-gray-200 rounded w-3/4" />
            <div className="h-4 bg-gray-200 rounded w-1/2" />
            <div className="h-64 bg-gray-200 rounded-xl mt-8" />
          </div>
        </div>
        <LandingFooter />
      </div>
    );
  }

  if (notFound || !post) {
    return (
      <div className="min-h-screen bg-white">
        <LandingHeader />
        <div className="max-w-4xl mx-auto px-6 pt-32 pb-20 text-center">
          <Anchor className="w-24 h-24 text-gray-200 mx-auto mb-6" />
          <h1 className="text-3xl font-bold text-brand-navy mb-4">Article introuvable</h1>
          <p className="text-gray-600 mb-8">
            Cet article n&apos;existe pas ou n&apos;est pas encore publié.
          </p>
          <Link href="/blog">
            <span className="inline-flex items-center space-x-2 px-6 py-3 bg-brand-turquoise text-white rounded-lg hover:bg-brand-turquoise/90 transition-all font-semibold">
              <ArrowLeft className="w-4 h-4" />
              <span>Retour au blog</span>
            </span>
          </Link>
        </div>
        <LandingFooter />
      </div>
    );
  }

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

      {/* Hero */}
      <section className="relative pt-32 pb-16 bg-gradient-to-br from-brand-navy to-brand-navy/95">
        <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>

        <div className="relative z-10 max-w-4xl mx-auto px-6 lg:px-8">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6 }}
          >
            <Link href="/blog">
              <span className="inline-flex items-center space-x-2 text-white/60 hover:text-white transition-colors mb-8 text-sm">
                <ArrowLeft className="w-4 h-4" />
                <span>Retour au blog</span>
              </span>
            </Link>

            <div className="flex items-center space-x-3 mb-6">
              <span className="px-3 py-1 bg-brand-turquoise text-white text-sm font-medium rounded-full">
                {CATEGORY_LABELS[post.category] ?? post.category}
              </span>
              {post.isFeatured && (
                <span className="px-3 py-1 bg-white/20 text-white text-sm font-medium rounded-full">
                  À la une
                </span>
              )}
            </div>

            <h1 className="text-3xl lg:text-5xl font-bold text-white mb-6 leading-tight">
              {post.title}
            </h1>

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

            <div className="flex flex-wrap items-center gap-6 text-white/60 text-sm">
              <div className="flex items-center space-x-2">
                <User className="w-4 h-4" />
                <span>{post.authorName}</span>
              </div>
              {post.publishedAt && (
                <div className="flex items-center space-x-2">
                  <Calendar className="w-4 h-4" />
                  <span>{formatDate(post.publishedAt)}</span>
                </div>
              )}
              {post.tags.length > 0 && (
                <div className="flex items-center space-x-2">
                  <Tag className="w-4 h-4" />
                  <span>{post.tags.join(', ')}</span>
                </div>
              )}
            </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>

      {/* Cover Image */}
      {post.coverImageUrl && (
        <div className="max-w-4xl mx-auto px-6 lg:px-8 -mt-8 relative z-10">
          <motion.img
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.2 }}
            src={resolveUrl(post.coverImageUrl)}
            alt={post.title}
            className="w-full h-64 lg:h-96 object-cover rounded-2xl shadow-2xl"
          />
        </div>
      )}

      {/* Content */}
      <section className="py-16">
        <div className="max-w-4xl mx-auto px-6 lg:px-8">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.3 }}
            className="prose prose-lg prose-brand max-w-none"
            dangerouslySetInnerHTML={{
              __html: post.content.replace(
                /src="(\/api\/v1\/blog\/images\/[^"]+)"/g,
                `src="${API_BASE_URL}$1"`
              ),
            }}
          />

          {/* Tags */}
          {post.tags.length > 0 && (
            <div className="flex flex-wrap gap-2 mt-12 pt-8 border-t border-gray-200">
              {post.tags.map(tag => (
                <span
                  key={tag}
                  className="px-3 py-1 bg-gray-100 text-gray-600 text-sm rounded-full"
                >
                  #{tag}
                </span>
              ))}
            </div>
          )}

          {/* Back link */}
          <div className="mt-12">
            <Link href="/blog">
              <span className="inline-flex items-center space-x-2 px-6 py-3 bg-brand-navy text-white rounded-lg hover:bg-brand-navy/90 transition-all font-semibold">
                <ArrowLeft className="w-4 h-4" />
                <span>Retour au blog</span>
              </span>
            </Link>
          </div>
        </div>
      </section>

      <LandingFooter />
    </div>
  );
}
