'use client';
import { useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useParams, useRouter } from 'next/navigation';
import { useSnackbar } from 'notistack';
import { Paper, Skeleton, Stack, TextField, Typography } from '@mui/material';
import { AppButton, EmptyState, RatingInput, ReviewTagSelector, StatusChip } from '@/components';
import type { StatusKind } from '@/components';
import { formatShamsiDate } from '@/utils';
import { useBookingDetail } from '@/services/bookings';
import { useReviewEligibility, useMyReviewForBooking, useCreateReview } from '@/services/reviews';
import { REVIEW_TAG_CODES, type ModerationStatus } from '@/services/reviews/types';

const REVIEW_BODY_MAX = 2000;

/** moderationStatus → StatusChip kind (published=success, pending=warning, rejected=error, hidden=neutral). */
const STATUS_KIND: Record<ModerationStatus, StatusKind> = {
  pending_moderation: 'pending',
  published: 'verified',
  hidden: 'neutral',
  rejected: 'rejected',
};

/**
 * f13 — Leave a review («ثبت نظر»): the customer's one moderated review for a completed booking. The form is
 * shown only when the server says the booking can be reviewed AND it is not already reviewed; on submit it
 * flips to the persistent "under review" state (the review is `pending_moderation` and never appears publicly
 * here). One review per booking (1:1) — a returning customer sees their review's state, never a second form.
 */
export default function LeaveReviewPage() {
  const t = useTranslations('reviews');
  const tc = useTranslations('common');
  const locale = useLocale();
  const router = useRouter();
  const { enqueueSnackbar } = useSnackbar();

  const params = useParams<{ id: string }>();
  const rawId = Number(params.id);
  const bookingId = Number.isInteger(rawId) && rawId > 0 ? rawId : -1;

  const { data: booking } = useBookingDetail(bookingId, 'customer');
  const eligibility = useReviewEligibility(bookingId);
  const myReview = useMyReviewForBooking(bookingId);
  const createReview = useCreateReview();

  const [rating, setRating] = useState(0);
  const [body, setBody] = useState('');
  const [tagCodes, setTagCodes] = useState<string[]>([]);

  const nurseName = booking?.nurseName?.trim();

  const submit = () => {
    if (rating < 1) return;
    createReview.mutate(
      { bookingId, body: { rating, body: body.trim() || null, tagCodes } },
      { onError: () => enqueueSnackbar(t('error_submit'), { variant: 'error' }) },
    );
  };

  // ── Already reviewed → the persistent under-review / published state (never a second form) ───────────────
  const existing = myReview.data;
  const submittedThisSession = createReview.isSuccess;
  if ((existing && existing.status !== 'none') || submittedThisSession) {
    const status: ModerationStatus =
      existing && existing.status !== 'none' ? existing.status : 'pending_moderation';
    const shownRating = existing && existing.status !== 'none' ? (existing.rating ?? rating) : rating;
    const shownBody = existing && existing.status !== 'none' ? existing.body : body.trim() || null;
    const shownTags = existing && existing.status !== 'none' ? existing.tagCodes : tagCodes;
    return (
      <Stack sx={{ gap: 3, maxWidth: 560, mx: 'auto', width: '100%' }}>
        <PageHeading title={t('my_review_title')} subtitle={nurseName ? t('for_nurse', { name: nurseName }) : undefined} />
        <Paper elevation={0} sx={{ p: 2.5, border: '1px solid', borderColor: 'divider', borderRadius: 2 }}>
          <Stack sx={{ gap: 1.5 }}>
            <Stack direction="row" sx={{ alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
              <StatusChip status={STATUS_KIND[status]} label={t(`status_${status}`)} />
              {existing?.createdAt ? (
                <Typography variant="caption" sx={{ color: 'text.secondary' }}>
                  {formatShamsiDate(existing.createdAt, locale)}
                </Typography>
              ) : null}
            </Stack>
            {status === 'pending_moderation' ? (
              <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                {t('under_review_body')}
              </Typography>
            ) : null}
            <RatingInput value={shownRating} readOnly size={22} ariaLabel={t('rating_label')} />
            {shownBody ? <Typography variant="body2">{shownBody}</Typography> : null}
            {shownTags.length > 0 ? (
              <Stack direction="row" sx={{ gap: 1, flexWrap: 'wrap' }}>
                {shownTags.map((code) => (
                  <StatusChip key={code} status="info" label={t.has(`tag_${code}`) ? t(`tag_${code}`) : code} />
                ))}
              </Stack>
            ) : null}
          </Stack>
        </Paper>
        <AppButton variant="outlined" color="primary" onClick={() => router.back()} sx={{ alignSelf: 'flex-start' }}>
          {tc('back')}
        </AppButton>
      </Stack>
    );
  }

  if (eligibility.isLoading || myReview.isLoading) {
    return (
      <Stack sx={{ gap: 2, maxWidth: 560, mx: 'auto', width: '100%' }}>
        <Skeleton variant="text" width="50%" height={36} />
        <Skeleton variant="rounded" height={56} />
        <Skeleton variant="rounded" height={120} />
        <Skeleton variant="rounded" height={72} />
      </Stack>
    );
  }

  // ── Not eligible → a clear, non-leaking reason (no form) ─────────────────────────────────────────────────
  if (!eligibility.data?.canReview) {
    const reason = eligibility.data?.reason ?? 'not_completed';
    return (
      <Stack sx={{ gap: 3, maxWidth: 560, mx: 'auto', width: '100%' }}>
        <PageHeading title={t('not_eligible_title')} />
        <EmptyState title={t(`reason_${reason}`)} />
        <AppButton variant="outlined" color="primary" onClick={() => router.back()} sx={{ alignSelf: 'flex-start' }}>
          {tc('back')}
        </AppButton>
      </Stack>
    );
  }

  // ── Eligible → the review form ───────────────────────────────────────────────────────────────────────────
  return (
    <Stack sx={{ gap: 3, maxWidth: 560, mx: 'auto', width: '100%' }}>
      <PageHeading title={t('title')} subtitle={nurseName ? t('for_nurse', { name: nurseName }) : t('subtitle')} />

      <Stack sx={{ gap: 1 }}>
        <Typography variant="subtitle2" sx={{ fontWeight: 700 }}>
          {t('rating_label')}
        </Typography>
        <RatingInput value={rating} onChange={setRating} ariaLabel={t('rating_label')} />
      </Stack>

      <TextField
        label={t('body_label')}
        placeholder={t('body_placeholder')}
        value={body}
        onChange={(e) => setBody(e.target.value.slice(0, REVIEW_BODY_MAX))}
        multiline
        minRows={3}
        fullWidth
      />

      <Stack sx={{ gap: 1 }}>
        <Typography variant="subtitle2" sx={{ fontWeight: 700 }}>
          {t('tags_label')}
        </Typography>
        <ReviewTagSelector
          codes={REVIEW_TAG_CODES}
          selected={tagCodes}
          onChange={setTagCodes}
          labelFor={(code) => (t.has(`tag_${code}`) ? t(`tag_${code}`) : code)}
          disabled={createReview.isPending}
        />
      </Stack>

      <Stack direction="row" sx={{ gap: 1, justifyContent: 'flex-end' }}>
        <AppButton variant="text" color="primary" onClick={() => router.back()} disabled={createReview.isPending}>
          {tc('cancel')}
        </AppButton>
        <AppButton
          variant="contained"
          color="primary"
          onClick={submit}
          disabled={rating < 1 || createReview.isPending}
          startIcon="star"
        >
          {createReview.isPending ? t('submitting') : t('submit')}
        </AppButton>
      </Stack>
    </Stack>
  );
}

function PageHeading({ title, subtitle }: { title: string; subtitle?: string }) {
  return (
    <Stack sx={{ gap: 0.5 }}>
      <Typography variant="h5" component="h1">
        {title}
      </Typography>
      {subtitle ? (
        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          {subtitle}
        </Typography>
      ) : null}
    </Stack>
  );
}
