'use client';
import { Suspense } from 'react';
import { useRouter } from 'next/navigation';
import { useLocale, useTranslations } from 'next-intl';
import { Box, MenuItem, Skeleton, Stack, TextField } from '@mui/material';
import { AppButton, AppLoading, StatusChip } from '@/components';
import type { StatusKind } from '@/components';
import { AdminDataTable, AdminEmptyState, AdminErrorState, AdminPageHeader, AdminPager } from '@/components/admin';
import type { AdminTableColumn } from '@/components/admin';
import { partnerBookingDetailPath } from '@/constants';
import { useAdminListState } from '@/hooks';
import { formatShamsiDate } from '@/utils';
import type { SponsoredBooking, SponsoredBookingFilters } 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 wire codes). */
const BOOKING_STATUS_OPTIONS = ['pending_payment', 'confirmed', 'in_progress', 'completed', 'disputed', 'closed', 'cancelled'] as const;

/** Booking status → chip tone. Progression reads left-to-right calmer→done; disputed/cancelled are the alarm tier. */
const PARTNER_BOOKING_STATUS_KIND: Record<string, StatusKind> = {
  pending_payment: 'pending',
  confirmed: 'info',
  in_progress: 'active',
  completed: 'verified',
  disputed: 'rejected',
  closed: 'neutral',
  cancelled: 'rejected',
};

const EMPTY_FILTERS: SponsoredBookingFilters = {};

function parseFilters(params: URLSearchParams): SponsoredBookingFilters {
  return { status: params.get('status') ?? undefined };
}

function serializeFilters(filters: SponsoredBookingFilters): Record<string, string> {
  return filters.status ? { status: filters.status } : {};
}

/**
 * Partner portal — sponsored bookings (f15). The read-only list of bookings the signed-in center legally
 * covers (portal scope; server-enforced tenancy). A status filter (applied+page mirrored into the URL via
 * `useAdminListState`, ui-phase-11) and a dense table of id/patient/date/status — every status label is
 * translated (`bstatus_*`), never the raw wire code. Rows link to a scoped read-only detail (REQ-064).
 * `useSearchParams` (inside `useAdminListState`) needs a `<Suspense>` boundary.
 */
export default function PartnerBookingsPage() {
  return (
    <Suspense fallback={<AppLoading />}>
      <PartnerBookingsScreen />
    </Suspense>
  );
}

function PartnerBookingsScreen() {
  const t = useTranslations('partner');
  const ta = useTranslations('admin');
  const locale = useLocale();
  const router = useRouter();

  const { draft, setDraft, applied, page, apply, clear, goToPage } = useAdminListState<SponsoredBookingFilters>({
    parse: parseFilters,
    serialize: serializeFilters,
    empty: EMPTY_FILTERS,
  });

  const bookings = useMySponsoredBookings(applied, page);

  const items = bookings.data?.items ?? [];
  const total = bookings.data?.total ?? 0;
  const pageCount = Math.max(1, Math.ceil(total / PARTNER_PAGE_SIZE));
  const from = items.length === 0 ? 0 : (page - 1) * PARTNER_PAGE_SIZE + 1;
  const to = items.length === 0 ? 0 : from + items.length - 1;

  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) => (
        <StatusChip status={PARTNER_BOOKING_STATUS_KIND[b.status] ?? 'neutral'} label={t(`bstatus_${b.status}`)} />
      ),
    },
  ];

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      <AdminPageHeader title={t('bookings_title')} />

      <Stack
        direction="row"
        sx={{ gap: 1.5, flexWrap: 'wrap', alignItems: 'center', p: 2, border: '1px solid', borderColor: 'divider', borderRadius: 'var(--bal-radius-md)' }}
      >
        <TextField
          select
          size="small"
          label={t('bookings_col_status')}
          value={draft.status ?? ''}
          onChange={(e) => setDraft({ status: e.target.value || undefined })}
          sx={{ minWidth: 180 }}
        >
          <MenuItem value="">{ta('filter_all')}</MenuItem>
          {BOOKING_STATUS_OPTIONS.map((s) => (
            <MenuItem key={s} value={s}>
              {t(`bstatus_${s}`)}
            </MenuItem>
          ))}
        </TextField>
        <AppButton variant="contained" color="primary" onClick={apply}>
          {ta('apply')}
        </AppButton>
        <AppButton variant="text" color="inherit" onClick={clear}>
          {ta('clear')}
        </AppButton>
      </Stack>

      {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')}
          onRowClick={(b) => router.push(`/${locale}${partnerBookingDetailPath(b.bookingId)}`)}
          footer={ta('showing_range', { from, to, total })}
        />
      )}

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