import { useState } from 'react'
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
import Stack from '@mui/material/Stack'
import Typography from '@mui/material/Typography'
import { ReviewDialog } from './ReviewDialog'

type EligibileItem = {
  productId: string
  title: string
  hasReview: boolean
}

type Props = {
  items: EligibileItem[]
  isSubmitPending: boolean
  isUploadPending: boolean
  submitError: unknown
  uploadError: unknown
  onSubmitReview: (params: { productId: string; rating: number; text: string; imageUrl: string | null }) => void
  onUploadImage: (file: File) => Promise<{ url: string }>
}

export function ReviewSection({
  items,
  isSubmitPending,
  isUploadPending,
  submitError,
  uploadError,
  onSubmitReview,
  onUploadImage,
}: Props) {
  const [target, setTarget] = useState<{ productId: string; title: string } | null>(null)
  const [uploadedImageUrl, setUploadedImageUrl] = useState<string | null>(null)

  if (items.length === 0) return null

  return (
    <Box sx={{ border: 1, borderColor: 'divider', borderRadius: 2, p: 2, bgcolor: 'background.paper' }}>
      <Typography variant="h6" gutterBottom>
        Отзывы
      </Typography>
      <Typography color="text.secondary" variant="body2" sx={{ mb: 2 }}>
        Поделитесь впечатлением о товарах. Отзывы появляются после модерации.
      </Typography>
      <Stack spacing={1}>
        {items.map((row) => (
          <Stack
            key={row.productId}
            direction={{ xs: 'column', sm: 'row' }}
            spacing={1}
            sx={{ alignItems: { sm: 'center' }, justifyContent: 'space-between' }}
          >
            <Typography sx={{ flexGrow: 1 }}>{row.title}</Typography>
            <Button
              size="small"
              variant="outlined"
              disabled={row.hasReview}
              onClick={() => setTarget({ productId: row.productId, title: row.title })}
            >
              {row.hasReview ? 'Отзыв отправлен' : 'Оставить отзыв'}
            </Button>
          </Stack>
        ))}
      </Stack>

      <ReviewDialog
        productTitle={target?.title ?? null}
        open={Boolean(target)}
        isPending={isSubmitPending}
        isUploadingImage={isUploadPending}
        error={submitError}
        uploadError={uploadError}
        onClose={() => {
          setTarget(null)
          setUploadedImageUrl(null)
        }}
        onSubmit={(params) => {
          if (!target) return
          onSubmitReview({
            productId: target.productId,
            ...params,
            imageUrl: uploadedImageUrl,
          })
        }}
        onUploadImage={async (file) => {
          const result = await onUploadImage(file)
          setUploadedImageUrl(result.url)
        }}
      />
    </Box>
  )
}
