import React from 'react';
import { Badge, Button, Drawer, Empty, List, Segmented, Space, Switch, Tag, Typography } from 'antd';
import { BellOutlined, CheckOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { useNavigate } from 'react-router-dom';
import { request } from '@/request';

const { Text } = Typography;

const severityColor = {
  info: 'blue',
  success: 'green',
  warning: 'gold',
  error: 'red',
};

export default function Notifications() {
  const navigate = useNavigate();
  const [open, setOpen] = React.useState(false);
  const [filter, setFilter] = React.useState('all');
  const [notifications, setNotifications] = React.useState([]);
  const [count, setCount] = React.useState(0);
  const [preferences, setPreferences] = React.useState(null);

  const load = React.useCallback(async () => {
    const [listResponse, countResponse, prefResponse] = await Promise.all([
      request.get({ entity: `notification?limit=30${filter === 'unread' ? '&unread=true' : ''}` }),
      request.get({ entity: 'notification/unread-count' }),
      request.get({ entity: 'notification/preferences' }),
    ]);
    setNotifications(listResponse?.result || []);
    setCount(countResponse?.result?.count || 0);
    setPreferences(prefResponse?.result || null);
  }, [filter]);

  React.useEffect(() => { load(); }, [load]);
  React.useEffect(() => {
    const timer = setInterval(load, 20000);
    return () => clearInterval(timer);
  }, [load]);

  const markRead = async (id) => {
    await request.patch({ entity: `notification/${id}/read`, jsonData: {} });
    await load();
  };

  const markAll = async () => {
    await request.post({ entity: 'notification/read-all', jsonData: {} });
    await load();
  };

  const savePreferences = async (next) => {
    await request.patch({ entity: 'notification/preferences', jsonData: next });
    setPreferences(next);
  };

  const openNotification = async (item) => {
    if (!item.readAt) await markRead(item._id);
    if (item.actionUrl) navigate(item.actionUrl);
    setOpen(false);
  };

  return (
    <>
      <Badge count={count} size="small">
        <Button shape="circle" icon={<BellOutlined />} onClick={() => setOpen(true)} />
      </Badge>
      <Drawer
        title="Notifications"
        open={open}
        onClose={() => setOpen(false)}
        width={420}
        extra={<Space><Button size="small" onClick={markAll}>Mark all read</Button></Space>}
      >
        <Space direction="vertical" size={16} style={{ width: '100%' }}>
          <Segmented value={filter} onChange={setFilter} options={[{ label: 'All', value: 'all' }, { label: 'Unread', value: 'unread' }]} />
          {preferences ? (
            <Space wrap style={{ width: '100%', justifyContent: 'space-between' }}>
              <Space><Text type="secondary">Email</Text><Switch size="small" checked={preferences.email !== false} onChange={(email) => savePreferences({ ...preferences, email })} /></Space>
              <Space><Text type="secondary">WhatsApp</Text><Switch size="small" checked={preferences.whatsapp === true} onChange={(whatsapp) => savePreferences({ ...preferences, whatsapp })} /></Space>
            </Space>
          ) : null}
          <List
            locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="No notifications yet" /> }}
            dataSource={notifications}
            renderItem={(item) => (
              <List.Item
                actions={[
                  !item.readAt ? <Button size="small" icon={<CheckOutlined />} onClick={() => markRead(item._id)}>Read</Button> : null,
                ].filter(Boolean)}
              >
                <List.Item.Meta
                  title={<Space><Tag color={severityColor[item.severity] || 'default'}>{item.severity || 'info'}</Tag><span>{item.title}</span>{!item.readAt ? <Badge status="processing" /> : null}</Space>}
                  description={
                    <button type="button" style={{ border: 0, background: 'transparent', padding: 0, textAlign: 'left', cursor: 'pointer' }} onClick={() => openNotification(item)}>
                      <Space direction="vertical" size={2}>
                        <Text>{item.message}</Text>
                        <Text type="secondary">{dayjs(item.created).format('DD MMM, HH:mm')}</Text>
                      </Space>
                    </button>
                  }
                />
              </List.Item>
            )}
          />
        </Space>
      </Drawer>
    </>
  );
}
