import { useCallback, useMemo, useState } from 'react'
import CancelIcon from '@mui/icons-material/Cancel'
import CheckCircleIcon from '@mui/icons-material/CheckCircle'
import ExpandMoreIcon from '@mui/icons-material/ExpandMore'
import Accordion from '@mui/material/Accordion'
import AccordionDetails from '@mui/material/AccordionDetails'
import AccordionSummary from '@mui/material/AccordionSummary'
import Alert from '@mui/material/Alert'
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
import CircularProgress from '@mui/material/CircularProgress'
import Dialog from '@mui/material/Dialog'
import DialogActions from '@mui/material/DialogActions'
import DialogContent from '@mui/material/DialogContent'
import DialogTitle from '@mui/material/DialogTitle'
import IconButton from '@mui/material/IconButton'
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 TableContainer from '@mui/material/TableContainer'
import TableHead from '@mui/material/TableHead'
import TableRow from '@mui/material/TableRow'
import TextField from '@mui/material/TextField'
import Tooltip from '@mui/material/Tooltip'
import Typography from '@mui/material/Typography'
import { TEST_CHECKLIST_ITEMS } from '@shared/constants/test-checklist-items'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
  fetchTestChecklistResults,
  resetTestChecklist,
  updateTestChecklistItem,
} from '@/entities/test-checklist/api/test-checklist-api'

type Status = 'passed' | 'failed' | 'unchecked'

function statusFromResult(r: { passed: boolean; comment: string | null } | undefined): Status {
  if (!r) return 'unchecked'
  return r.passed ? 'passed' : 'failed'
}

function formatDate(iso: string): string {
  return new Date(iso).toLocaleString('ru-RU', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

function StatusIcon({ status, onClick }: { status: Status; onClick: () => void }) {
  const icons = {
    passed: <CheckCircleIcon sx={{ color: 'success.main' }} />,
    failed: <CancelIcon sx={{ color: 'error.main' }} />,
    unchecked: <Box sx={{ width: 24, height: 24, borderRadius: '50%', border: 2, borderColor: 'action.disabled' }} />,
  }

  return (
    <Tooltip title={status === 'passed' ? 'Пройдено' : status === 'failed' ? 'Не пройдено' : 'Не проверено'}>
      <IconButton size="small" onClick={onClick} sx={{ p: 0.5 }}>
        {icons[status]}
      </IconButton>
    </Tooltip>
  )
}

export function AdminTestChecklistPage() {
  const queryClient = useQueryClient()
  const [confirmOpen, setConfirmOpen] = useState(false)
  const [expanded, setExpanded] = useState<string | false>(false)
  const [errorDialogOpen, setErrorDialogOpen] = useState(false)
  const [errorItemKey, setErrorItemKey] = useState<string | null>(null)
  const [errorComment, setErrorComment] = useState('')
  const [errorCommentError, setErrorCommentError] = useState(false)

  const { data, isLoading, isError } = useQuery({
    queryKey: ['admin', 'test-checklist'],
    queryFn: fetchTestChecklistResults,
  })

  const updateMutation = useMutation({
    mutationFn: ({ itemKey, passed, comment }: { itemKey: string; passed: boolean; comment?: string | null }) =>
      updateTestChecklistItem(itemKey, passed, comment),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'test-checklist'] })
    },
  })

  const resetMutation = useMutation({
    mutationFn: resetTestChecklist,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'test-checklist'] })
      setConfirmOpen(false)
    },
  })

  const sections = useMemo(() => {
    const map = new Map<string, (typeof TEST_CHECKLIST_ITEMS)[number][]>()
    for (const item of TEST_CHECKLIST_ITEMS) {
      const existing = map.get(item.section) || []
      existing.push(item)
      map.set(item.section, existing)
    }
    return Array.from(map.entries())
  }, [])

  const results = data?.results ?? {}

  const total = TEST_CHECKLIST_ITEMS.length
  const passedCount = TEST_CHECKLIST_ITEMS.filter((i) => results[i.key]?.passed).length

  const handleStatusClick = useCallback(
    (itemKey: string) => {
      const current = statusFromResult(results[itemKey])
      if (current === 'failed') {
        updateMutation.mutate({ itemKey, passed: false, comment: null })
      } else if (current === 'unchecked') {
        updateMutation.mutate({ itemKey, passed: true })
      } else {
        setErrorItemKey(itemKey)
        setErrorComment('')
        setErrorCommentError(false)
        setErrorDialogOpen(true)
      }
    },
    [results, updateMutation],
  )

  const handleSaveError = () => {
    if (!errorItemKey) return
    if (!errorComment.trim()) {
      setErrorCommentError(true)
      return
    }
    updateMutation.mutate({ itemKey: errorItemKey, passed: false, comment: errorComment.trim() })
    setErrorDialogOpen(false)
    setErrorItemKey(null)
    setErrorComment('')
  }

  const errorItem = errorItemKey ? TEST_CHECKLIST_ITEMS.find((i) => i.key === errorItemKey) : null

  return (
    <Box>
      <Stack direction="row" sx={{ mb: 3, justifyContent: 'space-between', alignItems: 'center' }}>
        <Box>
          <Typography variant="h5" sx={{ fontWeight: 700 }}>
            Тест-чеклист
          </Typography>
          <Typography variant="body2" color="text.secondary">
            Пройдено: {passedCount} из {total}
          </Typography>
        </Box>
        <Button
          variant="outlined"
          color="warning"
          onClick={() => setConfirmOpen(true)}
          disabled={resetMutation.isPending}
        >
          Сбросить все
        </Button>
      </Stack>

      {isLoading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
          <CircularProgress />
        </Box>
      ) : isError ? (
        <Alert severity="error">Не удалось загрузить чеклист.</Alert>
      ) : (
        sections.map(([section, items]) => (
          <Accordion
            key={section}
            expanded={expanded === section}
            onChange={(_, isExpanded) => setExpanded(isExpanded ? section : false)}
          >
            <AccordionSummary expandIcon={<ExpandMoreIcon />}>
              <Typography sx={{ fontWeight: 600 }}>{section}</Typography>
            </AccordionSummary>
            <AccordionDetails sx={{ px: 0 }}>
              <TableContainer>
                <Table size="small">
                  <TableHead>
                    <TableRow>
                      <TableCell sx={{ width: 56 }} />
                      <TableCell sx={{ fontWeight: 600 }}>Действие</TableCell>
                      <TableCell sx={{ fontWeight: 600 }}>Ожидаемый результат</TableCell>
                      <TableCell sx={{ fontWeight: 600 }}>Комментарий</TableCell>
                      <TableCell sx={{ fontWeight: 600, whiteSpace: 'nowrap' }}>Дата проверки</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {items.map((item) => {
                      const r = results[item.key]
                      const status = statusFromResult(r)
                      return (
                        <TableRow key={item.key} hover>
                          <TableCell>
                            <StatusIcon status={status} onClick={() => handleStatusClick(item.key)} />
                          </TableCell>
                          <TableCell>{item.action}</TableCell>
                          <TableCell>{item.expectedResult}</TableCell>
                          <TableCell sx={{ maxWidth: 200 }}>
                            {r?.comment ? (
                              <Tooltip title={r.comment} arrow>
                                <Typography
                                  variant="body2"
                                  color="error.main"
                                  sx={{
                                    overflow: 'hidden',
                                    textOverflow: 'ellipsis',
                                    whiteSpace: 'nowrap',
                                    cursor: 'pointer',
                                  }}
                                >
                                  {r.comment}
                                </Typography>
                              </Tooltip>
                            ) : (
                              <Typography variant="body2" color="text.disabled">
                                —
                              </Typography>
                            )}
                          </TableCell>
                          <TableCell sx={{ whiteSpace: 'nowrap', color: r ? 'text.primary' : 'text.disabled' }}>
                            {r ? formatDate(r.checkedAt) : '—'}
                          </TableCell>
                        </TableRow>
                      )
                    })}
                  </TableBody>
                </Table>
              </TableContainer>
            </AccordionDetails>
          </Accordion>
        ))
      )}

      <Dialog open={confirmOpen} onClose={() => setConfirmOpen(false)}>
        <DialogTitle>Сбросить все проверки?</DialogTitle>
        <DialogContent>
          <Typography>Все отметки будут удалены. Это действие нельзя отменить.</Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setConfirmOpen(false)}>Отмена</Button>
          <Button color="warning" onClick={() => resetMutation.mutate()}>
            Сбросить
          </Button>
        </DialogActions>
      </Dialog>

      <Dialog open={errorDialogOpen} onClose={() => setErrorDialogOpen(false)} maxWidth="sm" fullWidth>
        <DialogTitle>Описание ошибки — {errorItem?.action}</DialogTitle>
        <DialogContent>
          <TextField
            fullWidth
            multiline
            rows={4}
            value={errorComment}
            onChange={(e) => {
              setErrorComment(e.target.value)
              if (errorCommentError) setErrorCommentError(false)
            }}
            placeholder="Опишите, что пошло не так..."
            error={errorCommentError}
            helperText={errorCommentError ? 'Обязательное поле' : ''}
            sx={{ mt: 1 }}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setErrorDialogOpen(false)}>Отмена</Button>
          <Button color="error" onClick={handleSaveError}>
            Сохранить
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  )
}
