'use client';
import { useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useRouter } from 'next/navigation';
import { Box, Chip, Skeleton, Stack, Tab, Tabs, Typography } from '@mui/material';
import { AppLink, CountdownTimer, EmptyState, ErrorState, Pager, PageHeader, SurfaceCard } from '@/components';
import { CONTENT_MAX_WIDTH } from '@/components/config';
import { ROUTES } from '@/constants';
import { formatShamsiDate, localeTag } from '@/utils';
import { useNurseRequestInbox } from '@/services/bookingRequests';
import { coarseResponseLabel } from '@/services/bookingRequests/format';
import type { BookingRequestListItem } from '@/services/bookingRequests/types';

type InboxTab = 'pending' | 'answered' | 'expired';

/** The pill's urgency tiers (§3.4): teal >2h · amber <2h · terracotta <30min. */
const URGENT_THRESHOLD_SECONDS = 30 * 60;
const WARN_THRESHOLD_SECONDS = 2 * 60 * 60;

/**
 * Nurse incoming-requests inbox (نمای پرستار), ui-phase-7 redesign. Decision-first cards (service + price
 * headline when the list DTO serves them — REQ-050, mock-tolerant), an urgency-tinted countdown pill, and
 * three tabs: «در انتظار» (a single `pending_nurse_response` query) / «پاسخ‌داده» (merged, page-1-only —
 * the API filters by a *single* status and there's no status-group filter yet, so this tab concatenates
 * three page-1 queries; a documented limitation until REQ-050's status-group filter lands) / «منقضی»
 * (`expired_no_response`). Two-stage disclosure unchanged: the row shows only `customerNotes` — never an
 * address or any clinical field.
 */
export default function NurseRequestsPage() {
  const t = useTranslations('booking');
  const [tab, setTab] = useState<InboxTab>('pending');
  const [pendingPage, setPendingPage] = useState(1);
  const [expiredPage, setExpiredPage] = useState(1);

  const pendingQuery = useNurseRequestInbox('pending_nurse_response', pendingPage, { enabled: tab === 'pending' });
  const expiredQuery = useNurseRequestInbox('expired_no_response', expiredPage, { enabled: tab === 'expired' });
  const acceptedQuery = useNurseRequestInbox('accepted_awaiting_payment', 1, { enabled: tab === 'answered' });
  const convertedQuery = useNurseRequestInbox('converted', 1, { enabled: tab === 'answered' });
  const rejectedQuery = useNurseRequestInbox('rejected_by_nurse', 1, { enabled: tab === 'answered' });

  const onTabChange = (_event: React.SyntheticEvent, next: InboxTab) => setTab(next);

  const answeredLoading = acceptedQuery.isLoading || convertedQuery.isLoading || rejectedQuery.isLoading;
  const answeredError = acceptedQuery.isError || convertedQuery.isError || rejectedQuery.isError;
  const answeredItems = [
    ...(acceptedQuery.data?.items ?? []),
    ...(convertedQuery.data?.items ?? []),
    ...(rejectedQuery.data?.items ?? []),
  ];
  const retryAnswered = () => {
    acceptedQuery.refetch();
    convertedQuery.refetch();
    rejectedQuery.refetch();
  };

  const active =
    tab === 'pending'
      ? {
          items: pendingQuery.data?.items ?? [],
          isLoading: pendingQuery.isLoading,
          isError: pendingQuery.isError,
          refetch: pendingQuery.refetch,
          page: pendingPage,
          pageCount: Math.max(1, Math.ceil((pendingQuery.data?.total ?? 0) / (pendingQuery.data?.pageSize || 1))),
          onPageChange: setPendingPage,
        }
      : tab === 'expired'
        ? {
            items: expiredQuery.data?.items ?? [],
            isLoading: expiredQuery.isLoading,
            isError: expiredQuery.isError,
            refetch: expiredQuery.refetch,
            page: expiredPage,
            pageCount: Math.max(1, Math.ceil((expiredQuery.data?.total ?? 0) / (expiredQuery.data?.pageSize || 1))),
            onPageChange: setExpiredPage,
          }
        : {
            items: answeredItems,
            isLoading: answeredLoading,
            isError: answeredError,
            refetch: retryAnswered,
            page: 1,
            pageCount: 1,
            onPageChange: () => {},
          };

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

      <Tabs value={tab} onChange={onTabChange} variant="scrollable" scrollButtons="auto" allowScrollButtonsMobile>
        <Tab value="pending" label={t('nurse_inbox_tab_pending')} sx={{ textTransform: 'none' }} />
        <Tab value="answered" label={t('nurse_inbox_tab_answered')} sx={{ textTransform: 'none' }} />
        <Tab value="expired" label={t('nurse_inbox_tab_expired')} sx={{ textTransform: 'none' }} />
      </Tabs>

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

      {tab !== 'answered' ? (
        <Pager
          page={active.page}
          pageCount={active.pageCount}
          onPrev={() => active.onPageChange(Math.max(1, active.page - 1))}
          onNext={() => active.onPageChange(Math.min(active.pageCount, active.page + 1))}
        />
      ) : null}
    </Box>
  );
}

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

  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)}`;
  const hasPricedService = Boolean(item.variantLabel);

  return (
    <AppLink to={`/${locale}${ROUTES.NURSE_REQUESTS}/${item.id}`} color="inherit" underline="none" sx={{ display: 'block' }}>
      <SurfaceCard data-request-status={item.status}>
        <Stack sx={{ gap: 1.5 }}>
          <Stack direction="row" sx={{ justifyContent: 'space-between', alignItems: 'flex-start', gap: 2 }}>
            <Stack sx={{ gap: 0.5, minWidth: 0 }}>
              {hasPricedService ? (
                <>
                  <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
                    {item.variantLabel}
                  </Typography>
                  <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                    {item.counterpartyName}
                  </Typography>
                </>
              ) : (
                <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
                  {item.counterpartyName}
                </Typography>
              )}
              <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                {whenLabel}
              </Typography>
            </Stack>
            {item.status === 'pending_nurse_response' ? (
              <CountdownTimer
                deadlineIso={item.nurseResponseDeadlineAt}
                label={t('inbox_countdown_pill_label')}
                elapsedText={t('response_elapsed')}
                warnThresholdSeconds={WARN_THRESHOLD_SECONDS}
                urgentThresholdSeconds={URGENT_THRESHOLD_SECONDS}
                coarseLabel={(minutes) => coarseResponseLabel(minutes, t)}
                size="sm"
              />
            ) : null}
          </Stack>

          <Stack direction="row" sx={{ gap: 1, flexWrap: 'wrap' }}>
            {item.requiredCaregiverGender ? (
              <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 }}
              />
            ) : null}
          </Stack>

          {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}
        </Stack>
      </SurfaceCard>
    </AppLink>
  );
}
