'use client';
import { useLocale, useTranslations } from 'next-intl';
import { useRouter } from 'next/navigation';
import { Box, Chip, Paper, Skeleton, Stack, Typography } from '@mui/material';
import { AppButton, CountdownTimer, EmptyState, ErrorState } from '@/components';
import { ROUTES } from '@/constants';
import { formatShamsiDate, localeTag } from '@/utils';
import { useNurseRequestInbox } from '@/services/bookingRequests';
import type { BookingRequestListItem } from '@/services/bookingRequests/types';

/**
 * Nurse incoming-requests inbox (نمای پرستار). Lists pending requests — each a card with the family's
 * patient name, the requested time (Shamsi), the **required-caregiver-gender** chip, a notes preview, and
 * a **per-request countdown** to that request's response deadline. Two-stage disclosure: the row shows
 * only `customerNotes` — never an address or any clinical field. Lightly polled so new requests appear.
 */
export default function NurseRequestsPage() {
  const t = useTranslations('booking');
  const tc = useTranslations('common');
  const { data, isLoading, isError, refetch } = useNurseRequestInbox();
  const items = data?.items ?? [];

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3, maxWidth: 640 }}>
      <Box>
        <Typography variant="h5" component="h1">
          {t('inbox_title')}
        </Typography>
        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          {t('inbox_subtitle')}
        </Typography>
      </Box>

      {isLoading ? (
        <Stack sx={{ gap: 2 }}>
          {[0, 1].map((key) => (
            <Skeleton key={key} variant="rounded" height={140} />
          ))}
        </Stack>
      ) : isError ? (
        <ErrorState message={t('inbox_error')} retryLabel={tc('retry')} onRetry={() => refetch()} />
      ) : items.length === 0 ? (
        <EmptyState icon="requests" title={t('inbox_empty')} />
      ) : (
        <Stack sx={{ gap: 2 }}>
          {items.map((item) => (
            <InboxCard key={item.id} item={item} />
          ))}
        </Stack>
      )}
    </Box>
  );
}

function InboxCard({ item }: { item: BookingRequestListItem }) {
  const t = useTranslations('booking');
  const locale = useLocale();
  const router = useRouter();

  const startDate = new Date(`${item.requestedDate}T${item.requestedTimeStart}`);
  const endDate = new Date(`${item.requestedDate}T${item.requestedTimeEnd}`);
  const timeFmt = new Intl.DateTimeFormat(localeTag(locale), { hour: '2-digit', minute: '2-digit' });
  const whenLabel = `${formatShamsiDate(startDate, locale)} · ${timeFmt.format(startDate)} – ${timeFmt.format(endDate)}`;

  return (
    <Paper elevation={0} sx={{ p: 2.5, border: '1px solid', borderColor: 'divider', borderRadius: 2 }}>
      <Stack sx={{ gap: 1.5 }}>
        <Stack direction="row" sx={{ justifyContent: 'space-between', alignItems: 'flex-start', gap: 2 }}>
          <Stack sx={{ gap: 0.5, minWidth: 0 }}>
            <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
              {item.counterpartyName}
            </Typography>
            <Typography variant="body2" sx={{ color: 'text.secondary' }}>
              {whenLabel}
            </Typography>
          </Stack>
          <CountdownTimer deadlineIso={item.nurseResponseDeadlineAt} elapsedText={t('response_elapsed')} />
        </Stack>

        {item.requiredCaregiverGender ? (
          <Box>
            <Chip
              size="small"
              label={t('required_gender_chip', { gender: t(`gender_${item.requiredCaregiverGender}`) })}
              sx={{ bgcolor: 'var(--bal-primary-soft)', color: 'var(--bal-primary)', fontWeight: 500 }}
            />
          </Box>
        ) : null}

        {item.customerNotes ? (
          <Box>
            <Typography variant="caption" sx={{ color: 'text.secondary', fontWeight: 700 }}>
              {t('inbox_notes_label')}
            </Typography>
            <Typography variant="body2" sx={{ color: 'text.secondary' }} noWrap>
              {item.customerNotes}
            </Typography>
          </Box>
        ) : null}

        <AppButton
          variant="outlined"
          color="primary"
          endIcon="requests"
          onClick={() => router.push(`/${locale}${ROUTES.NURSE_REQUESTS}/${item.id}`)}
          sx={{ alignSelf: 'flex-start' }}
        >
          {t('open_detail')}
        </AppButton>
      </Stack>
    </Paper>
  );
}
