'use client';

import { useMemo } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { Link } from '@/i18n/navigation';
import { useAuth } from '@/lib/hooks/useAuth';
import { getUserFacingError } from '@/components/shared/formatApiError';
import { TodayDashboard } from '@/components/ui/today/TodayDashboard';
import { TodayLoadErrorBanner } from '@/components/ui/today/TodayLoadErrorBanner';
import { TodaySectionErrorFallback } from '@/components/ui/today/TodaySectionErrorFallback';
import { TodayWidgetErrorBoundary } from '@/components/ui/today/TodayWidgetErrorBoundary';
import { useTodaySummary } from '@/lib/hooks/useTodaySummary';
import { formatAppTime } from '@/lib/i18n/format';

export function TodayPage() {
  const locale = useLocale();
  const t = useTranslations('today');
  const tErrors = useTranslations('errors');
  const { currentOrganization } = useAuth();
  const orgId = currentOrganization?.id;
  const {
    data,
    loading,
    isInitialLoad,
    error,
    chartPeriods,
    setChartPeriod,
    reload,
  } = useTodaySummary(orgId);

  const showNoSubscriptionNotice = useMemo(
    () => Boolean(currentOrganization?.isOwner) && !currentOrganization?.plan,
    [currentOrganization],
  );

  const sectionErrorMessage = t('sectionLoadError');

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between">
        <h1 className="text-2xl font-semibold">{t('welcomeBack')}</h1>
        {data?.generatedAt && !isInitialLoad ? (
          <p className="text-xs text-text-muted">
            {t('lastUpdated', {
              time: formatAppTime(data.generatedAt, locale),
            })}
          </p>
        ) : null}
      </div>

      {showNoSubscriptionNotice && (
        <div className="rounded-[var(--radius-md)] border border-amber-500/30 bg-amber-500/10 p-4">
          <p className="text-sm text-amber-200">
            {t('noSubscriptionNotice')}{' '}
            <Link href="/settings/subscriptions" className="font-medium underline underline-offset-2">
              {t('choosePlanLink')}
            </Link>{' '}
            {t('noSubscriptionCta')}
          </p>
        </div>
      )}

      {error ? (
        <TodayLoadErrorBanner
          message={getUserFacingError(error, tErrors, t('loadError'))}
          retryLabel={t('retryLoad')}
          onRetry={() => void reload()}
          isRetrying={loading && Boolean(data)}
        />
      ) : null}

      <TodayWidgetErrorBoundary
        fallback={<TodaySectionErrorFallback message={sectionErrorMessage} />}
      >
        <TodayDashboard
          widgets={data?.widgets ?? {}}
          charts={data?.charts ?? {}}
          actions={data?.actions ?? {}}
          subscription={data?.subscription}
          chartPeriods={chartPeriods}
          onChartPeriodChange={setChartPeriod}
          loading={loading}
          isInitialLoad={isInitialLoad}
          hasError={Boolean(error)}
        />
      </TodayWidgetErrorBoundary>
    </div>
  );
}
