import React from 'react';
import { useTranslation } from 'react-i18next';
import { StatCard } from '@/components/shared/StatCard';
import { ActivityFeed, ActivityItem } from '@/components/shared/ActivityFeed';
import { DashboardGrid } from '@/components/dashboard/DashboardGrid';
import { useUnifiedContacts, useAuditLog } from '@/api/hooks';
import { useDashboardWidgets } from '@/api/dashboard';
import { formatDateTime } from '@/utils/date';

export function DashboardPage() {
  const { t } = useTranslation();
  const { data: companiesData } = useUnifiedContacts(1, 1, undefined, 'company');
  const { data: contactsData } = useUnifiedContacts(1, 1, undefined, 'person');
  const { data: auditData, isError: auditError } = useAuditLog(1, 5);
  const { data: widgetsData, isError: widgetsError } = useDashboardWidgets();

  const totalCompanies = companiesData?.total ?? 0;
  const totalContacts = contactsData?.total ?? 0;

  const auditEntries = auditData?.items ?? [];
  const activeThisWeek = auditEntries.filter((e) => {
    if (!e.timestamp) return false;
    const d = new Date(e.timestamp);
    const weekAgo = new Date();
    weekAgo.setDate(weekAgo.getDate() - 7);
    return d >= weekAgo;
  }).length;

  const newThisMonth = auditEntries.filter((e) => {
    if (!e.timestamp) return false;
    const d = new Date(e.timestamp);
    const monthAgo = new Date();
    monthAgo.setMonth(monthAgo.getMonth() - 1);
    return d >= monthAgo;
  }).length;

  const activities: ActivityItem[] = auditError
    ? []
    : auditEntries.map((entry) => ({
        id: `${entry.timestamp}-${entry.user}-${entry.action}`,
        user: entry.user || 'System',
        action: entry.action || '',
        time: entry.timestamp ? (formatDateTime(entry.timestamp) || '') : '',
        avatarUrl: null,
      }));

  const widgets = widgetsData?.items ?? [];

  return (
    <div className="p-6 max-w-7xl mx-auto" data-testid="dashboard-page">
      <h1 className="text-2xl font-bold text-secondary-900 mb-6">{t('dashboard.title')}</h1>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        <StatCard
          label={t('dashboard.totalCompanies')}
          value={totalCompanies}
          testId="stat-companies"
        />
        <StatCard
          label={t('dashboard.totalContacts')}
          value={totalContacts}
          testId="stat-contacts"
        />
        <StatCard
          label={t('dashboard.activeThisWeek')}
          value={activeThisWeek}
          testId="stat-active-week"
        />
        <StatCard
          label={t('dashboard.newThisMonth')}
          value={newThisMonth}
          testId="stat-new-month"
        />
      </div>

      {/* Dynamic Plugin Widgets */}
      {widgetsError ? (
        <p className="text-sm text-secondary-500 mb-6" data-testid="dashboard-widgets-unavailable">
          {t('dashboard.widgetsUnavailable')}
        </p>
      ) : widgets.length > 0 ? (
        <div className="mb-8">
          <h2 className="text-lg font-semibold text-secondary-800 mb-4">{t('dashboard.widgets')}</h2>
          <DashboardGrid widgets={widgets} />
        </div>
      ) : null}

      {auditError ? (
        <p className="text-sm text-secondary-500" data-testid="activity-unavailable">
          {t('dashboard.activityUnavailable')}
        </p>
      ) : (
        <ActivityFeed activities={activities} title={t('dashboard.recentActivity')} />
      )}
    </div>
  );
}
