import React, { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import {
  DialogRoot,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogBody,
  DialogFooter,
  DialogActionTrigger,
  Button,
  Text,
} from '@chakra-ui/react'
import { useClearChainSubmissionsMutation } from '../__data__/api/api'
import { toaster } from './ui/toaster'
import type { ChallengeChain } from '../types/challenge'

interface ClearSubmissionsDialogProps {
  isOpen: boolean
  onClose: () => void
  chain: ChallengeChain | null
}

export const ClearSubmissionsDialog: React.FC<ClearSubmissionsDialogProps> = ({
  isOpen,
  onClose,
  chain,
}) => {
  const { t } = useTranslation()
  const [clearSubmissions, { isLoading }] = useClearChainSubmissionsMutation()

  // Прокручиваем страницу к началу при открытии диалога
  useEffect(() => {
    if (isOpen) {
      window.scrollTo({ top: 0, behavior: 'smooth' })
    }
  }, [isOpen])

  const handleConfirm = async () => {
    if (!chain) return

    try {
      await clearSubmissions(chain.id).unwrap()
      toaster.create({
        title: t('challenge.admin.common.success'),
        description: t('challenge.admin.chains.clear.submissions.success'),
        type: 'success',
      })
      onClose()
    } catch (err) {
      toaster.create({
        title: t('challenge.admin.common.error'),
        description: t('challenge.admin.chains.clear.submissions.error'),
        type: 'error',
      })
    }
  }

  if (!chain) return null

  return (
    <DialogRoot open={isOpen} onOpenChange={(e) => !e.open && onClose()} scrollBehavior="inside">
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{t('challenge.admin.chains.clear.submissions.dialog.title')}</DialogTitle>
        </DialogHeader>
        <DialogBody>
          <Text>{t('challenge.admin.chains.clear.submissions.dialog.message', { name: chain.name })}</Text>
        </DialogBody>
        <DialogFooter>
          <DialogActionTrigger asChild>
            <Button variant="outline" onClick={onClose} disabled={isLoading}>
              {t('challenge.admin.common.cancel')}
            </Button>
          </DialogActionTrigger>
          <Button colorPalette="red" onClick={handleConfirm} disabled={isLoading}>
            {t('challenge.admin.chains.clear.submissions.dialog.button.confirm')}
          </Button>
        </DialogFooter>
      </DialogContent>
    </DialogRoot>
  )
}




