import { useState } from 'react'
import Alert from '@mui/material/Alert'
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
import Chip from '@mui/material/Chip'
import Stack from '@mui/material/Stack'
import Table from '@mui/material/Table'
import TableBody from '@mui/material/TableBody'
import TableCell from '@mui/material/TableCell'
import TableHead from '@mui/material/TableHead'
import TableRow from '@mui/material/TableRow'
import TextField from '@mui/material/TextField'
import Typography from '@mui/material/Typography'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { fetchAdminReviews, moderateReview } from '@/entities/review/api/admin-review-api'
import { getErrorMessage } from '@/shared/lib/get-error-message'
import { invalidateQueryKeys } from '@/shared/lib/invalidate-query-keys'
import { RichTextMessageContent } from '@/shared/ui/RichTextMessageContent'

export function AdminReviewsPage() {
  const qc = useQueryClient()
  const [status] = useState('pending')

  const reviewsQuery = useQuery({
    queryKey: ['admin', 'reviews', status],
    queryFn: () => fetchAdminReviews({ status, page: 1, pageSize: 50 }),
  })

  const modMut = useMutation({
    mutationFn: (params: { id: string; action: 'approve' | 'reject' }) => moderateReview(params.id, params.action),
    onSuccess: () => void invalidateQueryKeys(qc, [['admin', 'reviews']]),
  })

  const error = modMut.error

  const items = reviewsQuery.data?.items ?? []

  return (
    <Box>
      <Typography variant="h4" sx={{ mb: 2 }}>
        Отзывы
      </Typography>

      <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
        Модерация отзывов доступна пользователю с правами администратора.
      </Typography>
      <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} sx={{ mb: 2 }}>
        <TextField size="small" label="Статус" value="pending" disabled />
      </Stack>

      {reviewsQuery.isError && <Alert severity="error">Не удалось загрузить отзывы.</Alert>}
      {error && <Alert severity="error">{getErrorMessage(error)}</Alert>}

      <Table size="small">
        <TableHead>
          <TableRow>
            <TableCell>Товар</TableCell>
            <TableCell>Пользователь</TableCell>
            <TableCell>Оценка</TableCell>
            <TableCell>Текст</TableCell>
            <TableCell align="right">Действия</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {items.map((r) => (
            <TableRow key={r.id} hover>
              <TableCell>{r.product.title}</TableCell>
              <TableCell>{r.user.email}</TableCell>
              <TableCell>
                <Chip label={String(r.rating)} size="small" />
              </TableCell>
              <TableCell>{r.text?.trim() ? <RichTextMessageContent value={r.text} tone="review" /> : '—'}</TableCell>
              <TableCell align="right">
                <Button
                  size="small"
                  onClick={() => modMut.mutate({ id: r.id, action: 'approve' })}
                  disabled={modMut.isPending}
                >
                  Одобрить
                </Button>
                <Button
                  size="small"
                  color="error"
                  onClick={() => modMut.mutate({ id: r.id, action: 'reject' })}
                  disabled={modMut.isPending}
                >
                  Отклонить
                </Button>
              </TableCell>
            </TableRow>
          ))}
          {reviewsQuery.isSuccess && items.length === 0 && (
            <TableRow>
              <TableCell colSpan={5} sx={{ color: 'text.secondary' }}>
                Нет отзывов на модерации.
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>
    </Box>
  )
}
