'use client';

import { useState } from 'react';
import Image from 'next/image';
import { motion } from 'framer-motion';
import {
  MessageCircle,
  Heart,
  Search,
  Plus,
  ChevronRight,
  AlertTriangle,
} from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useForumPosts, useForumStats } from '@/hooks/useForum';
import { useUser } from '@/store/auth.store';
import { ForumCategory } from '@/types';

export default function ForumPage() {
  const router = useRouter();
  const user = useUser();
  const [activeFilter, setActiveFilter] = useState<'all' | ForumCategory>(
    'all'
  );
  const [searchQuery, setSearchQuery] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');

  // Debounce search
  const handleSearch = (value: string) => {
    setSearchQuery(value);
    clearTimeout(
      (globalThis as Record<string, unknown>).__forumSearchTimer as ReturnType<
        typeof setTimeout
      >
    );
    (globalThis as Record<string, unknown>).__forumSearchTimer = setTimeout(
      () => {
        setDebouncedSearch(value);
      },
      400
    );
  };

  // API hooks
  const {
    data: postsResponse,
    isLoading: postsLoading,
    isError: postsError,
  } = useForumPosts({
    category: activeFilter,
    search: debouncedSearch || undefined,
  });

  const { data: stats } = useForumStats();

  const posts = postsResponse?.data ?? [];

  const handleCreateTopic = () => {
    if (user) {
      router.push('/forum/create');
    } else {
      router.push('/auth/login');
    }
  };

  return (
    <div className="min-h-screen bg-white text-gray-900">
      {/* Hero */}
      <section className="relative py-32 overflow-hidden bg-gradient-to-br from-yellow-50 via-white to-orange-50 border-b border-gray-200">
        {/* Mascot Decoration - Left */}
        <div className="absolute -left-16 bottom-0 opacity-20 pointer-events-none hidden lg:block">
          <Image
            src="/imports/WhatsApp_Image_2025-10-20_at_09.51.51__2_.jpeg"
            alt="Mascot Left"
            width={288}
            height={288}
            className="w-72 h-72 object-contain animate-float"
          />
        </div>

        {/* Mascot Decoration - Right */}
        <div className="absolute -right-16 top-1/4 opacity-20 pointer-events-none hidden lg:block">
          <Image
            src="/imports/WhatsApp_Image_2025-10-20_at_09.51.51__1_.jpeg"
            alt="Mascot Right"
            width={256}
            height={256}
            className="w-64 h-64 object-contain animate-float"
            style={{ animationDelay: '1s' }}
          />
        </div>

        <div className="container mx-auto px-4 relative z-10">
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8 }}
            className="text-center max-w-4xl mx-auto"
          >
            <div className="flex items-center justify-center gap-4 mb-6">
              <div className="h-1 w-12 bg-[#FFD738] rounded-full"></div>
              <span className="text-[#FFD738] font-bold tracking-[0.2em] uppercase text-sm">
                Discussion Board
              </span>
              <div className="h-1 w-12 bg-[#FFD738] rounded-full"></div>
            </div>
            <h1 className="text-5xl md:text-7xl font-black uppercase tracking-tight mb-6">
              FORUM
              <br />
              <span className="text-[#FFD738]">DISKUSI</span>
            </h1>
            <p className="text-gray-600 text-lg md:text-xl leading-relaxed mb-10">
              Berbagi cerita, resep, dan pengalaman bersama komunitas pecinta
              kuliner
            </p>

            {/* Search Bar */}
            <div className="max-w-2xl mx-auto relative">
              <Search
                size={20}
                className="absolute left-6 top-1/2 -translate-y-1/2 text-gray-400"
              />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => handleSearch(e.target.value)}
                placeholder="Cari topik diskusi..."
                className="w-full bg-white border-2 border-gray-200 rounded-full px-16 py-4 text-gray-900 placeholder-gray-400 focus:border-[#FFD738] focus:outline-none transition-colors shadow-sm"
              />
              <button className="absolute right-2 top-1/2 -translate-y-1/2 bg-[#FFD738] text-white px-6 py-2 rounded-full font-bold hover:bg-yellow-500 transition-colors shadow-md">
                Cari
              </button>
            </div>
          </motion.div>
        </div>
      </section>

      <div className="container mx-auto px-4 py-12">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Main Content */}
          <div className="lg:col-span-2">
            {/* Filter Tabs */}
            <div className="flex items-center justify-between mb-8 flex-wrap gap-4">
              <div className="flex items-center gap-2 bg-gray-100 rounded-xl p-1.5 shadow-sm">
                <button
                  onClick={() => setActiveFilter('all')}
                  className={`px-6 py-2.5 rounded-lg font-bold text-sm uppercase transition-all ${
                    activeFilter === 'all'
                      ? 'bg-[#FFD738] text-white shadow-md'
                      : 'text-gray-600 hover:text-gray-900'
                  }`}
                >
                  Semua
                </button>
                <button
                  onClick={() => setActiveFilter('resep')}
                  className={`px-6 py-2.5 rounded-lg font-bold text-sm uppercase transition-all ${
                    activeFilter === 'resep'
                      ? 'bg-[#FFD738] text-white shadow-md'
                      : 'text-gray-600 hover:text-gray-900'
                  }`}
                >
                  Resep
                </button>
                <button
                  onClick={() => setActiveFilter('komunitas')}
                  className={`px-6 py-2.5 rounded-lg font-bold text-sm uppercase transition-all ${
                    activeFilter === 'komunitas'
                      ? 'bg-[#FFD738] text-white shadow-md'
                      : 'text-gray-600 hover:text-gray-900'
                  }`}
                >
                  Komunitas
                </button>
              </div>

              <motion.button
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
                onClick={handleCreateTopic}
                className="flex items-center gap-2 bg-[#FFD738] text-white px-6 py-2.5 rounded-xl font-bold hover:bg-yellow-500 transition-colors shadow-lg"
              >
                <Plus size={18} />
                Buat Topik
              </motion.button>
            </div>

            {/* Loading State */}
            {postsLoading && (
              <div className="space-y-4">
                {[...Array(3)].map((_, i) => (
                  <div
                    key={i}
                    className="bg-white p-6 rounded-2xl border border-gray-200 animate-pulse"
                  >
                    <div className="flex items-center gap-3 mb-4">
                      <div className="h-6 w-16 bg-gray-200 rounded-full" />
                      <div className="h-4 w-24 bg-gray-200 rounded" />
                      <div className="h-4 w-20 bg-gray-200 rounded" />
                    </div>
                    <div className="h-6 w-3/4 bg-gray-200 rounded mb-3" />
                    <div className="h-4 w-full bg-gray-200 rounded mb-2" />
                    <div className="h-4 w-2/3 bg-gray-200 rounded mb-4" />
                    <div className="flex gap-6">
                      <div className="h-4 w-20 bg-gray-200 rounded" />
                      <div className="h-4 w-16 bg-gray-200 rounded" />
                    </div>
                  </div>
                ))}
              </div>
            )}

            {/* Error State */}
            {postsError && (
              <div className="text-center py-12 bg-white rounded-2xl border border-red-200">
                <AlertTriangle
                  className="mx-auto mb-4 text-red-400"
                  size={48}
                />
                <p className="text-red-500 font-bold text-lg mb-2">
                  Gagal memuat diskusi
                </p>
                <p className="text-gray-500 text-sm">
                  Terjadi kesalahan saat mengambil data. Silakan coba lagi.
                </p>
              </div>
            )}

            {/* Posts List */}
            {!postsLoading && !postsError && (
              <div className="space-y-4">
                {posts.length > 0 ? (
                  posts.map((post, idx) => (
                    <motion.div
                      key={post.id}
                      initial={{ opacity: 0, y: 20 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ duration: 0.5, delay: idx * 0.1 }}
                      className="bg-white p-6 rounded-2xl border border-gray-200 hover:border-[#FFD738] hover:shadow-xl transition-all group cursor-pointer"
                      onClick={() => router.push(`/forum/${post.id}`)}
                    >
                      <div className="flex items-start justify-between mb-4">
                        <div className="flex-1">
                          <div className="flex items-center gap-3 mb-2 flex-wrap">
                            <span
                              className={`px-3 py-1.5 rounded-full text-xs font-bold uppercase shadow-sm ${
                                post.category === 'resep'
                                  ? 'bg-[#FFD738] text-white'
                                  : 'bg-blue-500 text-white'
                              }`}
                            >
                              {post.category}
                            </span>
                            <span className="text-gray-500 text-sm font-medium">
                              oleh {post.author.name}
                            </span>
                            <span className="text-gray-400 text-sm">
                              •{' '}
                              {new Date(post.created_at).toLocaleDateString(
                                'id-ID',
                                {
                                  day: 'numeric',
                                  month: 'long',
                                  year: 'numeric',
                                }
                              )}
                            </span>
                          </div>
                          <h3 className="text-xl font-black uppercase group-hover:text-[#FFD738] transition-colors mb-3 text-gray-900">
                            {post.title}
                          </h3>
                          <p className="text-gray-600 text-sm line-clamp-2 mb-4">
                            {post.content}
                          </p>
                        </div>
                      </div>

                      <div className="flex items-center gap-6 text-sm">
                        <div className="flex items-center gap-2 text-gray-600 font-medium">
                          <MessageCircle size={16} />
                          <span>{post.replies_count} Balasan</span>
                        </div>
                        <div className="flex items-center gap-2 text-gray-600 font-medium">
                          <Heart size={16} />
                          <span>{post.likes_count} Suka</span>
                        </div>
                        <button className="ml-auto text-[#FFD738] font-bold flex items-center gap-1 group-hover:gap-2 transition-all">
                          Baca Selengkapnya
                          <ChevronRight size={16} />
                        </button>
                      </div>
                    </motion.div>
                  ))
                ) : (
                  <div className="text-center py-12 bg-white rounded-2xl border border-gray-200">
                    <p className="text-gray-500 font-medium">
                      Tidak ada topik diskusi ditemukan
                    </p>
                  </div>
                )}
              </div>
            )}
          </div>

          {/* Sidebar */}
          <div className="space-y-6">
            {/* Community Stats */}
            <div className="bg-gradient-to-br from-[#FFD738] to-yellow-500 p-6 rounded-2xl text-white shadow-lg">
              <h3 className="text-xl font-black uppercase mb-4">
                Statistik Komunitas
              </h3>
              <div className="space-y-3">
                <div className="flex items-center justify-between bg-white/10 backdrop-blur-sm rounded-lg p-3">
                  <span className="font-bold">Total Member</span>
                  <span className="text-2xl font-black">
                    {stats ? stats.total_members.toLocaleString('id-ID') : '—'}
                  </span>
                </div>
                <div className="flex items-center justify-between bg-white/10 backdrop-blur-sm rounded-lg p-3">
                  <span className="font-bold">Topik Diskusi</span>
                  <span className="text-2xl font-black">
                    {stats
                      ? stats.total_discussions.toLocaleString('id-ID')
                      : '—'}
                  </span>
                </div>
              </div>
            </div>

            {/* Mascot Image Slot */}
            <motion.div
              initial={{ opacity: 0, scale: 0.8 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ delay: 0.5 }}
              className="hidden lg:block"
            >
              <Image
                src="/imports/WhatsApp_Image_2025-10-20_at_09.51.51__2_.jpeg"
                alt="Forum Mascot"
                width={400}
                height={400}
                className="w-full h-auto object-contain drop-shadow-2xl animate-float"
              />
            </motion.div>

            {/* Call to Action */}
            <div className="bg-white p-6 rounded-2xl border border-gray-200 shadow-sm">
              <h3 className="text-lg font-black uppercase mb-4 text-gray-900">
                {user ? 'Mulai Diskusi!' : 'Belum Bergabung?'}
              </h3>
              <p className="text-gray-600 text-sm mb-6">
                {user
                  ? 'Bagikan pengalaman kulinermu dan berdiskusi dengan komunitas!'
                  : 'Daftar sekarang dan mulai berbagi pengalaman kulinermu!'}
              </p>
              <motion.button
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
                onClick={handleCreateTopic}
                className="w-full bg-[#FFD738] text-white py-3 rounded-xl font-black uppercase hover:bg-yellow-500 transition-colors shadow-md"
              >
                {user ? 'Buat Topik Baru' : 'Daftar Gratis'}
              </motion.button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
