'use client';

import { useState, useEffect } from 'react';
import { AdminDashboardTemplate } from '@/templates/AdminDashboardTemplate';
import { AdminDashboardViewData } from '@/lib/view-data/AdminDashboardViewData';
import { AdminDashboardPageQuery } from '@/lib/page-queries/AdminDashboardPageQuery';

export function AdminDashboardClient() {
  const [viewData, setViewData] = useState<AdminDashboardViewData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const loadStats = async () => {
    try {
      setLoading(true);
      
      const query = new AdminDashboardPageQuery();
      const result = await query.execute();
      
      if (result.status === 'ok') {
        // Page Query already returns View Data via builder
        setViewData(result.dto);
      } else if (result.status === 'notFound') {
        // Handle not found - could show a message or redirect
        console.error('Access denied - You must be logged in as an Owner or Admin');
      } else {
        // Handle error - could show a toast or error message
        console.error('Failed to load dashboard stats');
      }
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Failed to load stats';
      console.error(message);
    } finally {
      setLoading(false);
    }
  };

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

  if (!viewData) {
    return (
      <div className="flex flex-col items-center justify-center py-20 space-y-3">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-blue"></div>
        <div className="text-gray-400">Loading dashboard...</div>
      </div>
    );
  }

  return (
    <AdminDashboardTemplate
      viewData={viewData}
      onRefresh={loadStats}
      isLoading={loading}
    />
  );
}