'use client';
import { FunctionComponent } from 'react';
import Box from '@mui/material/Box';
import ButtonBase from '@mui/material/ButtonBase';
import Skeleton from '@mui/material/Skeleton';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import StatusChip from '@/components/StatusChip';
import { AppIcon } from '@/components/common';
import type { TicketSummary } from '@/services/tickets/types';
import { ticketCategoryIcon, ticketStatusKind } from './statusKind';

export interface TicketListCardProps {
  ticket: TicketSummary;
  /** Translated category label (also the subject fallback when `subject` is null). */
  categoryLabel: string;
  /** Translated status label. */
  statusLabel: string;
  /** Pre-formatted last-activity time — the caller owns locale. */
  timeLabel: string;
  /** e.g. "رزرو #۵۰۰۱" — rendered only when the ticket is booking-linked (null-safe). */
  linkedBookingLabel?: string | null;
  /** e.g. "بازپرداخت #۹۰۰۱" — rendered only when refund-linked (null-safe). */
  linkedRefundLabel?: string | null;
  onOpen: () => void;
}

/**
 * One ticket in the "My Tickets" inbox. The **`referenceCode` is shown prominently** (§5 — it's what a user
 * quotes to support); the status chip reuses the shared `StatusChip`, the linked-booking/refund hint renders
 * only when present (null-safe), and an **unread indicator** (a count dot + bolded subject) shows when the
 * ticket has unread activity. Purely presentational — the caller supplies translated labels + the formatted
 * time and handles navigation via `onOpen`.
 * @component TicketListCard
 */
const TicketListCard: FunctionComponent<TicketListCardProps> = ({
  ticket,
  categoryLabel,
  statusLabel,
  timeLabel,
  linkedBookingLabel,
  linkedRefundLabel,
  onOpen,
}) => {
  const hasUnread = (ticket.unreadCount ?? 0) > 0;
  const subject = ticket.subject?.trim() || categoryLabel;

  return (
    <ButtonBase
      onClick={onOpen}
      data-testid="ticket-card"
      sx={{
        display: 'block',
        width: '100%',
        textAlign: 'start',
        p: 2,
        borderRadius: 2,
        border: '1px solid',
        borderColor: 'divider',
        bgcolor: 'var(--bal-bg-paper)',
      }}
    >
      <Stack sx={{ gap: 0.75, width: '100%' }}>
        <Stack direction="row" sx={{ alignItems: 'center', gap: 1 }}>
          <AppIcon icon={ticketCategoryIcon(ticket.category)} size={18} color="var(--bal-primary)" />
          <Typography variant="subtitle2" sx={{ fontWeight: hasUnread ? 800 : 600, flexGrow: 1 }}>
            {subject}
          </Typography>
          {hasUnread ? (
            <Box
              data-testid="ticket-unread"
              sx={{
                minWidth: 20,
                height: 20,
                px: 0.5,
                borderRadius: 10,
                bgcolor: 'var(--bal-primary)',
                color: 'var(--bal-primary-contrast)',
                fontSize: 12,
                fontWeight: 700,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              {ticket.unreadCount}
            </Box>
          ) : null}
          <StatusChip status={ticketStatusKind(ticket.status)} label={statusLabel} />
        </Stack>

        <Typography
          variant="caption"
          sx={{ fontWeight: 700, letterSpacing: 0.5, color: 'var(--bal-primary)', direction: 'ltr', alignSelf: 'flex-start' }}
        >
          {ticket.referenceCode}
        </Typography>

        <Stack direction="row" sx={{ alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
          {linkedBookingLabel ? (
            <Typography variant="caption" sx={{ color: 'var(--bal-text-secondary)' }}>
              {linkedBookingLabel}
            </Typography>
          ) : null}
          {linkedRefundLabel ? (
            <Typography variant="caption" sx={{ color: 'var(--bal-text-secondary)' }}>
              {linkedRefundLabel}
            </Typography>
          ) : null}
          <Typography variant="caption" sx={{ color: 'var(--bal-text-secondary)', marginInlineStart: 'auto' }}>
            {timeLabel}
          </Typography>
        </Stack>
      </Stack>
    </ButtonBase>
  );
};

/** Matches the real card's anatomy (icon/subject/status row, reference line, footer row) for the ticket inbox. */
const TicketListCardSkeleton: FunctionComponent = () => (
  <Box sx={{ p: 2, borderRadius: 2, border: '1px solid', borderColor: 'divider', bgcolor: 'var(--bal-bg-paper)' }}>
    <Stack sx={{ gap: 0.75 }}>
      <Stack direction="row" sx={{ alignItems: 'center', gap: 1 }}>
        <Skeleton variant="circular" width={18} height={18} />
        <Skeleton variant="text" width="50%" height={22} sx={{ flexGrow: 1 }} />
        <Skeleton variant="rounded" width={64} height={22} />
      </Stack>
      <Skeleton variant="text" width={110} height={16} />
      <Skeleton variant="text" width="70%" height={16} />
    </Stack>
  </Box>
);

export default Object.assign(TicketListCard, { Skeleton: TicketListCardSkeleton });
