// pages/dashboard.jsx - User Dashboard After Login
import { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import Link from 'next/link';

export default function Dashboard() {
  const router = useRouter();
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState({
    profiles: 0,
    ads: 0,
    listings: 0
  });

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

  const checkAuth = async () => {
    try {
      const token = localStorage.getItem('token');
      if (!token) {
        router.push('/login');
        return;
      }

      const response = await fetch('/api/auth/me', {
        headers: { 'Authorization': `Bearer ${token}` }
      });

      if (response.ok) {
        const data = await response.json();
        setUser(data.user);
        fetchUserStats(token);
      } else {
        localStorage.removeItem('token');
        router.push('/login');
      }
    } catch (error) {
      router.push('/login');
    } finally {
      setLoading(false);
    }
  };

  const fetchUserStats = async (token) => {
    // Fetch user's profile count, ads count, listings count
    // This is a placeholder - implement actual API calls
    setStats({
      profiles: 1,
      ads: 3,
      listings: 2
    });
  };

  const handleLogout = () => {
    localStorage.removeItem('token');
    router.push('/');
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white shadow-sm">
        <div className="container mx-auto px-4 py-4 flex items-center justify-between">
          <Link href="/">
            <h1 className="text-2xl font-bold text-blue-600 cursor-pointer">Your Platform</h1>
          </Link>
          <div className="flex items-center gap-6">
            <Link href="/" className="text-gray-600 hover:text-blue-600">Home</Link>
            <Link href="/dashboard" className="text-blue-600 font-semibold">Dashboard</Link>
            {(user?.role === 'Admin' || user?.role === 'Staff') && (
              <Link href="/admin" className="text-gray-600 hover:text-blue-600">Admin Panel</Link>
            )}
            <button
              onClick={handleLogout}
              className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
            >
              Logout
            </button>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <div className="container mx-auto px-4 py-8">
        {/* Welcome Section */}
        <div className="bg-white rounded-lg shadow p-6 mb-8">
          <h2 className="text-2xl font-bold mb-2">
            Welcome back, {user?.firstName} {user?.lastName}!
          </h2>
          <p className="text-gray-600">
            Email: {user?.email} • Role: <span className="font-semibold">{user?.role}</span>
          </p>
        </div>

        {/* Stats Grid */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
          <StatCard
            title="Matrimonial Profiles"
            count={stats.profiles}
            icon="💑"
            link="/matrimonial/my-profile"
            linkText="Manage Profile"
          />
          <StatCard
            title="My Classified Ads"
            count={stats.ads}
            icon="🛍️"
            link="/classifieds/my-ads"
            linkText="View Ads"
          />
          <StatCard
            title="My Event Listings"
            count={stats.listings}
            icon="🎉"
            link="/events/my-listings"
            linkText="View Listings"
          />
        </div>

        {/* Quick Actions */}
        <div className="bg-white rounded-lg shadow p-6">
          <h3 className="text-xl font-bold mb-4">Quick Actions</h3>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <ActionButton
              href="/matrimonial/create-profile"
              icon="➕"
              title="Create Matrimonial Profile"
            />
            <ActionButton
              href="/classifieds/post-ad"
              icon="📝"
              title="Post Classified Ad"
            />
            <ActionButton
              href="/events/create-listing"
              icon="🎯"
              title="Create Event Listing"
            />
          </div>
        </div>
      </div>
    </div>
  );
}

function StatCard({ title, count, icon, link, linkText }) {
  return (
    <div className="bg-white rounded-lg shadow p-6">
      <div className="flex items-center justify-between mb-4">
        <div className="text-4xl">{icon}</div>
        <div className="text-right">
          <p className="text-3xl font-bold text-blue-600">{count}</p>
          <p className="text-sm text-gray-600">{title}</p>
        </div>
      </div>
      <Link href={link}>
        <div className="text-center py-2 bg-blue-50 text-blue-600 rounded hover:bg-blue-100 cursor-pointer">
          {linkText} →
        </div>
      </Link>
    </div>
  );
}

function ActionButton({ href, icon, title }) {
  return (
    <Link href={href}>
      <div className="flex items-center gap-3 p-4 border-2 border-gray-200 rounded-lg hover:border-blue-500 hover:bg-blue-50 cursor-pointer transition-all">
        <span className="text-2xl">{icon}</span>
        <span className="font-medium">{title}</span>
      </div>
    </Link>
  );
}