'use client';

import { useState, useEffect, useCallback } from 'react';

import Box from '@mui/material/Box';
import Tab from '@mui/material/Tab';
import Tabs from '@mui/material/Tabs';
import List from '@mui/material/List';
import Stack from '@mui/material/Stack';
import Alert from '@mui/material/Alert';
import Badge from '@mui/material/Badge';
import Button from '@mui/material/Button';
import Divider from '@mui/material/Divider';
import Tooltip from '@mui/material/Tooltip';
import ListItem from '@mui/material/ListItem';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import ListItemText from '@mui/material/ListItemText';
import CircularProgress from '@mui/material/CircularProgress';

import { paths } from 'src/routes/paths';

import {
  markAsRead,
  markAllAsRead,
  getNotifications,
  deleteNotification,
} from 'src/utils/notifications-api';

import { DashboardContent } from 'src/layouts/dashboard';

import { Iconify } from 'src/components/iconify';
import { CustomBreadcrumbs } from 'src/components/custom-breadcrumbs';

// ----------------------------------------------------------------------

function formatDate(s) {
  if (!s) return '';
  const d = new Date(s);
  return Number.isNaN(d.getTime())
    ? ''
    : d.toLocaleString('ru-RU', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
}

function notifIcon(type) {
  switch (type) {
    case 'success': return 'eva:checkmark-circle-2-outline';
    case 'warning': return 'eva:alert-triangle-outline';
    case 'error': return 'eva:close-circle-outline';
    default: return 'eva:bell-outline';
  }
}

function notifColor(type) {
  switch (type) {
    case 'success': return 'success.main';
    case 'warning': return 'warning.main';
    case 'error': return 'error.main';
    default: return 'info.main';
  }
}

// ----------------------------------------------------------------------

export function NotificationsView() {
  const [notifications, setNotifications] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [tab, setTab] = useState('unread');
  const [processing, setProcessing] = useState(null);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await getNotifications({ page_size: 100 });
      setNotifications(res.results);
    } catch (e) {
      setError(e?.response?.data?.detail || e?.message || 'Ошибка загрузки');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { load(); }, [load]);

  const filtered = notifications.filter((n) =>
    tab === 'all' ? true : !n.is_read
  );

  const unreadCount = notifications.filter((n) => !n.is_read).length;

  const handleMarkAsRead = async (id) => {
    try {
      setProcessing(id);
      await markAsRead(id);
      setNotifications((prev) => prev.map((n) => n.id === id ? { ...n, is_read: true } : n));
    } catch {
      // ignore
    } finally {
      setProcessing(null);
    }
  };

  const handleMarkAll = async () => {
    try {
      await markAllAsRead();
      setNotifications((prev) => prev.map((n) => ({ ...n, is_read: true })));
    } catch (e) {
      setError(e?.response?.data?.detail || e?.message || 'Ошибка');
    }
  };

  const handleDelete = async (id) => {
    try {
      setProcessing(id);
      await deleteNotification(id);
      setNotifications((prev) => prev.filter((n) => n.id !== id));
    } catch {
      // ignore
    } finally {
      setProcessing(null);
    }
  };

  return (
    <DashboardContent>
      <CustomBreadcrumbs
        heading="Уведомления"
        links={[{ name: 'Главная', href: paths.dashboard.root }, { name: 'Уведомления' }]}
        action={
          unreadCount > 0 && (
            <Button variant="outlined" size="small" onClick={handleMarkAll}>
              Отметить все как прочитанные
            </Button>
          )
        }
        sx={{ mb: 3 }}
      />

      {error && <Alert severity="error" sx={{ mb: 3 }}>{error}</Alert>}

      <Tabs value={tab} onChange={(_, v) => setTab(v)} sx={{ mb: 3 }}>
        <Tab value="unread" label={
          <Badge badgeContent={unreadCount} color="error">
            <Box sx={{ pr: unreadCount > 0 ? 1.5 : 0 }}>Непрочитанные</Box>
          </Badge>
        } />
        <Tab value="all" label="Все" />
      </Tabs>

      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 6 }}>
          <CircularProgress />
        </Box>
      ) : filtered.length === 0 ? (
        <Box sx={{ textAlign: 'center', py: 8 }}>
          <Iconify icon="eva:bell-off-outline" width={64} color="text.disabled" sx={{ mb: 2 }} />
          <Typography variant="body1" color="text.secondary">
            {tab === 'unread' ? 'Нет непрочитанных уведомлений' : 'Нет уведомлений'}
          </Typography>
        </Box>
      ) : (
        <List disablePadding sx={{ border: '1px solid', borderColor: 'divider', borderRadius: 2, overflow: 'hidden' }}>
          {filtered.map((n, idx) => (
            <Box key={n.id}>
              <ListItem
                sx={{
                  alignItems: 'flex-start',
                  bgcolor: n.is_read ? 'transparent' : 'action.selected',
                  '&:hover': { bgcolor: 'action.hover' },
                  py: 2,
                }}
                secondaryAction={
                  <Stack direction="row" spacing={0.5}>
                    {!n.is_read && (
                      <Tooltip title="Отметить прочитанным">
                        <IconButton
                          size="small"
                          onClick={() => handleMarkAsRead(n.id)}
                          disabled={processing === n.id}
                        >
                          <Iconify icon="eva:checkmark-outline" width={18} />
                        </IconButton>
                      </Tooltip>
                    )}
                    <Tooltip title="Удалить">
                      <IconButton
                        size="small"
                        color="error"
                        onClick={() => handleDelete(n.id)}
                        disabled={processing === n.id}
                      >
                        <Iconify icon="eva:trash-2-outline" width={18} />
                      </IconButton>
                    </Tooltip>
                  </Stack>
                }
              >
                <Box sx={{ mr: 2, mt: 0.5 }}>
                  <Iconify
                    icon={notifIcon(n.type || n.notification_type)}
                    width={22}
                    color={notifColor(n.type || n.notification_type)}
                  />
                </Box>
                <ListItemText
                  primary={
                    <Stack direction="row" alignItems="center" spacing={1}>
                      <Typography variant="subtitle2">
                        {n.title || 'Уведомление'}
                      </Typography>
                      {!n.is_read && (
                        <Box
                          sx={{
                            width: 8,
                            height: 8,
                            borderRadius: '50%',
                            bgcolor: 'primary.main',
                            flexShrink: 0,
                          }}
                        />
                      )}
                    </Stack>
                  }
                  secondary={
                    <>
                      <Typography variant="body2" color="text.secondary" component="span" sx={{ display: 'block' }}>
                        {n.message}
                      </Typography>
                      <Typography variant="caption" color="text.disabled" component="span">
                        {formatDate(n.created_at)}
                      </Typography>
                    </>
                  }
                />
              </ListItem>
              {idx < filtered.length - 1 && <Divider />}
            </Box>
          ))}
        </List>
      )}
    </DashboardContent>
  );
}
