'use client';

import Link from 'next/link';
import { MobileLayout } from '@/components/mobile-layout';
import type { useActiveFieldPeriod } from '@/hooks/use-active-field-period';

export function FieldPeriodStatus({ state }: { state: ReturnType<typeof useActiveFieldPeriod> }) {
  const status = (state.error as { response?: { status?: number } } | null)?.response?.status;
  const authRequired = status === 401 || status === 403;
  const loading = state.isOnline && (state.isPending && !state.isError || state.isFetching);
  const message = loading ? 'Loading the current plan period...'
    : authRequired ? 'Sign in again to load the current plan period.'
    : !state.isOnline ? 'Connect once to download the current plan period.'
    : state.isError ? 'Could not reach the server. Please try again.'
    : 'No plan period is currently active.';
  return <MobileLayout>
    <div className="space-y-3 p-5" role="status">
      <p>{message}</p>
      {!loading && authRequired && <Link href="/login" className="font-semibold text-emerald-700 underline">Sign in</Link>}
      {!loading && !authRequired && state.isOnline && <button type="button" onClick={() => void state.refetch()} className="font-semibold text-emerald-700 underline">Retry</button>}
    </div>
  </MobileLayout>;
}
