'use client';
import { FunctionComponent, useState } from 'react';
import Chip from '@mui/material/Chip';
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 { ticketThreadPath } from '@/constants';
import { useMyTickets } from '@/services/tickets';
import { TICKETS_PAGE_SIZE } from '@/services/tickets/constants';
import type { TicketStatus } from '@/services/tickets/types';
import { formatRelativeTime, formatShamsiDate } from '@/utils';
import { authorLabelKey } from './authorLabel';
import ContactSupportDialog from './ContactSupportDialog';
import EmergencyPlaybookRow from './EmergencyPlaybookRow';
import TicketListCard from './TicketListCard';

export interface TicketInboxScreenProps {
  role: 'customer' | 'nurse';
}

/** Status filter chips — `undefined` (همه) plus every `TicketStatus`, in display order. */
const STATUS_FILTERS: Array<TicketStatus | undefined> = [undefined, 'open', 'closed'];

/**
 * The "My Tickets" inbox — a status filter chip row, the compact emergency playbook row, a "Contact
 * support" CTA that opens a new ticket (and shows its `referenceCode`), and the paginated ticket list.
 * Cards show the **`referenceCode`** prominently, the status chip, an unread indicator + last-message
 * preview + relative last-activity time (mock-tolerant: they degrade gracefully when the real API hasn't
 * shipped the enrichment fields yet, REQ-059), and a null-safe linked-booking/refund hint. Empty /
 * loading-skeleton / error→retry states. Shared by the customer and nurse inbox pages (role decides the
 * thread route + the ticket shell, not the components).
 * @component TicketInboxScreen
 */
const TicketInboxScreen: FunctionComponent<TicketInboxScreenProps> = ({ role }) => {
  const t = useTranslations('tickets');
  const locale = useLocale();
  const router = useRouter();
  const [dialogOpen, setDialogOpen] = useState(false);
  const [status, setStatus] = useState<TicketStatus | undefined>(undefined);
  const [limit, setLimit] = useState(TICKETS_PAGE_SIZE);

  const { data, isLoading, isError, isFetching, refetch } = useMyTickets({ status, pageSize: limit, page: 1 });
  const tickets = data?.items ?? [];
  const total = data?.total ?? 0;

  const selectStatus = (next: TicketStatus | undefined) => {
    setStatus(next);
    setLimit(TICKETS_PAGE_SIZE);
  };

  const openThread = (ticketId: number) => router.push(`/${locale}${ticketThreadPath(role, ticketId)}`);

  return (
    <Stack sx={{ gap: 2, maxWidth: 720, mx: 'auto', width: '100%' }}>
      <Stack direction="row" sx={{ alignItems: 'center', justifyContent: 'space-between', gap: 1 }}>
        <Typography variant="h6" sx={{ fontWeight: 800 }}>
          {t('title')}
        </Typography>
        <AppButton
          variant="contained"
          color="primary"
          startIcon="support"
          onClick={() => setDialogOpen(true)}
        >
          {t('contact_support')}
        </AppButton>
      </Stack>

      <EmergencyPlaybookRow onOpenTicket={() => setDialogOpen(true)} />

      <Stack direction="row" sx={{ gap: 1, flexWrap: 'wrap' }}>
        {STATUS_FILTERS.map((filter) => (
          <Chip
            key={filter ?? 'all'}
            label={filter ? t(`status_${filter}`) : t('filter_all')}
            onClick={() => selectStatus(filter)}
            color={status === filter ? 'primary' : 'default'}
            variant={status === filter ? 'filled' : 'outlined'}
          />
        ))}
      </Stack>

      {isLoading ? (
        <Stack sx={{ gap: 1 }}>
          {[0, 1, 2].map((i) => (
            <Skeleton key={i} variant="rounded" height={96} />
          ))}
        </Stack>
      ) : isError ? (
        <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('error_body')}
          </Typography>
          <AppButton variant="outlined" color="primary" onClick={() => refetch()}>
            {t('retry')}
          </AppButton>
        </Stack>
      ) : tickets.length === 0 ? (
        <Stack sx={{ gap: 1, alignItems: 'center', py: 6 }}>
          <AppIcon icon="support" size={36} color="var(--bal-primary)" />
          <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
            {t('empty_title')}
          </Typography>
          <Typography variant="body2" sx={{ color: 'var(--bal-text-secondary)' }}>
            {t('empty_body')}
          </Typography>
        </Stack>
      ) : (
        <Stack sx={{ gap: 1 }}>
          {tickets.map((ticket) => (
            <TicketListCard
              key={ticket.id}
              ticket={ticket}
              categoryLabel={t(`category_${ticket.category}`)}
              statusLabel={t(`status_${ticket.status}`)}
              timeLabel={formatRelativeTime(ticket.lastMessageAt ?? ticket.createdAt, locale, formatShamsiDate)}
              previewLabel={
                ticket.lastMessagePreview
                  ? ticket.lastAuthorRole
                    ? `${t(authorLabelKey(ticket.lastAuthorRole))}: ${ticket.lastMessagePreview}`
                    : ticket.lastMessagePreview
                  : null
              }
              linkedBookingLabel={ticket.bookingId != null ? t('linked_booking', { id: ticket.bookingId }) : null}
              linkedRefundLabel={ticket.refundId != null ? t('linked_refund', { id: ticket.refundId }) : null}
              onOpen={() => openThread(ticket.id)}
            />
          ))}
          {total > tickets.length ? (
            <AppButton
              variant="text"
              color="primary"
              onClick={() => setLimit((current) => current + TICKETS_PAGE_SIZE)}
              disabled={isFetching}
              sx={{ alignSelf: 'center' }}
            >
              {t('load_more')}
            </AppButton>
          ) : null}
        </Stack>
      )}

      <ContactSupportDialog open={dialogOpen} onClose={() => setDialogOpen(false)} role={role} defaultCategory="support" />
    </Stack>
  );
};

export default TicketInboxScreen;
