'use client';
import { FunctionComponent } from 'react';
import Box from '@mui/material/Box';
import Chip from '@mui/material/Chip';
import Paper from '@mui/material/Paper';
import Skeleton from '@mui/material/Skeleton';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { useLocale, useTranslations } from 'next-intl';
import { useRouter } from 'next/navigation';
import AppButton from '@/components/common/AppButton';
import { AppIcon } from '@/components/common';
import StatusChip from '@/components/StatusChip';
import { ROUTES, nurseBookingDetailPath, ticketsBasePath } from '@/constants';
import { useTicket } from '@/services/tickets';
import MessageComposer from './MessageComposer';
import TicketMessageList from './TicketMessageList';
import { ticketCategoryIcon, ticketStatusKind } from './statusKind';

export interface TicketThreadScreenProps {
  role: 'customer' | 'nurse';
  ticketId: number;
}

/**
 * A ticket thread — the role-aware bubble stream + a sticky composer. The header shows the **`referenceCode`
 * prominently**, the category, the status chip, and (when present) a linked-booking chip. Closed tickets show
 * a notice instead of the composer. **No internal-note affordance anywhere** (§5). Shared by the customer and
 * nurse thread pages (role decides the back/booking route + composer entitlement, not the components).
 * @component TicketThreadScreen
 */
const TicketThreadScreen: FunctionComponent<TicketThreadScreenProps> = ({ role, ticketId }) => {
  const t = useTranslations('tickets');
  const locale = useLocale();
  const router = useRouter();
  const { data: ticket, isLoading, isError, refetch } = useTicket(ticketId);

  const goBack = () => router.push(`/${locale}${ticketsBasePath(role)}`);
  const goToBooking = (bookingId: number) => {
    const path = role === 'nurse' ? nurseBookingDetailPath(bookingId) : `${ROUTES.BOOKINGS}/${bookingId}`;
    router.push(`/${locale}${path}`);
  };

  return (
    <Stack sx={{ gap: 2, maxWidth: 720, mx: 'auto', width: '100%' }}>
      <AppButton variant="text" color="primary" onClick={goBack} sx={{ alignSelf: 'flex-start' }}>
        {t('back_to_tickets')}
      </AppButton>

      {isLoading ? (
        <Stack sx={{ gap: 1 }}>
          <Skeleton variant="rounded" height={72} />
          <Skeleton variant="rounded" height={56} sx={{ width: '70%' }} />
          <Skeleton variant="rounded" height={56} sx={{ width: '70%', alignSelf: 'flex-end' }} />
        </Stack>
      ) : isError || !ticket ? (
        <Stack sx={{ gap: 1.5, alignItems: 'center', py: 4 }}>
          <AppIcon icon="error" size={32} color="var(--bal-error)" />
          <Typography variant="body2" sx={{ color: 'var(--bal-text-secondary)' }}>
            {t('thread_error')}
          </Typography>
          <AppButton variant="outlined" color="primary" onClick={() => refetch()}>
            {t('retry')}
          </AppButton>
        </Stack>
      ) : (
        <>
          <Paper elevation={0} sx={{ p: 2, borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
            <Stack sx={{ gap: 1 }}>
              <Stack direction="row" sx={{ alignItems: 'center', gap: 1 }}>
                <AppIcon icon={ticketCategoryIcon(ticket.category)} size={20} color="var(--bal-primary)" />
                <Typography variant="subtitle1" sx={{ fontWeight: 700, flexGrow: 1 }}>
                  {ticket.subject?.trim() || t(`category_${ticket.category}`)}
                </Typography>
                <StatusChip status={ticketStatusKind(ticket.status)} label={t(`status_${ticket.status}`)} />
              </Stack>
              <Stack direction="row" sx={{ alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
                <Typography variant="caption" sx={{ color: 'var(--bal-text-secondary)' }}>
                  {t('ref_code_label')}
                </Typography>
                <Typography variant="body2" sx={{ fontWeight: 800, letterSpacing: 0.5, direction: 'ltr' }}>
                  {ticket.referenceCode}
                </Typography>
                {ticket.bookingId != null ? (
                  <Chip
                    size="small"
                    variant="outlined"
                    icon={<AppIcon icon="bookings" size={14} color="var(--bal-primary)" />}
                    label={t('linked_booking', { id: ticket.bookingId })}
                    onClick={() => goToBooking(ticket.bookingId as number)}
                    sx={{ marginInlineStart: 'auto' }}
                  />
                ) : null}
              </Stack>
            </Stack>
          </Paper>

          <TicketMessageList ticketId={ticketId} />

          <Box
            sx={{
              position: 'sticky',
              bottom: 0,
              bgcolor: 'var(--bal-bg-default)',
              pt: 1,
              pb: 0.5,
            }}
          >
            {ticket.status === 'closed' ? (
              <Typography
                variant="body2"
                sx={{ textAlign: 'center', color: 'var(--bal-text-secondary)', py: 1 }}
              >
                {t('closed_notice')}
              </Typography>
            ) : (
              // Key on ticketId so navigating thread→thread (the App Router reuses the [id] subtree)
              // remounts the composer — its draft + in-flight/failed send state never cross tickets.
              <MessageComposer key={ticketId} ticketId={ticketId} />
            )}
          </Box>
        </>
      )}
    </Stack>
  );
};

export default TicketThreadScreen;
