'use client';
import { useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { Box, Chip, MenuItem, Skeleton, Stack, TextField } from '@mui/material';
import { AdminDataTable, AdminEmptyState, AdminErrorState, AdminPageHeader, AdminPager } from '@/components/admin';
import type { AdminTableColumn } from '@/components/admin';
import { formatShamsiDate } from '@/utils';
import type { SponsoredBooking } from '@/services/partnerCenter/types';
import { PARTNER_PAGE_SIZE } from '@/services/partnerCenter/constants';
import { useMySponsoredBookings } from '@/services/partnerCenter';

/**
 * Booking lifecycle codes the center may legally cover — the read-only filter options. Stable string codes
 * (the wire enum); labels are the codes themselves since `status` is a free-form summary field, not a
 * localized enum in the portal contract.
 */
const BOOKING_STATUS_OPTIONS = ['pending_payment', 'confirmed', 'in_progress', 'completed', 'disputed', 'closed', 'cancelled'] as const;

/**
 * Partner portal — sponsored bookings (f15). The read-only list of bookings the signed-in center legally
 * covers (portal scope; server-enforced tenancy). An optional status filter (filter+page keyed cache) and a
 * dense table of id/patient/date/status. No PII beyond the summary; the center never sees clinical detail.
 */
export default function PartnerBookingsPage() {
  const t = useTranslations('partner');
  const ta = useTranslations('admin');
  const locale = useLocale();

  const [status, setStatus] = useState<string>('');
  const [page, setPage] = useState(1);

  const filters = { status: status || undefined };
  const bookings = useMySponsoredBookings(filters, page);

  const items = bookings.data?.items ?? [];
  const pageCount = Math.max(1, Math.ceil((bookings.data?.total ?? 0) / PARTNER_PAGE_SIZE));

  const columns: AdminTableColumn<SponsoredBooking>[] = [
    { key: 'id', header: t('bookings_col_id'), render: (b) => `#${b.bookingId}` },
    { key: 'patient', header: t('bookings_col_patient'), render: (b) => b.patientName },
    { key: 'date', header: t('bookings_col_date'), render: (b) => formatShamsiDate(b.scheduledDate, locale) },
    {
      key: 'status',
      header: t('bookings_col_status'),
      render: (b) => <Chip size="small" variant="outlined" label={b.status} />,
    },
  ];

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      <AdminPageHeader
        title={t('bookings_title')}
        actions={
          <TextField
            select
            size="small"
            label={t('bookings_col_status')}
            value={status}
            onChange={(e) => {
              setStatus(e.target.value);
              setPage(1);
            }}
            sx={{ minWidth: 180 }}
          >
            <MenuItem value="">{ta('filter_all')}</MenuItem>
            {BOOKING_STATUS_OPTIONS.map((s) => (
              <MenuItem key={s} value={s}>
                {s}
              </MenuItem>
            ))}
          </TextField>
        }
      />

      {bookings.isLoading ? (
        <Stack sx={{ gap: 2 }}>
          {[0, 1, 2].map((k) => (
            <Skeleton key={k} variant="rounded" height={56} />
          ))}
        </Stack>
      ) : bookings.isError ? (
        <AdminErrorState message={ta('error_generic')} retryLabel={ta('retry')} onRetry={() => bookings.refetch()} />
      ) : items.length === 0 ? (
        <AdminEmptyState icon="bookings" title={t('bookings_empty')} />
      ) : (
        <AdminDataTable
          columns={columns}
          rows={items}
          getRowKey={(b) => b.bookingId}
          ariaLabel={t('bookings_title')}
        />
      )}

      <AdminPager
        page={page}
        pageCount={pageCount}
        onPrev={() => setPage((p) => Math.max(1, p - 1))}
        onNext={() => setPage((p) => Math.min(pageCount, p + 1))}
        prevLabel={ta('prev_page')}
        nextLabel={ta('next_page')}
        indicator={ta('page_indicator', { page })}
      />
    </Box>
  );
}
