'use client';

import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { errorText } from '@/lib/api/errors';
import { listDashboards } from '../api.client';
import { DashboardsView } from './DashboardsView';
import { StateMessage } from './shared';

/**
 * Reports › Dashboards opens a dashboard, as in the design: the one you marked "Default
 * dashboard" (QA #571), else the business's default, else the first. With none, the list.
 */
export function DashboardsHome() {
  const router = useRouter();
  const [state, setState] = useState<'loading' | 'empty' | { error: string }>('loading');
  useEffect(() => {
    let alive = true;
    listDashboards().then(
      (rows) => {
        if (!alive) return;
        const first = rows.find((d) => d.isMyDefault) ?? rows.find((d) => d.isDefault) ?? rows[0];
        if (first) router.replace(`/reports/dashboards/${first.id}`);
        else setState('empty');
      },
      (err: unknown) => alive && setState({ error: errorText(err) }),
    );
    return () => {
      alive = false;
    };
  }, [router]);
  if (state === 'empty') return <DashboardsView />;
  return (
    <section className="card list-card">
      {state === 'loading' ? (
        <StateMessage>Opening your dashboard…</StateMessage>
      ) : (
        <StateMessage tone="danger" title="Could not load dashboards">
          {state.error}
        </StateMessage>
      )}
    </section>
  );
}
