'use client';
import { useLocale, useTranslations } from 'next-intl';
import { Avatar, Box, Chip, Skeleton, Stack, Typography } from '@mui/material';
import {
  AppIcon,
  EmptyState,
  PageHeader,
  ServicePriceRow,
  SurfaceCard,
  TrustBadge,
  VerificationPanel,
} from '@/components';
import { ROUTES } from '@/constants';
import { formatNumber } from '@/utils';
import { useMe } from '@/services/auth';
import { useMyVariants } from '@/services/catalog';
import { useServiceAreas } from '@/services/serviceAreas';
import { useNurseProfile } from '@/services/profiles';
import { useNurseTrustBadge, useVerificationStatus } from '@/services/verification';
import { ownBadgeState } from '@/services/verification/types';

function parseSpecializations(json: string): string[] {
  try {
    const parsed = JSON.parse(json);
    return Array.isArray(parsed) ? parsed.filter((item): item is string => typeof item === 'string') : [];
  } catch {
    return [];
  }
}

/**
 * "نمایهٔ عمومی من" — how families see this nurse. Composes the same C3 trust-dossier pieces
 * (`TrustBadge`, `VerificationPanel`, `ServicePriceRow`) but **entirely from the nurse's own cached
 * data** (own profile + `useMyVariants` + `useServiceAreas` + own badge) — no dependency on the search
 * index, so it renders truthfully even pre-publish (before `is_searchable` can ever be true). Linked
 * from the profile and services pages — the strongest motivator to finish bio/photo/credentials.
 */
export default function NursePublicProfilePreviewPage() {
  const t = useTranslations('nurseProfile');
  const tv = useTranslations('verification');
  const locale = useLocale();

  const { data: me, isLoading: meLoading } = useMe();
  const { data: profile, isLoading: profileLoading } = useNurseProfile();
  const verification = useVerificationStatus();
  const trustBadge = useNurseTrustBadge(me?.id);
  const variantsQuery = useMyVariants();
  const areasQuery = useServiceAreas();

  const isLoading = meLoading || profileLoading || verification.isLoading;

  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3, maxWidth: 560 }}>
        <PageHeader title={t('preview_title')} backTo={`/${locale}${ROUTES.NURSE_PROFILE}`} backLabel={t('back_to_profile')} />
        <Stack direction="row" sx={{ gap: 2, alignItems: 'center' }}>
          <Skeleton variant="circular" width={72} height={72} />
          <Skeleton variant="text" width="50%" height={32} />
        </Stack>
        <Skeleton variant="rounded" height={96} />
        <Skeleton variant="rounded" height={140} />
      </Box>
    );
  }

  const displayName = me ? [me.firstName, me.lastName].filter(Boolean).join(' ').trim() || me.phone : '';
  const specializations = parseSpecializations(profile?.specializationsJson ?? '[]');
  const activeVariants = (variantsQuery.data?.items ?? []).filter((variant) => variant.isActive);
  const areas = areasQuery.data?.items ?? [];

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3, maxWidth: 560 }}>
      <PageHeader title={t('preview_title')} subtitle={t('preview_subtitle')} backTo={`/${locale}${ROUTES.NURSE_PROFILE}`} backLabel={t('back_to_profile')} />

      <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 }}
          >
            {profile?.avatarUrl ? null : (displayName || '؟').charAt(0)}
          </Avatar>
          <Stack sx={{ gap: 0.5 }}>
            <Typography variant="h5" component="h2">
              {displayName}
            </Typography>
            {profile && profile.totalReviews > 0 ? (
              <Stack direction="row" sx={{ gap: 0.5, alignItems: 'center' }}>
                <AppIcon icon="star" size={18} color="var(--bal-rating)" />
                <Typography variant="body2" sx={{ fontWeight: 700 }}>
                  {formatNumber(profile.averageRating, locale, { minimumFractionDigits: 1, maximumFractionDigits: 1 })}
                </Typography>
                <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                  {t('preview_reviews_count', { count: profile.totalReviews })}
                </Typography>
              </Stack>
            ) : null}
            {profile ? (
              <Typography variant="caption" sx={{ color: 'text.secondary' }}>
                {t('preview_completed_visits', { count: formatNumber(profile.totalCompletedBookings, locale) })}
              </Typography>
            ) : null}
          </Stack>
        </Stack>

        <TrustBadge state={ownBadgeState(verification.data)} sx={{ alignSelf: 'flex-start' }} />

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

      {profile?.yearsOfExperience || specializations.length > 0 ? (
        <Stack direction="row" sx={{ gap: 1, flexWrap: 'wrap' }}>
          {profile?.yearsOfExperience ? (
            <Chip variant="outlined" label={t('preview_years_experience', { years: formatNumber(profile.yearsOfExperience, locale) })} />
          ) : null}
          {specializations.map((code) => (
            <Chip key={code} variant="outlined" label={tv.has(`specialty_${code}`) ? tv(`specialty_${code}`) : code} />
          ))}
        </Stack>
      ) : null}

      <Stack sx={{ gap: 1 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
          {t('preview_verified_title')}
        </Typography>
        <SurfaceCard padding="md">
          <VerificationPanel badge={trustBadge.data} isLoading={trustBadge.isLoading} isError={trustBadge.isError} />
        </SurfaceCard>
      </Stack>

      <Stack sx={{ gap: 1 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
          {t('preview_services_title')}
        </Typography>
        {activeVariants.length === 0 ? (
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {t('preview_services_empty')}
          </Typography>
        ) : (
          <Box>
            {activeVariants.map((variant) => (
              <ServicePriceRow
                key={variant.id}
                displayName={variant.displayName}
                priceIrr={variant.price}
                priceUnit={variant.priceUnit}
                sessionCount={variant.sessionCount}
              />
            ))}
          </Box>
        )}
      </Stack>

      <Stack sx={{ gap: 1 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
          {t('preview_coverage_title')}
        </Typography>
        {areas.length === 0 ? (
          <EmptyState icon="coverage" title={t('preview_coverage_empty')} />
        ) : (
          <Stack direction="row" sx={{ gap: 1, flexWrap: 'wrap' }}>
            {areas.map((area) => {
              const city = locale === 'en' ? area.cityNameEn : area.cityNameFa;
              const district = locale === 'en' ? area.districtNameEn : area.districtNameFa;
              return (
                <Chip
                  key={area.id}
                  label={area.isWholeCity ? city : `${city} · ${district}`}
                  sx={{ bgcolor: 'var(--bal-primary-soft)', fontWeight: 500 }}
                />
              );
            })}
          </Stack>
        )}
      </Stack>
    </Box>
  );
}
