import { useEffect, useState } from 'react';
import { useParams, Link, Navigate } from 'react-router-dom';
import { ArrowLeft, Clock, User, Tag, ArrowRight, Share2 } from 'lucide-react';
import PageHero from '@/components/PageHero';
import CTASection from '@/components/CTASection';
import { Reveal, SectionHeading } from '@/components/ui/Animation';
import { supabase } from '@/lib/supabase';

interface FullPost {
  id: string;
  title: string;
  slug: string;
  excerpt: string | null;
  content: string;
  cover_image: string | null;
  category: string | null;
  tags: string[];
  author: string;
  published_at: string | null;
}

const samplePosts: Record<string, FullPost> = {
  'ai-agents-b2b-sales-2026': {
    id: '1', title: 'How AI agents are reshaping B2B sales in 2026', slug: 'ai-agents-b2b-sales-2026',
    excerpt: 'Autonomous agents now qualify leads, draft outreach, and update CRMs around the clock.',
    cover_image: 'https://images.pexels.com/photos/8386440/pexels-photo-8386440.jpeg?auto=compress&cs=tinysrgb&w=1200',
    category: 'AI', tags: ['AI', 'Sales', 'Automation'], author: 'Meera Joshi', published_at: '2026-07-10',
    content: `AI agents have crossed from demo to production. In 2026, the most efficient B2B sales teams aren't hiring more SDRs — they're deploying agents that work around the clock.

## What changed

Three things made agents production-ready: reliable tool use, grounded retrieval, and human-in-the-loop guardrails. Agents can now safely call your CRM, send email, and update records — with a human approving anything irreversible.

## A typical workflow

1. A lead submits your contact form.
2. An agent enriches the lead with firmographic data.
3. The agent scores the lead and drafts a personalized email.
4. A human reviews and sends.

This compresses what used to take a day into minutes.

## Getting started

Start with one workflow, not a platform. Pick a painful, repetitive task, build a prototype, and measure the time saved. Scale from there.`,
  },
  'erp-migration-without-downtime': {
    id: '2', title: 'A practical guide to ERP migration without downtime', slug: 'erp-migration-without-downtime',
    excerpt: 'Migrating an ERP doesn’t have to mean a weekend of fear.',
    cover_image: 'https://images.pexels.com/photos/3823488/pexels-photo-3823488.jpeg?auto=compress&cs=tinysrgb&w=1200',
    category: 'Engineering', tags: ['ERP', 'Migration'], author: 'Karan Singh', published_at: '2026-06-22',
    content: `ERP migrations are notoriously risky. But with a phased, parallel-run approach, you can move to a new system without taking the business offline.

## The parallel-run method

Run both systems simultaneously for a defined period. Enter data in both, reconcile daily, and only cut over when the new system has proven accurate for weeks.

## Phase 1: Read-only mirror

Replicate data into the new system as read-only. Let users explore without risk.

## Phase 2: Dual entry

Key modules run in both systems. Reconciliation catches discrepancies early.

## Phase 3: Cutover

Once confidence is high, flip the old system to read-only and make the new one primary.`,
  },
  'startups-ship-on-the-edge': {
    id: '3', title: 'Why your startup should ship on the edge', slug: 'startups-ship-on-the-edge',
    excerpt: 'Edge functions cut latency, simplify infra, and scale globally from day one.',
    cover_image: 'https://images.pexels.com/photos/5380642/pexels-photo-5380642.jpeg?auto=compress&cs=tinysrgb&w=1200',
    category: 'Cloud', tags: ['Edge', 'Cloud'], author: 'Arjun Nair', published_at: '2026-06-08',
    content: `For most startups, edge functions are the right default. They cut latency, simplify infrastructure, and scale globally without you provisioning a single server.

## Why edge

Your code runs close to the user. A request from Mumbai hits a Mumbai node, not a Virginia one. That's 200ms saved per round trip.

## When NOT to use edge

Long-running tasks, heavy CPU work, and stateful connections still belong on a server. Edge is for fast, stateless work — APIs, auth, webhooks, redirects.`,
  },
};

export default function BlogPost() {
  const { slug } = useParams();
  const [post, setPost] = useState<FullPost | null>(samplePosts[slug || ''] || null);
  const [loading, setLoading] = useState(!samplePosts[slug || '']);

  useEffect(() => {
    if (!slug) return;
    (async () => {
      try {
        const { data, error } = await supabase
          .from('blog_posts')
          .select('id, title, slug, excerpt, content, cover_image, category, tags, author, published_at')
          .eq('slug', slug)
          .eq('status', 'published')
          .maybeSingle();
        if (!error && data) {
          setPost(data);
        }
      } catch {
        // keep fallback
      } finally {
        setLoading(false);
      }
    })();
  }, [slug]);

  if (loading) {
    return (
      <div className="container-wide section-padding py-32 text-center">
        <p className="text-primary-400 dark:text-gray-500">Loading article…</p>
      </div>
    );
  }
  if (!post) return <Navigate to="/blog" replace />;

  const paragraphs = post.content.split('\n\n');

  return (
    <article>
      <PageHero
        eyebrow={post.category || 'Article'}
        title={post.title}
        crumbs={[{ label: 'Home', to: '/' }, { label: 'Blog', to: '/blog' }, { label: post.title }]}
      >
        <div className="flex flex-wrap items-center gap-4 text-sm text-primary-400 dark:text-gray-500">
          <span className="flex items-center gap-1.5"><User size={15} /> {post.author}</span>
          <span className="flex items-center gap-1.5"><Clock size={15} /> 6 min read</span>
          {post.published_at && (
            <span>{new Date(post.published_at).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })}</span>
          )}
        </div>
      </PageHero>

      <section className="container-wide section-padding py-8">
        <div className="mx-auto max-w-3xl">
          <Reveal>
            <img
              src={post.cover_image || 'https://images.pexels.com/photos/669615/pexels-photo-669615.jpeg?auto=compress&cs=tinysrgb&w=1200'}
              alt={post.title}
              className="aspect-[16/9] w-full rounded-3xl object-cover shadow-soft-lg dark:shadow-soft-dark-lg"
            />
          </Reveal>

          <div className="mt-10 space-y-6">
            {paragraphs.map((para, i) => {
              if (para.startsWith('## ')) {
                return (
                  <Reveal key={i} delay={i * 0.03}>
                    <h2 className="mt-10 text-2xl font-bold">{para.replace('## ', '')}</h2>
                  </Reveal>
                );
              }
              if (para.match(/^\d+\.\s/)) {
                const items = para.split('\n').filter((l) => l.trim());
                return (
                  <Reveal key={i} delay={i * 0.03}>
                    <ol className="ml-5 list-decimal space-y-2 text-primary-600 dark:text-gray-300">
                      {items.map((it, j) => <li key={j}>{it.replace(/^\d+\.\s/, '')}</li>)}
                    </ol>
                  </Reveal>
                );
              }
              return (
                <Reveal key={i} delay={i * 0.03}>
                  <p className="text-lg leading-relaxed text-primary-600 dark:text-gray-300">{para}</p>
                </Reveal>
              );
            })}
          </div>

          {/* Tags */}
          <div className="mt-12 flex flex-wrap items-center gap-3">
            {post.tags.map((t) => (
              <span key={t} className="flex items-center gap-1.5 rounded-full glass px-3 py-1.5 text-xs font-medium text-primary-500 dark:text-gray-400">
                <Tag size={12} /> {t}
              </span>
            ))}
            <button className="ml-auto flex items-center gap-1.5 text-sm font-medium text-secondary-500 hover:underline dark:text-accent-400">
              <Share2 size={15} /> Share
            </button>
          </div>

          {/* Back */}
          <Link to="/blog" className="mt-10 inline-flex items-center gap-2 text-sm font-semibold text-secondary-500 dark:text-accent-400">
            <ArrowLeft size={16} /> All articles
          </Link>
        </div>
      </section>

      {/* Related */}
      <section className="container-wide section-padding py-16">
        <SectionHeading eyebrow="Keep reading" title={<>Related <span className="gradient-text">articles</span></>} />
        <div className="mt-10 grid gap-6 md:grid-cols-3">
          {Object.values(samplePosts).filter((p) => p.slug !== slug).slice(0, 3).map((p) => (
            <Link key={p.slug} to={`/blog/${p.slug}`}>
              <div className="group glass h-full overflow-hidden rounded-3xl card-hover">
                <div className="aspect-[16/10] overflow-hidden">
                  <img src={p.cover_image!} alt={p.title} loading="lazy" className="h-full w-full object-cover transition-transform duration-700 group-hover:scale-110" />
                </div>
                <div className="p-5">
                  <span className="text-xs font-semibold text-secondary-600 dark:text-accent-400">{p.category}</span>
                  <h3 className="mt-2 font-bold leading-snug">{p.title}</h3>
                  <span className="mt-3 inline-flex items-center gap-1.5 text-sm font-semibold text-secondary-500 dark:text-accent-400">
                    Read <ArrowRight size={14} />
                  </span>
                </div>
              </div>
            </Link>
          ))}
        </div>
      </section>

      <CTASection />
    </article>
  );
}
