import { useState } from 'react'
import Button from '@mui/material/Button'
import Dialog from '@mui/material/Dialog'
import DialogActions from '@mui/material/DialogActions'
import DialogContent from '@mui/material/DialogContent'
import DialogContentText from '@mui/material/DialogContentText'
import DialogTitle from '@mui/material/DialogTitle'
import Divider from '@mui/material/Divider'
import Stack from '@mui/material/Stack'
import Typography from '@mui/material/Typography'
import { useMutation, useQuery } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import { fetchMyOrders } from '@/entities/order'
import { apiClient } from '@/shared/api/client'
import { getApiErrorMessage } from '@/shared/lib/get-api-error-message'
import { logout, tokenSet } from '@/shared/model/auth'

const ACTIVE_STATUSES = ['DRAFT', 'PENDING_PAYMENT', 'PAID', 'IN_PROGRESS', 'SHIPPED', 'READY_FOR_PICKUP']

export function DeleteAccountSection() {
  const navigate = useNavigate()
  const [dialogOpen, setDialogOpen] = useState(false)

  const ordersQuery = useQuery({
    queryKey: ['my-orders'],
    queryFn: fetchMyOrders,
    staleTime: 30_000,
  })

  const activeOrders = ordersQuery.data?.items.filter((o) => ACTIVE_STATUSES.includes(o.status)) ?? []
  const hasActiveOrders = activeOrders.length > 0

  const deleteMutation = useMutation({
    mutationFn: async () => {
      await apiClient.delete('me')
    },
    onSuccess: () => {
      tokenSet(null)
      logout()
      setDialogOpen(false)
      navigate('/')
    },
  })

  return (
    <>
      <Divider />
      <Stack spacing={2}>
        <Typography variant="h6" color="error">
          Удаление аккаунта
        </Typography>

        <Button variant="outlined" color="error" onClick={() => setDialogOpen(true)} sx={{ alignSelf: 'start' }}>
          Удалить аккаунт
        </Button>

        {deleteMutation.error && (
          <Typography variant="caption" color="error">
            {getApiErrorMessage(deleteMutation.error) || 'Не удалось удалить аккаунт'}
          </Typography>
        )}
      </Stack>

      <Dialog open={dialogOpen} onClose={() => setDialogOpen(false)}>
        <DialogTitle>Удаление аккаунта</DialogTitle>
        <DialogContent>
          {hasActiveOrders && (
            <DialogContentText sx={{ mb: 1, fontWeight: 500 }}>
              У вас есть {activeOrders.length} незавершённых заказ
              {activeOrders.length === 1 ? '' : activeOrders.length < 5 ? 'а' : 'ов'}. После удаления аккаунта
              отслеживание заказов станет недоступным.
            </DialogContentText>
          )}
          <DialogContentText>
            Вы уверены? Все данные будут безвозвратно удалены. Восстановить аккаунт будет невозможно.
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDialogOpen(false)}>Отмена</Button>
          <Button
            onClick={() => deleteMutation.mutate()}
            variant="contained"
            color="error"
            disabled={deleteMutation.isPending}
          >
            Удалить
          </Button>
        </DialogActions>
      </Dialog>
    </>
  )
}
