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

interface BlogPostSummary {
  id: string;
  title: string;
  slug: string;
  excerpt: string | null;
  cover_image: string | null;
  category: string | null;
  author: string;
  published_at: string | null;
}

const fallbackPosts: BlogPostSummary[] = [
  {
    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. Here’s how to deploy them safely.',
    cover_image: 'https://images.pexels.com/photos/8386440/pexels-photo-8386440.jpeg?auto=compress&cs=tinysrgb&w=800',
    category: 'AI', author: 'Meera Joshi', published_at: '2026-07-10',
  },
  {
    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. Our phased, parallel-run approach keeps the business running.',
    cover_image: 'https://images.pexels.com/photos/3823488/pexels-photo-3823488.jpeg?auto=compress&cs=tinysrgb&w=800',
    category: 'Engineering', author: 'Karan Singh', published_at: '2026-06-22',
  },
  {
    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. Here’s when they make sense.',
    cover_image: 'https://images.pexels.com/photos/5380642/pexels-photo-5380642.jpeg?auto=compress&cs=tinysrgb&w=800',
    category: 'Cloud', author: 'Arjun Nair', published_at: '2026-06-08',
  },
  {
    id: '4', title: 'Designing dashboards people actually understand', slug: 'designing-dashboards-people-understand',
    excerpt: 'Most dashboards dump data. Good dashboards tell a story. Here are the principles we use at Queneva.',
    cover_image: 'https://images.pexels.com/photos/669615/pexels-photo-669615.jpeg?auto=compress&cs=tinysrgb&w=800',
    category: 'Design', author: 'Priya Reddy', published_at: '2026-05-30',
  },
];

const categories = ['All', 'AI', 'Engineering', 'Cloud', 'Design'];

export default function Blog() {
  const [posts, setPosts] = useState<BlogPostSummary[]>(fallbackPosts);
  const [active, setActive] = useState('All');
  const [loading, setLoading] = useState(true);

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

  const filtered = active === 'All' ? posts : posts.filter((p) => p.category === active);
  const featured = filtered[0];
  const rest = filtered.slice(1);

  return (
    <div>
      <PageHero
        eyebrow="Blog"
        title={<>Ideas on <span className="gradient-text">building & scaling</span></>}
        subtitle="Practical thinking from the Queneva team on AI, engineering, design, and running a modern software studio."
        crumbs={[{ label: 'Home', to: '/' }, { label: 'Blog' }]}
      />

      {/* Filters */}
      <section className="container-wide section-padding py-6">
        <div className="flex flex-wrap justify-center gap-2">
          {categories.map((c) => (
            <button
              key={c}
              onClick={() => setActive(c)}
              className={`rounded-full px-5 py-2.5 text-sm font-medium transition-all ${
                active === c
                  ? 'bg-secondary-500 text-white shadow-glow'
                  : 'glass text-primary-600 hover:scale-105 dark:text-gray-300'
              }`}
            >
              {c}
            </button>
          ))}
        </div>
      </section>

      {/* Featured */}
      {featured && (
        <section className="container-wide section-padding py-8">
          <Reveal>
            <Link to={`/blog/${featured.slug}`}>
              <div className="group grid gap-8 overflow-hidden rounded-3xl glass p-6 lg:grid-cols-2 lg:items-center lg:p-8 card-hover">
                <div className="aspect-[16/10] overflow-hidden rounded-2xl">
                  <img
                    src={featured.cover_image || 'https://images.pexels.com/photos/669615/pexels-photo-669615.jpeg?auto=compress&cs=tinysrgb&w=800'}
                    alt={featured.title}
                    loading="lazy"
                    className="h-full w-full object-cover transition-transform duration-700 group-hover:scale-105"
                  />
                </div>
                <div>
                  <span className="rounded-full bg-secondary-500/10 px-3 py-1 text-xs font-semibold text-secondary-600 dark:text-accent-400">
                    Featured · {featured.category}
                  </span>
                  <h2 className="mt-4 text-2xl font-bold leading-snug sm:text-3xl">{featured.title}</h2>
                  <p className="mt-3 text-sm leading-relaxed text-primary-400 dark:text-gray-400">{featured.excerpt}</p>
                  <div className="mt-5 flex items-center gap-4 text-xs text-primary-400 dark:text-gray-500">
                    <span className="flex items-center gap-1.5"><User size={13} /> {featured.author}</span>
                    <span className="flex items-center gap-1.5"><Clock size={13} /> 6 min read</span>
                  </div>
                  <span className="mt-6 inline-flex items-center gap-1.5 text-sm font-semibold text-secondary-500 transition-all group-hover:gap-2.5 dark:text-accent-400">
                    Read article <ArrowRight size={15} />
                  </span>
                </div>
              </div>
            </Link>
          </Reveal>
        </section>
      )}

      {/* Grid */}
      <section className="container-wide section-padding py-8">
        <StaggerContainer className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
          {rest.map((p) => (
            <StaggerItem key={p.id}>
              <Link 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 || 'https://images.pexels.com/photos/669615/pexels-photo-669615.jpeg?auto=compress&cs=tinysrgb&w=800'}
                      alt={p.title}
                      loading="lazy"
                      className="h-full w-full object-cover transition-transform duration-700 group-hover:scale-110"
                    />
                  </div>
                  <div className="p-6">
                    <div className="flex items-center justify-between text-xs">
                      <span className="flex items-center gap-1.5 font-semibold text-secondary-600 dark:text-accent-400">
                        <Tag size={12} /> {p.category}
                      </span>
                      <span className="text-primary-400 dark:text-gray-500">
                        {p.published_at ? new Date(p.published_at).toLocaleDateString('en-US', { month: 'short', year: 'numeric' }) : ''}
                      </span>
                    </div>
                    <h3 className="mt-3 text-lg font-bold leading-snug">{p.title}</h3>
                    <p className="mt-2 text-sm leading-relaxed text-primary-400 dark:text-gray-400 line-clamp-2">{p.excerpt}</p>
                    <div className="mt-4 flex items-center gap-1.5 text-xs text-primary-400 dark:text-gray-500">
                      <User size={12} /> {p.author}
                    </div>
                  </div>
                </div>
              </Link>
            </StaggerItem>
          ))}
        </StaggerContainer>
        {!loading && filtered.length === 0 && (
          <p className="py-12 text-center text-primary-400 dark:text-gray-500">No posts in this category yet.</p>
        )}
      </section>

      <section className="container-wide section-padding py-16">
        <SectionHeading
          eyebrow="Newsletter"
          title={<>Get our best ideas <span className="gradient-text">in your inbox</span></>}
          subtitle="One thoughtful email a month. No spam, no fluff."
        />
        <Reveal className="mx-auto mt-8 max-w-md">
          <form onSubmit={(e) => e.preventDefault()} className="flex gap-3">
            <input
              type="email"
              required
              placeholder="you@company.com"
              className="flex-1 rounded-full glass px-5 py-3 text-sm outline-none focus:ring-2 focus:ring-secondary-500"
            />
            <button className="btn-primary">Subscribe</button>
          </form>
        </Reveal>
      </section>

      <CTASection />
    </div>
  );
}
