'use client';

import React, { useState, useMemo } from 'react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import {
  MessagesSquare,
  Search,
  PlusCircle,
  CheckCircle2,
  Eye,
  MessageCircle,
  Sparkles,
  X,
  Send,
  ThumbsUp,
  HelpCircle,
  Bug,
  Lightbulb,
  Server,
  Layers,
  Check,
} from 'lucide-react';
import { CommunityPost, Product, ForumCategoryType } from '@/types';
import { useAuth } from '@/context/AuthContext';

interface CommunityClientProps {
  initialPosts: CommunityPost[];
  products: Product[];
}

const FORUM_CATEGORIES: { id: ForumCategoryType; label: string; icon: any }[] = [
  { id: 'all', label: 'All Topics', icon: Layers },
  { id: 'questions', label: 'Questions', icon: HelpCircle },
  { id: 'discussions', label: 'Discussions', icon: MessagesSquare },
  { id: 'bugs', label: 'Bug Reports', icon: Bug },
  { id: 'features', label: 'Feature Requests', icon: Lightbulb },
  { id: 'modules', label: 'Module Support', icon: Server },
];

export default function CommunityClient({ initialPosts, products }: CommunityClientProps) {
  const searchParams = useSearchParams();
  const productFilter = searchParams.get('product') || 'all';
  const { user, isAdmin } = useAuth();

  const [posts, setPosts] = useState<CommunityPost[]>(initialPosts);
  const [search, setSearch] = useState('');
  const [activeCategory, setActiveCategory] = useState<ForumCategoryType>('all');
  const [selectedProduct, setSelectedProduct] = useState<string | number>(
    productFilter === 'all' ? 'all' : Number(productFilter) || productFilter
  );

  // New Post Modal State
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [newTitle, setNewTitle] = useState('');
  const [newContent, setNewContent] = useState('');
  const [newCategoryType, setNewCategoryType] = useState<CommunityPost['category_type']>('questions');
  const [newProductId, setNewProductId] = useState<string>('');
  const [newTags, setNewTags] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Upvote state
  const handleUpvote = async (e: React.MouseEvent, postId: string) => {
    e.preventDefault();
    e.stopPropagation();
    const activeUserId = user?.id || 'usr-demo';

    try {
      const res = await fetch(`/api/community/${postId}/upvote`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ user_id: activeUserId }),
      });
      const data = await res.json();
      if (data.upvotes !== undefined) {
        setPosts(
          posts.map((p) =>
            p.id === postId
              ? {
                  ...p,
                  upvotes: data.upvotes,
                  upvoters: data.userHasUpvoted
                    ? [...(p.upvoters || []), activeUserId]
                    : (p.upvoters || []).filter((u) => u !== activeUserId),
                }
              : p
          )
        );
      }
    } catch {
      // Local fallback
      setPosts(
        posts.map((p) =>
          p.id === postId
            ? { ...p, upvotes: (p.upvotes || 0) + 1 }
            : p
        )
      );
    }
  };

  // Filtered posts
  const filteredPosts = useMemo(() => {
    return posts.filter((p) => {
      if (search.trim()) {
        const q = search.toLowerCase();
        const matchesTitle = p.title.toLowerCase().includes(q);
        const matchesContent = p.content.toLowerCase().includes(q);
        if (!matchesTitle && !matchesContent) return false;
      }

      if (activeCategory !== 'all') {
        if (p.category_type !== activeCategory) return false;
      }

      if (selectedProduct !== 'all') {
        if (String(p.product_id) !== String(selectedProduct)) return false;
      }

      return true;
    });
  }, [posts, search, activeCategory, selectedProduct]);

  const handleCreatePost = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newTitle.trim() || !newContent.trim()) return;

    setIsSubmitting(true);
    const prod = products.find((p) => String(p.id) === String(newProductId));

    try {
      const payload = {
        user_id: user?.id || 'usr-demo',
        user_name: user?.name || 'Developer Community Member',
        user_avatar: user?.avatar,
        user_badge: isAdmin ? 'Admin' : 'Verified Buyer',
        category_type: newCategoryType,
        product_id: newProductId ? Number(newProductId) : undefined,
        product_title: prod?.title,
        title: newTitle.trim(),
        content: newContent.trim(),
        tags: newTags
          ? newTags.split(',').map((t) => t.trim())
          : [prod?.category_name || 'Discussion'],
      };

      const res = await fetch('/api/community', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      const data = await res.json();
      if (data.post) {
        setPosts([data.post, ...posts]);
        setIsModalOpen(false);
        setNewTitle('');
        setNewContent('');
        setNewProductId('');
        setNewTags('');
      }
    } catch {
      // Fallback
      const localPost: CommunityPost = {
        id: `post-${Date.now()}`,
        product_id: newProductId ? Number(newProductId) : undefined,
        product_title: prod?.title,
        category_type: newCategoryType,
        user_id: user?.id || 'usr-demo',
        user_name: user?.name || 'Developer Community Member',
        user_badge: 'Verified Buyer',
        title: newTitle.trim(),
        content: newContent.trim(),
        tags: ['Discussion'],
        views: 1,
        upvotes: 1,
        upvoters: [user?.id || 'usr-demo'],
        replies_count: 0,
        is_solved: false,
        created_at: new Date().toISOString(),
      };
      setPosts([localPost, ...posts]);
      setIsModalOpen(false);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="py-8 md:py-14 bg-gray-50 min-h-screen">
      <div className="container mx-auto px-4 max-w-6xl space-y-8">
        {/* Header Card */}
        <div className="bg-gradient-to-r from-gray-900 via-indigo-950 to-indigo-900 rounded-3xl p-6 sm:p-10 shadow-xl border border-indigo-800/40 text-white flex flex-col md:flex-row md:items-center justify-between gap-6 relative overflow-hidden">
          <div className="space-y-2 z-10">
            <div className="inline-flex items-center gap-1.5 text-xs font-black text-amber-400 uppercase tracking-wider bg-white/10 px-3 py-1 rounded-full">
              <Sparkles className="w-3.5 h-3.5" />
              <span>Connect, Ask Questions & Find Answers</span>
            </div>
            <h1 className="text-2xl sm:text-4xl font-black text-white">
              Product Community & Support Forum
            </h1>
            <p className="text-xs sm:text-sm text-indigo-200 max-w-2xl leading-relaxed">
              Explore solutions, report bugs, share WHMCS configuration best practices, and collaborate with verified developers.
            </p>
          </div>

          <button
            onClick={() => setIsModalOpen(true)}
            className="px-6 py-3.5 bg-indigo-500 hover:bg-indigo-600 text-white font-extrabold text-xs sm:text-sm rounded-2xl shadow-lg shadow-indigo-600/30 hover:shadow-xl transition-all transform active:scale-95 flex items-center justify-center gap-2 shrink-0 z-10"
          >
            <PlusCircle className="w-4 h-4" />
            <span>Start a Discussion</span>
          </button>
        </div>

        {/* Category Navigation Pills */}
        <div className="flex items-center gap-2 overflow-x-auto pb-2 scrollbar-none">
          {FORUM_CATEGORIES.map((cat) => {
            const Icon = cat.icon;
            const isActive = activeCategory === cat.id;
            return (
              <button
                key={cat.id}
                onClick={() => setActiveCategory(cat.id)}
                className={`px-4 py-2.5 rounded-2xl text-xs font-bold transition flex items-center gap-2 shrink-0 ${
                  isActive
                    ? 'bg-indigo-600 text-white shadow-md shadow-indigo-600/20'
                    : 'bg-white text-gray-700 hover:bg-gray-100 border border-gray-200/60'
                }`}
              >
                <Icon className="w-3.5 h-3.5" />
                <span>{cat.label}</span>
              </button>
            );
          })}
        </div>

        {/* Filters Toolbar */}
        <div className="bg-white rounded-2xl p-4 sm:p-5 shadow-sm border border-gray-100 flex flex-col sm:flex-row items-center justify-between gap-4">
          <div className="relative w-full sm:w-80">
            <input
              type="text"
              placeholder="Search discussions, bugs, WHMCS topics..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full text-xs py-2.5 pl-9 pr-4 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-600"
            />
            <Search className="w-4 h-4 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
          </div>

          {/* Product Filter */}
          <div className="w-full sm:w-auto flex items-center gap-2">
            <span className="text-xs font-medium text-gray-400 shrink-0">Product Filter:</span>
            <select
              value={selectedProduct}
              onChange={(e) => setSelectedProduct(e.target.value)}
              className="w-full sm:w-auto text-xs font-semibold bg-gray-50 border border-gray-200 rounded-xl px-3 py-2 focus:outline-none focus:border-indigo-600 text-gray-800"
            >
              <option value="all">All Products & General</option>
              {products.map((p) => (
                <option key={p.id} value={p.id}>
                  {p.title}
                </option>
              ))}
            </select>
          </div>
        </div>

        {/* Discussions List */}
        <div className="space-y-4">
          {filteredPosts.length > 0 ? (
            filteredPosts.map((post) => {
              const hasUpvoted = post.upvoters?.includes(user?.id || 'usr-demo');

              return (
                <Link
                  key={post.id}
                  href={`/community/${post.id}`}
                  className="block bg-white rounded-3xl p-6 shadow-sm hover:shadow-md border border-gray-100 transition transform hover:-translate-y-0.5"
                >
                  <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                    <div className="space-y-2.5 flex-1">
                      {/* Badge Tags */}
                      <div className="flex flex-wrap items-center gap-2">
                        {post.is_solved && (
                          <span className="inline-flex items-center gap-1 text-[10px] font-black uppercase px-2.5 py-0.5 rounded-full bg-emerald-100 text-emerald-800">
                            <CheckCircle2 className="w-3 h-3" /> Solved
                          </span>
                        )}

                        <span className="text-[10px] font-extrabold uppercase px-2.5 py-0.5 rounded-full bg-indigo-50 text-indigo-700">
                          {post.category_type || 'question'}
                        </span>

                        {post.product_title && (
                          <span className="text-[11px] font-semibold bg-gray-100 text-gray-800 px-2.5 py-0.5 rounded-full">
                            {post.product_title}
                          </span>
                        )}

                        {post.tags?.map((t) => (
                          <span key={t} className="text-[11px] text-gray-400 font-medium">
                            #{t}
                          </span>
                        ))}
                      </div>

                      {/* Title & Preview */}
                      <h3 className="text-base sm:text-lg font-black text-gray-900 hover:text-indigo-600 transition">
                        {post.title}
                      </h3>
                      <p className="text-xs text-gray-500 line-clamp-2 leading-relaxed">
                        {post.content}
                      </p>

                      {/* Author info & Badges */}
                      <div className="flex items-center gap-3 text-xs text-gray-400 pt-1">
                        <div className="flex items-center gap-1.5 font-bold text-gray-800">
                          <span>{post.user_name}</span>
                          {post.user_badge && (
                            <span className="text-[9px] font-black uppercase px-1.5 py-0.5 bg-indigo-100 text-indigo-700 rounded-md">
                              {post.user_badge}
                            </span>
                          )}
                        </div>
                        <span>•</span>
                        <span>{new Date(post.created_at).toLocaleDateString()}</span>
                      </div>
                    </div>

                    {/* Right Metrics: Upvotes, Views, Replies */}
                    <div className="flex items-center gap-3 text-xs font-semibold text-gray-500 shrink-0 sm:border-l sm:border-gray-100 sm:pl-6">
                      <button
                        type="button"
                        onClick={(e) => handleUpvote(e, post.id)}
                        className={`flex items-center gap-1 px-3 py-1.5 rounded-xl font-bold transition ${
                          hasUpvoted
                            ? 'bg-indigo-600 text-white'
                            : 'bg-gray-50 hover:bg-indigo-50 text-gray-700 hover:text-indigo-600'
                        }`}
                        title="Upvote Discussion"
                      >
                        <ThumbsUp className="w-3.5 h-3.5" />
                        <span>{post.upvotes || 0}</span>
                      </button>

                      <div className="flex items-center gap-1 text-gray-400">
                        <Eye className="w-4 h-4" />
                        <span>{post.views || 0}</span>
                      </div>

                      <div className="flex items-center gap-1.5 px-3 py-1.5 bg-indigo-50 text-indigo-700 rounded-xl font-bold">
                        <MessageCircle className="w-4 h-4 text-indigo-600" />
                        <span>{post.replies_count || post.replies?.length || 0}</span>
                      </div>
                    </div>
                  </div>
                </Link>
              );
            })
          ) : (
            <div className="bg-white rounded-3xl p-12 text-center text-gray-500 space-y-4">
              <MessagesSquare className="w-12 h-12 text-gray-300 mx-auto" />
              <h3 className="font-bold text-gray-800">No discussions found</h3>
              <p className="text-xs text-gray-400">
                Be the first to post a topic or question about our digital products.
              </p>
              <button
                onClick={() => setIsModalOpen(true)}
                className="px-5 py-2.5 bg-indigo-600 text-white text-xs font-semibold rounded-xl"
              >
                Start Discussion
              </button>
            </div>
          )}
        </div>
      </div>

      {/* New Topic Modal */}
      {isModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div
            className="fixed inset-0 bg-black/60 backdrop-blur-sm"
            onClick={() => setIsModalOpen(false)}
          />
          <div className="relative w-full max-w-xl bg-white rounded-3xl shadow-2xl p-6 sm:p-8 space-y-5 z-10 animate-fade-in">
            <div className="flex items-center justify-between border-b border-gray-100 pb-3">
              <h3 className="text-lg font-black text-gray-900">Post a New Topic</h3>
              <button
                onClick={() => setIsModalOpen(false)}
                className="w-8 h-8 rounded-full bg-gray-100 hover:bg-gray-200 text-gray-500 flex items-center justify-center"
              >
                <X className="w-4 h-4" />
              </button>
            </div>

            <form onSubmit={handleCreatePost} className="space-y-4 text-xs">
              <div>
                <label className="block font-bold text-gray-700 mb-1">
                  Topic Title *
                </label>
                <input
                  type="text"
                  required
                  placeholder="e.g. How to configure secondary IP pool on Proxmox module?"
                  value={newTitle}
                  onChange={(e) => setNewTitle(e.target.value)}
                  className="w-full py-2.5 px-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-600"
                />
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label className="block font-bold text-gray-700 mb-1">
                    Category Type *
                  </label>
                  <select
                    value={newCategoryType}
                    onChange={(e) => setNewCategoryType(e.target.value as any)}
                    className="w-full py-2.5 px-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-600 font-semibold"
                  >
                    <option value="questions">Question / Help</option>
                    <option value="discussions">General Discussion</option>
                    <option value="bugs">Bug Report</option>
                    <option value="features">Feature Request</option>
                    <option value="modules">WHMCS & Module Support</option>
                  </select>
                </div>

                <div>
                  <label className="block font-bold text-gray-700 mb-1">
                    Related Product
                  </label>
                  <select
                    value={newProductId}
                    onChange={(e) => setNewProductId(e.target.value)}
                    className="w-full py-2.5 px-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-600 font-semibold"
                  >
                    <option value="">General Community</option>
                    {products.map((p) => (
                      <option key={p.id} value={p.id}>
                        {p.title}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              <div>
                <label className="block font-bold text-gray-700 mb-1">
                  Tags (Comma separated)
                </label>
                <input
                  type="text"
                  placeholder="WHMCS, Proxmox, Config, Setup"
                  value={newTags}
                  onChange={(e) => setNewTags(e.target.value)}
                  className="w-full py-2.5 px-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-600"
                />
              </div>

              <div>
                <label className="block font-bold text-gray-700 mb-1">
                  Details & Description *
                </label>
                <textarea
                  rows={5}
                  required
                  placeholder="Provide all server details, error logs, and environment context..."
                  value={newContent}
                  onChange={(e) => setNewContent(e.target.value)}
                  className="w-full p-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-600"
                />
              </div>

              <div className="flex justify-end gap-3 pt-2">
                <button
                  type="button"
                  onClick={() => setIsModalOpen(false)}
                  className="px-5 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 font-semibold rounded-xl"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="px-6 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-xl shadow-md transition flex items-center gap-1.5"
                >
                  <Send className="w-3.5 h-3.5" />
                  <span>{isSubmitting ? 'Publishing...' : 'Publish Topic'}</span>
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
