'use client';
import { useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useParams, useRouter, useSearchParams } from 'next/navigation';
import { Avatar, Box, Chip, Paper, Skeleton, Stack, Tab, Tabs, Typography } from '@mui/material';
import { AppButton, AppIcon, EmptyState, ErrorState, RatingInput, ServicePriceRow, TrustBadge } from '@/components';
import { ROUTES } from '@/constants';
import { ApiError } from '@/lib/api/errors';
import { formatNumber, formatShamsiDate } from '@/utils';
import { useNurseProfile } from '@/services/search';
import type { NurseProfile } from '@/services/search/types';
import { useNurseReviews } from '@/services/reviews';
import type { ReviewListItem } from '@/services/reviews/types';

type ProfileTab = 'services' | 'reviews';

/**
 * C3 — Nurse profile (پروفایل پرستار): identity + trust badges (✓ تاییدشده, نظام پرستاری), attribute
 * chips, and a **tabbed** body — «خدمات» (the priced services list) and «نظرات» (the f13 published-reviews
 * tab: aggregate rating + count + an infinite list). Only `published` reviews are ever requested/rendered.
 * The primary CTA "درخواست رزرو" hands the selected nurse + variant + `required_caregiver_gender` to f7.
 */
export default function NurseProfilePage() {
  const t = useTranslations('search');
  const router = useRouter();
  const locale = useLocale();
  const routeParams = useParams<{ nurseId: string }>();
  const query = useSearchParams();

  const nurseId = Number(routeParams.nurseId);
  const { data: profile, isLoading, isError, error, refetch } = useNurseProfile(
    Number.isInteger(nurseId) && nurseId > 0 ? nurseId : undefined,
  );
  const [tab, setTab] = useState<ProfileTab>('services');

  if (isLoading) return <ProfileSkeleton />;

  if (isError) {
    const notFound = error instanceof ApiError && error.status === 404;
    return notFound ? (
      <EmptyState
        title={t('profile_not_found_title')}
        body={t('profile_not_found_body')}
        action={
          <AppButton variant="outlined" color="primary" onClick={() => router.push(`/${locale}${ROUTES.SEARCH}`)}>
            {t('profile_not_found_cta')}
          </AppButton>
        }
      />
    ) : (
      <ErrorState message={t('profile_error_body')} retryLabel={t('retry')} onRetry={() => refetch()} />
    );
  }

  if (!profile) return null;

  const requestBooking = () => {
    const carriedVariant = query.get('variant_id');
    const variantId = carriedVariant ?? String(profile.services[0]?.variantId ?? '');
    const params = new URLSearchParams();
    params.set('nurse_id', String(profile.nurseId));
    if (variantId) params.set('variant_id', variantId);
    // The same-gender intent chosen on C1, carried BEFORE booking (becomes required_caregiver_gender in f7/b8).
    const requiredGender = query.get('required_gender');
    if (requiredGender) params.set('required_gender', requiredGender);
    const cityId = query.get('city_id');
    if (cityId) params.set('city_id', cityId);
    const categoryId = query.get('service_category_id');
    if (categoryId) params.set('service_category_id', categoryId);
    const date = query.get('date');
    if (date) params.set('date', date);
    router.push(`/${locale}${ROUTES.BOOKING_REQUEST}?${params.toString()}`);
  };

  return (
    <Stack sx={{ gap: 3 }}>
      <ProfileHeader profile={profile} />
      <AttributeChips profile={profile} />

      <Tabs value={tab} onChange={(_, next: ProfileTab) => setTab(next)} sx={{ borderBottom: 1, borderColor: 'divider' }}>
        <Tab value="services" label={t('tab_services')} sx={{ textTransform: 'none', fontWeight: 700 }} />
        <Tab value="reviews" label={t('tab_reviews')} sx={{ textTransform: 'none', fontWeight: 700 }} />
      </Tabs>

      {tab === 'services' ? <ServicesSection profile={profile} /> : <ReviewsPanel nurseId={profile.nurseId} />}

      <AppButton
        color="primary"
        variant="contained"
        size="large"
        onClick={requestBooking}
        startIcon="bookings"
        sx={{ py: 1.5 }}
      >
        {t('request_booking')}
      </AppButton>
    </Stack>
  );
}

function ProfileHeader({ profile }: { profile: NurseProfile }) {
  const t = useTranslations('search');
  const locale = useLocale();
  const name = profile.nurseName.trim() || t('unnamed_nurse');
  const rating = formatNumber(profile.averageRating, locale, {
    minimumFractionDigits: 1,
    maximumFractionDigits: 1,
  });

  return (
    <Stack sx={{ gap: 1.5 }}>
      <Stack direction="row" sx={{ gap: 2, alignItems: 'center' }}>
        <Avatar
          src={profile.avatarUrl ?? undefined}
          sx={{ width: 72, height: 72, bgcolor: 'var(--bal-primary-soft)', color: 'var(--bal-primary)', fontWeight: 700, fontSize: 28 }}
        >
          {name.charAt(0)}
        </Avatar>
        <Stack sx={{ gap: 0.5 }}>
          <Typography variant="h5" component="h1">
            {name}
          </Typography>
          <Stack direction="row" sx={{ gap: 0.5, alignItems: 'center' }}>
            <AppIcon icon="star" size={18} color="var(--bal-warning)" />
            <Typography variant="body2" sx={{ fontWeight: 700 }}>
              {rating}
            </Typography>
            <Typography variant="body2" sx={{ color: 'text.secondary' }}>
              {t('reviews_count', { count: profile.totalReviews })}
            </Typography>
          </Stack>
        </Stack>
      </Stack>

      <Stack direction="row" sx={{ gap: 1, flexWrap: 'wrap' }}>
        <TrustBadge state="verified" />
        {profile.inoMembership ? (
          <Chip
            icon={<AppIcon icon="license" size={16} color="var(--bal-primary)" />}
            label={t('badge_ino')}
            sx={{ backgroundColor: 'var(--bal-primary-soft)', color: 'var(--bal-primary)', fontWeight: 700 }}
          />
        ) : null}
      </Stack>

      {profile.bio ? (
        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          {profile.bio}
        </Typography>
      ) : null}
    </Stack>
  );
}

function AttributeChips({ profile }: { profile: NurseProfile }) {
  const t = useTranslations('search');
  const locale = useLocale();
  const chips: string[] = [];
  if (profile.yearsExperience != null && profile.yearsExperience > 0) {
    const years = formatNumber(profile.yearsExperience, locale);
    chips.push(t('years_experience', { years }));
  }
  for (const code of profile.attributeChips) {
    chips.push(t.has(`specialty_${code}`) ? t(`specialty_${code}`) : code);
  }
  if (chips.length === 0) return null;

  return (
    <Stack direction="row" sx={{ gap: 1, flexWrap: 'wrap' }}>
      {chips.map((label) => (
        <Chip key={label} label={label} variant="outlined" />
      ))}
    </Stack>
  );
}

function ServicesSection({ profile }: { profile: NurseProfile }) {
  const t = useTranslations('search');
  return (
    <Stack sx={{ gap: 1 }}>
      {profile.services.length === 0 ? (
        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          {t('services_empty')}
        </Typography>
      ) : (
        <Box>
          {profile.services.map((service) => (
            <ServicePriceRow
              key={service.variantId}
              displayName={service.displayName}
              priceIrr={service.priceIrr}
              priceUnit={service.priceUnit}
              sessionCount={service.sessionCount}
            />
          ))}
        </Box>
      )}
    </Stack>
  );
}

/**
 * The f13 reviews tab — the aggregate rating + count and an infinite list of **published** reviews. Never
 * requests or renders `pending_moderation`/`hidden`/`rejected` content; the aggregate is the server's
 * recomputed value, not a client sum.
 */
function ReviewsPanel({ nurseId }: { nurseId: number }) {
  const t = useTranslations('reviews');
  const locale = useLocale();
  const { data, isLoading, isError, refetch, fetchNextPage, hasNextPage, isFetchingNextPage } = useNurseReviews(nurseId);

  if (isLoading) {
    return (
      <Stack sx={{ gap: 1.5 }}>
        <Skeleton variant="text" width="40%" />
        <Skeleton variant="rounded" height={88} />
        <Skeleton variant="rounded" height={88} />
      </Stack>
    );
  }

  if (isError) {
    return <ErrorState message={t('load_error')} retryLabel={t('retry')} onRetry={() => refetch()} />;
  }

  const aggregate = data?.pages[0]?.aggregate;
  const items = data?.pages.flatMap((page) => page.reviews.items) ?? [];
  const publishedCount = aggregate?.publishedCount ?? 0;

  if (publishedCount === 0) {
    return (
      <Typography variant="body2" sx={{ color: 'text.secondary' }}>
        {t('reviews_empty')}
      </Typography>
    );
  }

  const average = formatNumber(aggregate?.averageRating ?? 0, locale, {
    minimumFractionDigits: 1,
    maximumFractionDigits: 1,
  });

  return (
    <Stack sx={{ gap: 2 }}>
      <Stack direction="row" sx={{ alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
        <RatingInput value={aggregate?.averageRating ?? 0} readOnly size={20} ariaLabel={t('rating_label')} />
        <Typography variant="h6" component="p" sx={{ fontWeight: 700 }}>
          {average}
        </Typography>
        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          {t('count', { count: publishedCount })}
        </Typography>
      </Stack>

      <Stack sx={{ gap: 1.5 }}>
        {items.map((review) => (
          <ReviewCard key={review.id} review={review} />
        ))}
      </Stack>

      {hasNextPage ? (
        <AppButton
          variant="text"
          color="primary"
          onClick={() => fetchNextPage()}
          disabled={isFetchingNextPage}
          sx={{ alignSelf: 'center' }}
        >
          {isFetchingNextPage ? t('loading') : t('load_more')}
        </AppButton>
      ) : null}
    </Stack>
  );
}

function ReviewCard({ review }: { review: ReviewListItem }) {
  const t = useTranslations('reviews');
  const locale = useLocale();
  return (
    <Paper elevation={0} sx={{ p: 2, border: '1px solid', borderColor: 'divider', borderRadius: 2 }}>
      <Stack direction="row" sx={{ gap: 1, alignItems: 'center', mb: 0.5, flexWrap: 'wrap' }}>
        <RatingInput value={review.rating} readOnly size={16} ariaLabel={t('rating_label')} />
        <Typography variant="caption" sx={{ color: 'text.secondary', marginInlineStart: 'auto' }}>
          {t('author_masked')} · {formatShamsiDate(review.createdAt, locale)}
        </Typography>
      </Stack>
      {review.body ? <Typography variant="body2">{review.body}</Typography> : null}
      {review.tagCodes.length > 0 ? (
        <Stack direction="row" sx={{ gap: 0.5, flexWrap: 'wrap', mt: 1 }}>
          {review.tagCodes.map((code) => (
            <Chip key={code} size="small" variant="outlined" label={t.has(`tag_${code}`) ? t(`tag_${code}`) : code} />
          ))}
        </Stack>
      ) : null}
    </Paper>
  );
}

function ProfileSkeleton() {
  return (
    <Stack sx={{ gap: 3 }}>
      <Stack direction="row" sx={{ gap: 2, alignItems: 'center' }}>
        <Skeleton variant="circular" width={72} height={72} />
        <Stack sx={{ gap: 1, flexGrow: 1 }}>
          <Skeleton variant="text" width="60%" height={32} />
          <Skeleton variant="text" width="40%" />
        </Stack>
      </Stack>
      <Skeleton variant="rounded" height={72} />
      <Skeleton variant="rounded" height={120} />
      <Skeleton variant="rounded" height={96} />
    </Stack>
  );
}
