'use client';

import { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { boardApi, BoardPostListItem, BoardCategory, BoardPostListResponse, BoardCategoryListResponse } from '@/lib/api';
import { useAuthStore } from '@/lib/store';
import { useTranslate } from '@/lib/useTranslate';
import { useLanguageStore } from '@/lib/i18n';

export default function BoardPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { user, token } = useAuthStore();
  const isLoggedIn = !!token && !!user;
  const { translate } = useTranslate();
  const { language } = useLanguageStore();

  const [posts, setPosts] = useState<BoardPostListItem[]>([]);
  const [notices, setNotices] = useState<BoardPostListItem[]>([]);
  const [categories, setCategories] = useState<BoardCategory[]>([]);
  const [total, setTotal] = useState(0);
  const [totalPages, setTotalPages] = useState(1);
  const [loading, setLoading] = useState(true);

  const page = parseInt(searchParams.get('page') || '1');
  const categoryId = searchParams.get('category') ? parseInt(searchParams.get('category')!) : undefined;
  const search = searchParams.get('search') || '';

  const getCategoryName = (cat: BoardCategory) => {
    if (language === 'en' && cat.name_en) return cat.name_en;
    if (language === 'mn' && cat.name_mn) return cat.name_mn;
    if (language === 'ru' && cat.name_ru) return cat.name_ru;
    return cat.name;
  };

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const [postsRes, categoriesRes] = await Promise.all([
          boardApi.getPosts({ page, page_size: 20, category_id: categoryId, search }),
          boardApi.getCategories(),
        ]);
        setPosts(postsRes.posts);
        setNotices(postsRes.notices);
        setTotal(postsRes.total);
        setTotalPages(postsRes.total_pages);
        setCategories(categoriesRes.categories);
      } catch (error) {
        console.error('Failed to fetch board data:', error);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [page, categoryId, search]);

  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (days === 0) {
      return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    } else if (days < 7) {
      return `${days}d ago`;
    } else {
      return date.toLocaleDateString();
    }
  };

  const handleCategoryChange = (catId: number | undefined) => {
    const params = new URLSearchParams();
    if (catId) params.set('category', catId.toString());
    if (search) params.set('search', search);
    router.push(`/board?${params.toString()}`);
  };

  const handleSearch = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    const searchValue = formData.get('search') as string;
    const params = new URLSearchParams();
    if (categoryId) params.set('category', categoryId.toString());
    if (searchValue) params.set('search', searchValue);
    router.push(`/board?${params.toString()}`);
  };

  const renderPostRow = (post: BoardPostListItem, isNotice: boolean = false) => (
    <tr
      key={post.id}
      className={`hover:bg-gray-50 cursor-pointer ${isNotice ? 'bg-amber-50' : ''}`}
      onClick={() => router.push(`/board/${post.id}`)}
    >
      <td className="px-4 py-3 text-center text-sm text-gray-500">
        {isNotice ? (
          <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800">
            Notice
          </span>
        ) : (
          post.id
        )}
      </td>
      <td className="px-4 py-3">
        <div className="flex items-center gap-2">
          {post.is_pinned && !isNotice && (
            <span className="text-amber-500" title="Pinned">
              <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                <path d="M5.5 16a3.5 3.5 0 01-.369-6.98 4 4 0 117.753-1.977A4.5 4.5 0 1113.5 16h-8z" />
              </svg>
            </span>
          )}
          <span className={`text-sm ${isNotice ? 'font-semibold text-red-700' : 'text-gray-900'}`}>
            {post.title}
          </span>
        </div>
      </td>
      <td className="px-4 py-3 text-sm text-gray-500 hidden md:table-cell">
        {post.category_name || '-'}
      </td>
      <td className="px-4 py-3 text-sm text-gray-500 hidden sm:table-cell">
        {post.author_name || 'Unknown'}
      </td>
      <td className="px-4 py-3 text-sm text-gray-500 text-center hidden sm:table-cell">
        {post.view_count}
      </td>
      <td className="px-4 py-3 text-sm text-gray-500 text-right">
        {formatDate(post.created_at)}
      </td>
    </tr>
  );

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-6xl mx-auto px-4 py-8">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <h1 className="text-2xl font-bold text-gray-900">
            {translate('Board')}
          </h1>
          {isLoggedIn && (
            <Link
              href="/board/write"
              className="inline-flex items-center px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors"
            >
              <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
              </svg>
              {translate('Write')}
            </Link>
          )}
        </div>

        {/* Categories & Search */}
        <div className="bg-white rounded-lg shadow-sm p-4 mb-6">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            {/* Category Tabs */}
            <div className="flex flex-wrap gap-2">
              <button
                onClick={() => handleCategoryChange(undefined)}
                className={`px-3 py-1.5 text-sm rounded-full transition-colors ${
                  !categoryId
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }`}
              >
                {translate('All')}
              </button>
              {categories.map((cat) => (
                <button
                  key={cat.id}
                  onClick={() => handleCategoryChange(cat.id)}
                  className={`px-3 py-1.5 text-sm rounded-full transition-colors ${
                    categoryId === cat.id
                      ? 'bg-blue-600 text-white'
                      : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                  }`}
                >
                  {getCategoryName(cat)} ({cat.post_count})
                </button>
              ))}
            </div>

            {/* Search */}
            <form onSubmit={handleSearch} className="flex gap-2">
              <input
                type="text"
                name="search"
                defaultValue={search}
                placeholder={translate('Search...')}
                className="px-3 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
              <button
                type="submit"
                className="px-3 py-1.5 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
              >
                <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
              </button>
            </form>
          </div>
        </div>

        {/* Posts Table */}
        <div className="bg-white rounded-lg shadow-sm overflow-hidden">
          {loading ? (
            <div className="p-8 text-center">
              <div className="inline-block animate-spin rounded-full h-8 w-8 border-4 border-blue-600 border-t-transparent"></div>
            </div>
          ) : notices.length === 0 && posts.length === 0 ? (
            <div className="p-8 text-center text-gray-500">
              {translate('No posts yet')}
            </div>
          ) : (
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider w-20">
                    #
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    {translate('Title')}
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider hidden md:table-cell w-32">
                    {translate('Category')}
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider hidden sm:table-cell w-32">
                    {translate('Author')}
                  </th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider hidden sm:table-cell w-20">
                    {translate('Views')}
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider w-28">
                    {translate('Date')}
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {notices.map((notice) => renderPostRow(notice, true))}
                {posts.map((post) => renderPostRow(post, false))}
              </tbody>
            </table>
          )}
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="mt-6 flex justify-center">
            <nav className="flex items-center gap-1">
              <button
                onClick={() => {
                  const params = new URLSearchParams(searchParams.toString());
                  params.set('page', (page - 1).toString());
                  router.push(`/board?${params.toString()}`);
                }}
                disabled={page <= 1}
                className="px-3 py-2 text-sm text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Prev
              </button>
              <span className="px-4 py-2 text-sm text-gray-700">
                {page} / {totalPages}
              </span>
              <button
                onClick={() => {
                  const params = new URLSearchParams(searchParams.toString());
                  params.set('page', (page + 1).toString());
                  router.push(`/board?${params.toString()}`);
                }}
                disabled={page >= totalPages}
                className="px-3 py-2 text-sm text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Next
              </button>
            </nav>
          </div>
        )}

        {/* Login prompt for non-logged in users */}
        {!isLoggedIn && (
          <div className="mt-6 p-4 bg-blue-50 rounded-lg text-center">
            <p className="text-sm text-blue-800">
              {translate('Please login to write a post')}.{' '}
              <Link href="/login" className="font-medium underline">
                {translate('Login')}
              </Link>
            </p>
          </div>
        )}
      </div>
    </div>
  );
}
