'use client';
import { FunctionComponent, useState } from 'react';
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 { formatShamsiDateTime } from '@/utils';
import ContactSupportDialog from './ContactSupportDialog';
import EmergencyBanner from './EmergencyBanner';
import TicketListCard from './TicketListCard';

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

/**
 * The "My Tickets" inbox — the emergency playbook banner (support entry), 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, 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 { data, isLoading, isError, refetch } = useMyTickets({});
  const tickets = data?.items ?? [];

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

  return (
    <Stack sx={{ gap: 2, maxWidth: 640, 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>

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

      {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={formatShamsiDateTime(ticket.lastMessageAt ?? ticket.createdAt, locale)}
              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)}
            />
          ))}
        </Stack>
      )}

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

export default TicketInboxScreen;
