'use client';
import { Suspense, useCallback, useMemo, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useLocale, useTranslations } from 'next-intl';
import { MenuItem, Stack, TextField, Typography } from '@mui/material';
import { AppButton, AppLoading, EmptyState, ErrorState, NurseResultCard } from '@/components';
import { ROUTES } from '@/constants';
import { useNurseSearch } from '@/services/search';
import { searchParamsToFilters } from '@/services/search/filterParams';
import { SEARCH_PAGE_SIZE } from '@/services/search/constants';
import type { NurseSearchResult } from '@/services/search/types';

/**
 * C2 — Results (نتایج جستجو): the rating-sorted list of **only verified, accepting** nurses for the
 * carried filter set. The filter set lives in the URL (the deep-linkable, back/forward-safe cache key),
 * so returning to a prior filter URL is a cache hit with zero network calls (`useNurseSearch` +
 * `keepPreviousData`). Renders all four states (loading skeletons / empty "relax filters" / error-retry
 * / populated). Tapping a card opens C3, carrying the nurse + variant + gender intent.
 */
export default function SearchResultsPage() {
  return (
    <Suspense fallback={<AppLoading />}>
      <ResultsScreen />
    </Suspense>
  );
}

function ResultsScreen() {
  const t = useTranslations('search');
  const tc = useTranslations('common');
  const locale = useLocale();
  const router = useRouter();
  const params = useSearchParams();

  const [pageSize, setPageSize] = useState(SEARCH_PAGE_SIZE);

  // The URL is the source of truth for the filter set; grow only the page size for "load more".
  const filters = useMemo(() => ({ ...searchParamsToFilters(params), pageSize }), [params, pageSize]);
  const dateIntent = params.get('date') ?? undefined;

  const { data, isLoading, isError, isFetching, refetch } = useNurseSearch(filters);
  const items = data?.items ?? [];
  const total = data?.total ?? 0;
  const hasMore = items.length < total;

  const openProfile = useCallback(
    (nurse: NurseSearchResult) => {
      const query = new URLSearchParams();
      query.set('variant_id', String(nurse.variantId));
      query.set('service_category_id', String(filters.serviceCategoryId));
      query.set('city_id', String(filters.cityId));
      if (filters.nurseGender) query.set('required_gender', filters.nurseGender);
      if (dateIntent) query.set('date', dateIntent);
      router.push(`/${locale}${ROUTES.SEARCH_NURSE}/${nurse.nurseId}?${query.toString()}`);
    },
    [router, locale, filters.serviceCategoryId, filters.cityId, filters.nurseGender, dateIntent],
  );

  const backToFilters = () => router.push(`/${locale}${ROUTES.SEARCH}`);

  return (
    <Stack sx={{ gap: 2 }}>
      <Stack direction="row" sx={{ gap: 2, alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap' }}>
        <Typography variant="h6" component="h1">
          {isLoading ? t('results_loading_title') : t('results_count', { count: total })}
        </Typography>
        {/* Rating is the only MVP sort; rendered as a control with a single option. Other sorts DEFERRED. */}
        <TextField select size="small" label={t('sort_label')} value="rating" sx={{ minWidth: 160 }}>
          <MenuItem value="rating">{t('sort_rating')}</MenuItem>
        </TextField>
      </Stack>

      {isLoading ? (
        <Stack sx={{ gap: 1.5 }}>
          {[0, 1, 2, 3].map((key) => (
            <NurseResultCard.Skeleton key={key} />
          ))}
        </Stack>
      ) : isError ? (
        <ErrorState message={t('results_error')} retryLabel={tc('retry')} onRetry={() => refetch()} />
      ) : items.length === 0 ? (
        <RelaxFiltersEmptyState onRelax={backToFilters} />
      ) : (
        <Stack sx={{ gap: 1.5 }}>
          {items.map((nurse) => (
            <NurseResultCard key={`${nurse.nurseId}-${nurse.variantId}`} nurse={nurse} onSelect={openProfile} />
          ))}
          {hasMore ? (
            <AppButton
              variant="outlined"
              color="primary"
              onClick={() => setPageSize((size) => size + SEARCH_PAGE_SIZE)}
              disabled={isFetching}
              sx={{ alignSelf: 'center' }}
            >
              {t('load_more')}
            </AppButton>
          ) : null}
        </Stack>
      )}
    </Stack>
  );
}

/** The "no nurses match → relax your filters" state with concrete, product-aligned suggestions. */
function RelaxFiltersEmptyState({ onRelax }: { onRelax: () => void }) {
  const t = useTranslations('search');
  return (
    <EmptyState
      icon="search"
      title={t('empty_title')}
      body={
        <Stack sx={{ gap: 0.5 }}>
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {t('empty_suggest_gender')}
          </Typography>
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {t('empty_suggest_district')}
          </Typography>
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {t('empty_suggest_city')}
          </Typography>
        </Stack>
      }
      action={
        <AppButton variant="contained" color="primary" onClick={onRelax} startIcon="tune">
          {t('empty_cta')}
        </AppButton>
      }
    />
  );
}
