"use client";

import { useState, useEffect, useMemo } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { format } from "date-fns";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import Head from "next/head";
import Link from "next/link";

interface Message {
  id: string;
  date: string;
  content: string;
  timestamp: number;
  tags?: string[];
}

export default function BlogPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const selectedTag = searchParams.get("tag");
  
  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");

  useEffect(() => {
    fetchMessages();
  }, []);

  async function fetchMessages() {
    try {
      const res = await fetch("/api/messages");
      const data = await res.json();
      setMessages(data);
    } catch (err) {
      console.error("Failed to fetch:", err);
    } finally {
      setLoading(false);
    }
  }

  // Get all unique tags
  const allTags = useMemo(() => {
    const tags = new Set<string>();
    messages.forEach((m) => m.tags?.forEach((t) => tags.add(t)));
    return Array.from(tags).sort();
  }, [messages]);

  // Filter messages
  const filteredMessages = useMemo(() => {
    let filtered = messages;
    
    if (selectedTag) {
      filtered = filtered.filter((m) => m.tags?.includes(selectedTag));
    }
    
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(
        (m) =>
          m.content.toLowerCase().includes(query) ||
          m.tags?.some((t) => t.toLowerCase().includes(query))
      );
    }
    
    return filtered.sort((a, b) => b.timestamp - a.timestamp);
  }, [messages, selectedTag, searchQuery]);

  // Get featured post (most recent)
  const featuredPost = filteredMessages[0];
  const regularPosts = filteredMessages.slice(1);

  // Parse title from content
  function getTitle(content: string): string {
    const lines = content.split("\n");
    const titleLine = lines.find((l) => l.startsWith("# ") || l.startsWith("## "));
    return titleLine?.replace(/#{1,2}\s/, "") || "Daily Update";
  }

  // Get excerpt
  function getExcerpt(content: string, maxLength: number = 150): string {
    const plainText = content
      .replace(/#{1,6}\s/g, "")
      .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
      .replace(/\*/g, "")
      .replace(/\n/g, " ");
    if (plainText.length <= maxLength) return plainText;
    return plainText.substring(0, maxLength).trim() + "...";
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-white flex items-center justify-center">
        <div className="w-8 h-8 border-2 border-blue-600 border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  return (
    <>
      <Head>
        <title>Daily Digest | OpenClaw Blog</title>
        <meta name="description" content="AI-powered daily digests on iOS, AI coding assistants, and indie hacking" />
      </Head>

      <div className="min-h-screen bg-white">
        {/* Header */}
        <header className="border-b border-gray-200 sticky top-0 bg-white/95 backdrop-blur z-50">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex items-center justify-between h-16">
              <Link href="/" className="flex items-center gap-2">
                <div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center text-white font-bold">
                  📓
                </div>
                <span className="font-bold text-xl text-gray-900">Daily Digest</span>
              </Link>
              
              <nav className="hidden md:flex items-center gap-6">
                <Link href="https://gantt-board.vercel.app" className="text-sm text-gray-600 hover:text-gray-900">
                  Tasks
                </Link>
                <Link href="https://mission-control-rho-pink.vercel.app" className="text-sm text-gray-600 hover:text-gray-900">
                  Mission Control
                </Link>
              </nav>
            </div>
          </div>
        </header>

        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
            {/* Main Content */}
            <div className="lg:col-span-8">
              {/* Page Title */}
              <div className="mb-8">
                <h1 className="text-3xl font-bold text-gray-900 mb-2">
                  {selectedTag ? `Posts tagged "${selectedTag}"` : "Latest Posts"}
                </h1>
                <p className="text-gray-600">
                  {filteredMessages.length} post{filteredMessages.length !== 1 ? "s" : ""}
                  {selectedTag && (
                    <button
                      onClick={() => router.push("/")}
                      className="ml-4 text-blue-600 hover:text-blue-800 text-sm"
                    >
                      Clear filter →
                    </button>
                  )}
                </p>
              </div>

              {/* Featured Post */}
              {featuredPost && !selectedTag && !searchQuery && (
                <article className="mb-10">
                  <Link href={`/?post=${featuredPost.id}`} className="group block">
                    <div className="relative bg-gray-50 rounded-2xl overflow-hidden border border-gray-200 hover:border-blue-300 transition-colors">
                      <div className="p-6 md:p-8">
                        {featuredPost.tags && featuredPost.tags.length > 0 && (
                          <div className="flex flex-wrap gap-2 mb-4">
                            {featuredPost.tags.slice(0, 3).map((tag) => (
                              <span
                                key={tag}
                                className="px-2.5 py-0.5 rounded-full bg-blue-100 text-blue-700 text-xs font-medium"
                              >
                                {tag}
                              </span>
                            ))}
                          </div>
                        )}
                        <span className="text-sm text-blue-600 font-medium mb-2 block">
                          Featured Post
                        </span>
                        <h2 className="text-2xl md:text-3xl font-bold text-gray-900 mb-3 group-hover:text-blue-600 transition-colors">
                          {getTitle(featuredPost.content)}
                        </h2>
                        <p className="text-gray-600 mb-4 line-clamp-3">
                          {getExcerpt(featuredPost.content, 200)}
                        </p>
                        <div className="flex items-center gap-4 text-sm text-gray-500">
                          <span>{format(new Date(featuredPost.date), "MMMM d, yyyy")}</span>
                          <span>·</span>
                          <span>5 min read</span>
                        </div>
                      </div>
                    </div>
                  </Link>
                </article>
              )}

              {/* Post List */}
              <div className="space-y-6">
                {regularPosts.map((post) => (
                  <article
                    key={post.id}
                    className="flex gap-4 md:gap-6 p-4 rounded-xl hover:bg-gray-50 transition-colors border border-transparent hover:border-gray-200"
                  >
                    {/* Date Column */}
                    <div className="hidden sm:block text-center min-w-[60px]">
                      <div className="text-2xl font-bold text-gray-900">
                        {format(new Date(post.date), "d")}
                      </div>
                      <div className="text-xs text-gray-500 uppercase">
                        {format(new Date(post.date), "MMM")}
                      </div>
                    </div>

                    {/* Content */}
                    <div className="flex-1 min-w-0">
                      {post.tags && post.tags.length > 0 && (
                        <div className="flex flex-wrap gap-2 mb-2">
                          {post.tags.slice(0, 2).map((tag) => (
                            <button
                              key={tag}
                              onClick={() => router.push(`/?tag=${tag}`)}
                              className="text-xs text-blue-600 hover:text-blue-800 font-medium"
                            >
                              #{tag}
                            </button>
                          ))}
                        </div>
                      )}
                      
                      <h3 className="text-lg md:text-xl font-semibold text-gray-900 mb-2 hover:text-blue-600 cursor-pointer">
                        {getTitle(post.content)}
                      </h3>
                      
                      <p className="text-gray-600 text-sm line-clamp-2 mb-3">
                        {getExcerpt(post.content)}
                      </p>
                      
                      <div className="flex items-center gap-3 text-xs text-gray-500">
                        <span>{format(new Date(post.date), "MMMM d, yyyy")}</span>
                        <span>·</span>
                        <span>3 min read</span>
                      </div>
                    </div>
                  </article>
                ))}
              </div>

              {filteredMessages.length === 0 && (
                <div className="text-center py-16">
                  <p className="text-gray-500">No posts found.</p>
                  {(selectedTag || searchQuery) && (
                    <button
                      onClick={() => {
                        router.push("/");
                        setSearchQuery("");
                      }}
                      className="mt-2 text-blue-600 hover:text-blue-800"
                    >
                      Clear filters
                    </button>
                  )}
                </div>
              )}
            </div>

            {/* Sidebar */}
            <div className="lg:col-span-4 space-y-6">
              {/* Search */}
              <div className="bg-gray-50 rounded-xl p-4 border border-gray-200">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Search
                </label>
                <input
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder="Search posts..."
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              {/* Tags */}
              <div className="bg-gray-50 rounded-xl p-4 border border-gray-200">
                <h3 className="font-semibold text-gray-900 mb-3">Tags</h3>
                <div className="flex flex-wrap gap-2">
                  {allTags.map((tag) => (
                    <button
                      key={tag}
                      onClick={() =>
                        router.push(selectedTag === tag ? "/" : `/?tag=${tag}`)
                      }
                      className={`px-3 py-1 rounded-full text-sm font-medium transition-colors ${
                        selectedTag === tag
                          ? "bg-blue-600 text-white"
                          : "bg-white text-gray-700 border border-gray-300 hover:border-blue-400"
                      }`}
                    >
                      {tag}
                    </button>
                  ))}
                </div>
              </div>

              {/* About */}
              <div className="bg-gray-50 rounded-xl p-4 border border-gray-200">
                <h3 className="font-semibold text-gray-900 mb-2">About</h3>
                <p className="text-sm text-gray-600">
                  Daily curated digests covering AI coding assistants, iOS development, 
                  OpenClaw updates, and digital entrepreneurship.
                </p>
              </div>

              {/* Stats */}
              <div className="bg-gray-50 rounded-xl p-4 border border-gray-200">
                <h3 className="font-semibold text-gray-900 mb-3">Stats</h3>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-gray-600">Total posts</span>
                    <span className="font-medium">{messages.length}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600">Tags</span>
                    <span className="font-medium">{allTags.length}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Footer */}
        <footer className="border-t border-gray-200 mt-16">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
            <p className="text-center text-gray-500 text-sm">
              © {new Date().getFullYear()} OpenClaw Daily Digest
            </p>
          </div>
        </footer>
      </div>
    </>
  );
}
