'use client';
import { useMemo, useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useRouter } from 'next/navigation';
import { Box, Collapse, Paper, Skeleton, Stack, Tab, Tabs, Typography } from '@mui/material';
import { AppButton, AppIcon, EarningsBalanceHeader, EarningsRow, EmptyState, ErrorState } from '@/components';
import { nurseBookingDetailPath, nursePayoutDetailPath } from '@/constants';
import { formatNumber } from '@/utils';
import { PAYOUTS_PAGE_SIZE } from '@/services/payouts/constants';
import { EARNINGS_STATES, type EarningsState } from '@/services/payouts/types';
import { useNurseEarnings, useNurseEarningsBalance } from '@/services/payouts';

type EarningsTab = 'all' | EarningsState;
const TABS: readonly EarningsTab[] = ['all', ...EARNINGS_STATES];

/**
 * Nurse earnings home (f12) — the read-only "where is my money?" surface. Shows the ledger-derived net
 * payable balance + four-bucket breakdown (`EarningsBalanceHeader`), a plain-Persian explainer of the
 * weekly cadence + dispute-window gate, and a state-segmented earnings list. Each row deep-links to the f8
 * booking detail (never rebuilt here) and, when paid, to the payout detail. The server owns eligibility and
 * amounts; this screen only renders them.
 */
export default function NurseEarningsPage() {
  const t = useTranslations('payouts');
  const locale = useLocale();
  const router = useRouter();

  const [tab, setTab] = useState<EarningsTab>('all');
  const [page, setPage] = useState(1);
  const [explainerOpen, setExplainerOpen] = useState(false);

  const stateFilter = tab === 'all' ? undefined : tab;
  const balance = useNurseEarningsBalance();
  const earnings = useNurseEarnings(stateFilter, page);

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

  const openBooking = (bookingId: number) => router.push(`/${locale}${nurseBookingDetailPath(bookingId)}`);
  const openPayout = (payoutId: number) => router.push(`/${locale}${nursePayoutDetailPath(payoutId)}`);

  const onTabChange = (_: React.SyntheticEvent, next: EarningsTab) => {
    setTab(next);
    setPage(1);
  };

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      <Box>
        <Typography variant="h5" component="h1">
          {t('title')}
        </Typography>
        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          {t('subtitle')}
        </Typography>
      </Box>

      {balance.isLoading ? (
        <Skeleton variant="rounded" height={200} />
      ) : balance.isError ? (
        <ErrorState message={t('balance_error')} retryLabel={t('retry')} onRetry={() => balance.refetch()} />
      ) : balance.data ? (
        <EarningsBalanceHeader summary={balance.data} />
      ) : null}

      <ExplainerCard open={explainerOpen} onToggle={() => setExplainerOpen((v) => !v)} />

      <Stack sx={{ gap: 2 }}>
        <Tabs
          value={tab}
          onChange={onTabChange}
          variant="scrollable"
          scrollButtons="auto"
          allowScrollButtonsMobile
        >
          {TABS.map((value) => (
            <Tab key={value} value={value} label={t(`tab_${value}`)} sx={{ textTransform: 'none' }} />
          ))}
        </Tabs>

        {earnings.isLoading ? (
          <Stack sx={{ gap: 2 }}>
            {[0, 1].map((k) => (
              <Skeleton key={k} variant="rounded" height={200} />
            ))}
          </Stack>
        ) : earnings.isError ? (
          <ErrorState message={t('list_error')} retryLabel={t('retry')} onRetry={() => earnings.refetch()} />
        ) : items.length === 0 ? (
          <EmptyState icon="earnings" title={t('list_empty_title')} body={t('list_empty_body')} />
        ) : (
          <Stack sx={{ gap: 2 }}>
            {items.map((item) => (
              <EarningsRow key={item.bookingId} item={item} onViewBooking={openBooking} onViewPayout={openPayout} />
            ))}
          </Stack>
        )}

        <Pager
          page={page}
          pageCount={pageCount}
          onPrev={() => setPage((p) => Math.max(1, p - 1))}
          onNext={() => setPage((p) => Math.min(pageCount, p + 1))}
        />
      </Stack>
    </Box>
  );
}

/** Collapsible "how payouts work" — the cadence + dispute-window + method-invariant copy (both locales). */
function ExplainerCard({ open, onToggle }: { open: boolean; onToggle: () => void }) {
  const t = useTranslations('payouts');
  const points = useMemo(() => ['explainer_point_1', 'explainer_point_2', 'explainer_point_3'] as const, []);

  return (
    <Paper
      elevation={0}
      sx={{
        p: 2,
        borderRadius: 2,
        border: '1px solid',
        borderColor: 'divider',
        borderInlineStart: '3px solid',
        borderInlineStartColor: 'var(--bal-info)',
      }}
    >
      <Stack
        direction="row"
        sx={{ gap: 1, alignItems: 'center', justifyContent: 'space-between', cursor: 'pointer' }}
        onClick={onToggle}
      >
        <Stack direction="row" sx={{ gap: 0.75, alignItems: 'center' }}>
          <AppIcon icon="info" size={18} color="var(--bal-info)" />
          <Typography variant="subtitle2" sx={{ fontWeight: 700 }}>
            {t('explainer_title')}
          </Typography>
        </Stack>
        <AppIcon icon={open ? 'visibilityoff' : 'visibilityon'} size={18} color="var(--bal-text-secondary)" />
      </Stack>
      <Collapse in={open}>
        <Stack component="ul" sx={{ gap: 0.75, mt: 1.5, mb: 0, pl: 2.5 }}>
          {points.map((key) => (
            <Typography key={key} component="li" variant="body2" sx={{ color: 'text.secondary' }}>
              {t(key)}
            </Typography>
          ))}
        </Stack>
      </Collapse>
    </Paper>
  );
}

/** Prev/next pager — rendered only when there is more than one page. */
function Pager({
  page,
  pageCount,
  onPrev,
  onNext,
}: {
  page: number;
  pageCount: number;
  onPrev: () => void;
  onNext: () => void;
}) {
  const t = useTranslations('payouts');
  const locale = useLocale();
  if (pageCount <= 1) return null;
  const fmt = (n: number) => formatNumber(n, locale);

  return (
    <Stack direction="row" sx={{ gap: 1, alignItems: 'center', justifyContent: 'center' }}>
      <AppButton variant="text" color="primary" onClick={onPrev} disabled={page <= 1}>
        {t('page_prev')}
      </AppButton>
      <Typography variant="body2" sx={{ color: 'text.secondary' }}>
        {t('page_indicator', { page: fmt(page), total: fmt(pageCount) })}
      </Typography>
      <AppButton variant="text" color="primary" onClick={onNext} disabled={page >= pageCount}>
        {t('page_next')}
      </AppButton>
    </Stack>
  );
}
