'use client';

import { m } from 'framer-motion';
import { useState, useEffect, useCallback } from 'react';

import Box from '@mui/material/Box';
import Tab from '@mui/material/Tab';
import List from '@mui/material/List';
import Stack from '@mui/material/Stack';
import Badge from '@mui/material/Badge';
import Drawer from '@mui/material/Drawer';
import Button from '@mui/material/Button';
import Divider from '@mui/material/Divider';
import SvgIcon from '@mui/material/SvgIcon';
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 { useRouter } from 'src/routes/hooks';

import { useBoolean } from 'src/hooks/use-boolean';

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

import { Label } from 'src/components/label';
import { Iconify } from 'src/components/iconify';
import { varHover } from 'src/components/animate';
import { Scrollbar } from 'src/components/scrollbar';
import { CustomTabs } from 'src/components/custom-tabs';

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

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(n) {
  const t = n.type || n.notification_type || '';
  if (t === 'success') return 'eva:checkmark-circle-2-outline';
  if (t === 'warning') return 'eva:alert-triangle-outline';
  if (t === 'error') return 'eva:close-circle-outline';
  return 'eva:bell-outline';
}

function notifColor(n) {
  const t = n.type || n.notification_type || '';
  if (t === 'success') return 'success.main';
  if (t === 'warning') return 'warning.main';
  if (t === 'error') return 'error.main';
  return 'info.main';
}

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

export function NotificationsDrawer({ sx, ...other }) {
  const drawer = useBoolean();
  const router = useRouter();
  const [currentTab, setCurrentTab] = useState('unread');
  const [notifications, setNotifications] = useState([]);
  const [loading, setLoading] = useState(false);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await getNotifications({ page_size: 50 });
      setNotifications(res.results);
    } catch {
      // silently fail
    } finally {
      setLoading(false);
    }
  }, []);

  // Load when drawer opens
  useEffect(() => {
    if (drawer.value) load();
  }, [drawer.value, load]);

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

  const filtered =
    currentTab === 'unread'
      ? notifications.filter((n) => !n.is_read)
      : notifications;

  const handleMarkAllAsRead = async () => {
    try {
      await markAllAsRead();
      setNotifications((prev) => prev.map((n) => ({ ...n, is_read: true })));
    } catch {
      // ignore
    }
  };

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

  const TABS = [
    { value: 'unread', label: 'Непрочитанные', count: unreadCount },
    { value: 'all', label: 'Все', count: notifications.length },
  ];

  return (
    <>
      <IconButton
        component={m.button}
        whileTap="tap"
        whileHover="hover"
        variants={varHover(1.05)}
        onClick={drawer.onTrue}
        sx={sx}
        {...other}
      >
        <Badge badgeContent={unreadCount} color="error">
          <SvgIcon>
            <path
              fill="currentColor"
              d="M18.75 9v.704c0 .845.24 1.671.692 2.374l1.108 1.723c1.011 1.574.239 3.713-1.52 4.21a25.794 25.794 0 0 1-14.06 0c-1.759-.497-2.531-2.636-1.52-4.21l1.108-1.723a4.393 4.393 0 0 0 .693-2.374V9c0-3.866 3.022-7 6.749-7s6.75 3.134 6.75 7"
              opacity="0.5"
            />
            <path
              fill="currentColor"
              d="M12.75 6a.75.75 0 0 0-1.5 0v4a.75.75 0 0 0 1.5 0zM7.243 18.545a5.002 5.002 0 0 0 9.513 0c-3.145.59-6.367.59-9.513 0"
            />
          </SvgIcon>
        </Badge>
      </IconButton>

      <Drawer
        open={drawer.value}
        onClose={drawer.onFalse}
        anchor="right"
        slotProps={{ backdrop: { invisible: true } }}
        PaperProps={{ sx: { width: 1, maxWidth: 420 } }}
      >
        {/* Head */}
        <Stack
          direction="row"
          alignItems="center"
          sx={{ py: 2, pl: 2.5, pr: 1, minHeight: 68, borderBottom: '1px solid', borderColor: 'divider' }}
        >
          <Typography variant="h6" sx={{ flexGrow: 1 }}>
            Уведомления
          </Typography>
          {unreadCount > 0 && (
            <Tooltip title="Отметить все прочитанными">
              <IconButton color="primary" onClick={handleMarkAllAsRead}>
                <Iconify icon="eva:done-all-fill" />
              </IconButton>
            </Tooltip>
          )}
          <IconButton onClick={drawer.onFalse} sx={{ display: { xs: 'inline-flex', sm: 'none' } }}>
            <Iconify icon="mingcute:close-line" />
          </IconButton>
        </Stack>

        {/* Tabs */}
        <CustomTabs variant="fullWidth" value={currentTab} onChange={(_, v) => setCurrentTab(v)}>
          {TABS.map((tab) => (
            <Tab
              key={tab.value}
              iconPosition="end"
              value={tab.value}
              label={tab.label}
              icon={
                <Label
                  variant={tab.value === currentTab ? 'filled' : 'soft'}
                  color={tab.value === 'unread' ? 'info' : 'default'}
                >
                  {tab.count}
                </Label>
              }
            />
          ))}
        </CustomTabs>

        {/* List */}
        <Scrollbar sx={{ flex: 1 }}>
          {loading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
              <CircularProgress size={28} />
            </Box>
          ) : filtered.length === 0 ? (
            <Box sx={{ textAlign: 'center', py: 6 }}>
              <Iconify icon="eva:bell-off-outline" width={48} color="text.disabled" />
              <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                {currentTab === 'unread' ? 'Нет непрочитанных' : 'Нет уведомлений'}
              </Typography>
            </Box>
          ) : (
            <List disablePadding>
              {filtered.map((n, idx) => (
                <Box key={n.id}>
                  <ListItem
                    sx={{
                      alignItems: 'flex-start',
                      bgcolor: n.is_read ? 'transparent' : 'action.selected',
                      cursor: 'pointer',
                      '&:hover': { bgcolor: 'action.hover' },
                      py: 1.5,
                      px: 2.5,
                    }}
                    onClick={() => !n.is_read && handleMarkOne(n.id)}
                  >
                    <Box sx={{ mr: 1.5, mt: 0.5, flexShrink: 0 }}>
                      <Iconify icon={notifIcon(n)} width={20} color={notifColor(n)} />
                    </Box>
                    <ListItemText
                      primary={
                        <Stack direction="row" alignItems="center" spacing={0.75}>
                          <Typography variant="subtitle2" sx={{ flex: 1 }}>
                            {n.title || 'Уведомление'}
                          </Typography>
                          {!n.is_read && (
                            <Box sx={{ width: 7, height: 7, 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>
          )}
        </Scrollbar>

        {/* Footer */}
        <Box sx={{ p: 1, borderTop: '1px solid', borderColor: 'divider' }}>
          <Button
            fullWidth
            size="large"
            onClick={() => { drawer.onFalse(); router.push(paths.dashboard.notifications); }}
          >
            Смотреть все
          </Button>
        </Box>
      </Drawer>
    </>
  );
}
