'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { FileText, Users, Eye, Calendar } from 'lucide-react';
import api from '@/lib/api';
import { Post } from '@/types';
import { PageSpinner } from '@/components/ui/Spinner';
import { StatusBadge } from '@/components/ui/Badge';

interface Stats {
  posts: number;
  users: number;
}

const statCards = [
  { key: 'posts', label: 'News', icon: FileText, href: '/posts', color: 'bg-blue-50 text-blue-600' },
  { key: 'users', label: 'Users', icon: Users, href: '/users', color: 'bg-red-50 text-red-600' },
] as const;

function formatDate(dateString: string) {
  return new Date(dateString).toLocaleDateString('en-US', {
    month: 'short', day: 'numeric', year: 'numeric',
  });
}

export default function DashboardPage() {
  const [stats, setStats] = useState<Stats | null>(null);
  const [recentPosts, setRecentPosts] = useState<Post[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    async function loadData() {
      try {
        const [postsData] = await Promise.allSettled([
          api.getAdminPosts({ limit: 5, page: 1 }),
        ]);

        const postResult = postsData.status === 'fulfilled' ? postsData.value : null;

        let usersCount = 0;
        try {
          const usersData = await api.getUsers({ limit: 1, page: 1 });
          usersCount = usersData.pagination?.total ?? 0;
        } catch {
          // Not admin, ignore
        }

        setStats({
          posts: postResult?.pagination?.total ?? 0,
          users: usersCount,
        });

        if (postResult?.posts) {
          setRecentPosts(postResult.posts.slice(0, 5));
        }
      } finally {
        setIsLoading(false);
      }
    }
    loadData();
  }, []);

  if (isLoading) return <PageSpinner />;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-gray-900">Dashboard</h1>
        <p className="text-sm text-gray-500 mt-1">Welcome to GLG content management</p>
      </div>

      {/* Stats grid */}
      <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
        {statCards.map(({ key, label, icon: Icon, href, color }) => (
          <Link
            key={key}
            href={href}
            className="bg-white rounded-xl border border-gray-200 p-5 hover:shadow-md transition-shadow"
          >
            <div className={`w-10 h-10 rounded-lg flex items-center justify-center mb-3 ${color}`}>
              <Icon size={20} />
            </div>
            <p className="text-2xl font-bold text-gray-900">
              {stats?.[key] ?? '—'}
            </p>
            <p className="text-sm text-gray-500 mt-0.5">{label}</p>
          </Link>
        ))}
      </div>

      {/* Recent Posts */}
      <div className="bg-white rounded-xl border border-gray-200">
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200">
          <h2 className="text-base font-semibold text-gray-900">Recent News</h2>
          <Link href="/posts" className="text-sm text-blue-600 hover:text-blue-700 font-medium">
            View all
          </Link>
        </div>

        {recentPosts.length === 0 ? (
          <div className="px-6 py-10 text-center text-gray-400 text-sm">
            No news yet. <Link href="/posts/new" className="text-blue-600 hover:underline">Create your first article</Link>
          </div>
        ) : (
          <div className="divide-y divide-gray-100">
            {recentPosts.map((post) => (
              <div key={post._id} className="flex items-center gap-4 px-6 py-3.5">
                <div className="flex-1 min-w-0">
                  <Link
                    href={`/posts/edit?id=${post._id}`}
                    className="text-sm font-medium text-gray-900 hover:text-blue-600 truncate block"
                  >
                    {post.title?.en || post.title?.zh}
                  </Link>
                  <div className="flex items-center gap-3 mt-0.5">
                    <span className="text-xs text-gray-400">{post.category}</span>
                    <span className="text-xs text-gray-300">·</span>
                    <span className="flex items-center gap-1 text-xs text-gray-400">
                      <Eye size={11} />
                      {post.views}
                    </span>
                  </div>
                </div>
                <div className="flex items-center gap-3 flex-shrink-0">
                  <StatusBadge status={post.status} />
                  <span className="flex items-center gap-1 text-xs text-gray-400 hidden sm:flex">
                    <Calendar size={11} />
                    {formatDate(post.updatedAt)}
                  </span>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Quick actions */}
      <div className="bg-white rounded-xl border border-gray-200 p-6">
        <h2 className="text-base font-semibold text-gray-900 mb-4">Quick actions</h2>
        <div className="flex flex-wrap gap-3">
          <Link
            href="/posts/new"
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 transition-colors"
          >
            <FileText size={16} />
            New Article
          </Link>
        </div>
      </div>
    </div>
  );
}
