'use client';
import { useLocale, useTranslations } from 'next-intl';
import { useRouter } from 'next/navigation';
import { Box, Skeleton, Stack } from '@mui/material';
import { AppButton, EmptyState, ErrorState, PageHeader } from '@/components';
import { SessionCard, useEvvController } from '@/components/booking';
import { CONTENT_MAX_WIDTH } from '@/components/config';
import { ROUTES } from '@/constants';
import { formatShamsiDate } from '@/utils';
import { useSessionEvv, useTodaySessions } from '@/services/bookings';
import type { BookingSessionListItemDto } from '@/services/bookings/types';

const TODAY_HEADER_DATE_OPTIONS: Intl.DateTimeFormatOptions = { month: 'long', day: 'numeric' };

/**
 * Nurse ویزیت امروز (E3 top) — the day's operational surface. Lists today's sessions from
 * `useTodaySessions` (polled every 60s so a same-day schedule change surfaces without re-navigation);
 * each renders the shared `SessionCard` with the per-session EVV check-in/out control (driven by one
 * `useEvvController`) and the advisory EVV banner once checked in. A GPS mismatch is advisory, never a
 * block. Each card also deep-links to the full booking detail (`/nurse/visits/{id}`), where the gated
 * care instructions live. Visit-note authoring + task checklist are deferred to f13.
 */
export default function NurseVisitsPage() {
  const t = useTranslations('booking');
  const locale = useLocale();
  const { data, isLoading, isError, refetch } = useTodaySessions();
  const evv = useEvvController();
  const items = data?.items ?? [];
  const dateAnchor = t('today_date_prefix', { date: formatShamsiDate(new Date(), locale, TODAY_HEADER_DATE_OPTIONS) });

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3, maxWidth: CONTENT_MAX_WIDTH, mx: 'auto', width: '100%' }}>
      <PageHeader title={dateAnchor} subtitle={t('evv_visits_subtitle')} />

      {isLoading ? (
        <Stack sx={{ gap: 2 }}>
          {[0, 1].map((key) => (
            <Skeleton key={key} variant="rounded" height={150} />
          ))}
        </Stack>
      ) : isError ? (
        <ErrorState message={t('evv_visits_error')} retryLabel={t('retry')} onRetry={() => refetch()} />
      ) : items.length === 0 ? (
        <EmptyState icon="visits" title={t('evv_no_visits')} />
      ) : (
        <Stack sx={{ gap: 2 }}>
          {items.map((item) => (
            <TodayVisitCard key={item.sessionId} item={item} evv={evv} />
          ))}
        </Stack>
      )}
    </Box>
  );
}

function TodayVisitCard({ item, evv }: { item: BookingSessionListItemDto; evv: ReturnType<typeof useEvvController> }) {
  const t = useTranslations('booking');
  const locale = useLocale();
  const router = useRouter();

  // Fetch the EVV detail only once the session has activity, so the banner has the server check-in time.
  const hasEvvActivity = item.evvStatus !== 'pending';
  const { data: evvDetail } = useSessionEvv(item.sessionId, { enabled: hasEvvActivity });

  return (
    <Stack sx={{ gap: 0.75 }}>
      <SessionCard
        title={item.patientName}
        serviceLabel={item.variantLabel}
        sessionIndex={item.sessionIndex}
        scheduledDate={item.scheduledDate}
        scheduledTimeStart={item.scheduledTimeStart}
        scheduledTimeEnd={item.scheduledTimeEnd}
        status={item.status}
        evvStatus={item.evvStatus}
        checkInAt={evvDetail?.checkInAt ?? null}
        checkOutAt={evvDetail?.checkOutAt ?? null}
        checkInAddressMatch={evvDetail?.checkInAddressMatch ?? null}
        showEvvControls
        evvPending={evv.busySessionId === item.sessionId}
        acquiringLocation={evv.acquiringSessionId === item.sessionId}
        onCheckIn={() => evv.checkIn({ sessionId: item.sessionId, bookingId: item.bookingId })}
        onCheckOut={() => evv.checkOut({ sessionId: item.sessionId, bookingId: item.bookingId })}
      />
      <AppButton
        variant="text"
        color="primary"
        endIcon="bookings"
        onClick={() => router.push(`/${locale}${ROUTES.NURSE_VISITS}/${item.bookingId}`)}
        sx={{ alignSelf: 'flex-start' }}
      >
        {t('view_booking')}
      </AppButton>
    </Stack>
  );
}
