import { useState, useMemo, useEffect, CSSProperties } from 'react';
import { Typography, Badge, Segmented, Button, List, Card, Avatar, Empty, Skeleton, message } from 'antd';
import { ArrowLeftOutlined, CheckOutlined, BookOutlined, CheckCircleOutlined, ClockCircleOutlined, ExclamationCircleOutlined, TagOutlined, DollarOutlined, CreditCardOutlined } from '@ant-design/icons';
import { request } from '../api/client';
import { useNavigate } from 'react-router-dom';
import { useAppContext } from '../store/AppContext';
import { ROUTES } from '../router/routes.constant';

interface AuditlogResponse {
  id: string;
  user_id: string | null;
  action_type: string;
  entity_type: string | null;
  entity_id: string | null;
  timestamp: string;
  ip_address: string | null;
  details: Record<string, unknown> | null;
  created_at: string;
  updated_at: string;
}

interface NotificationItem {
  id: string;
  user_id: string;
  type: string;
  title: string;
  message: string;
  is_read: boolean;
  created_at: string;
  related_entity_id: string | null;
  related_entity_type: string | null;
}

export default function NotificationsPage() {
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate();
  const { currentUser } = useAppContext();

  const [notifications, setNotifications] = useState<NotificationItem[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [filterType, setFilterType] = useState<'all' | 'unread'>('all');

  const unreadCount = useMemo(() => {
    return notifications.filter(n => !n.is_read).length;
  }, [notifications]);

  const filteredNotifications = useMemo(() => {
    return filterType === 'unread' ? notifications.filter(n => !n.is_read) : notifications;
  }, [filterType, notifications]);

  const hasNotifications = useMemo(() => {
    return notifications.length > 0;
  }, [notifications]);

  const hasUnread = useMemo(() => {
    return notifications.some(n => !n.is_read);
  }, [notifications]);

  useEffect(() => {
    const fetchNotifications = async () => {
      if (!currentUser?.id) {
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        const result = await request<AuditlogResponse[]>({
          method: 'GET',
          path: '/system/audit-logs',
          query: {
            user_id: currentUser.id,
            limit: 100,
            offset: 0
          }
        });

        const transformedNotifications: NotificationItem[] = result.data.map(log => ({
          id: log.id,
          user_id: log.user_id || '',
          type: log.action_type,
          title: log.action_type,
          message: `${log.entity_type || 'Entity'} ${log.entity_id || ''}`,
          is_read: false,
          created_at: log.timestamp,
          related_entity_id: log.entity_id,
          related_entity_type: log.entity_type
        }));

        setNotifications(transformedNotifications);
      } catch (error) {
        messageApi.error('Failed to load notifications');
      } finally {
        setLoading(false);
      }
    };

    fetchNotifications();
  }, [currentUser, messageApi]);

  const onFilterChange = (value: string | number) => {
    setFilterType(value as 'all' | 'unread');
  };

  const markAsRead = (item: NotificationItem) => {
    setNotifications(notifications.map(n => n.id === item.id ? { ...n, is_read: true } : n));
  };

  const markAllAsRead = () => {
    setNotifications(notifications.map(n => ({ ...n, is_read: true })));
    messageApi.success('All notifications marked as read');
  };

  const navigateToDashboard = () => {
    navigate(ROUTES.DASHBOARD || '/dashboard');
  };

  const navigateToBook = (bookId: string) => {
    navigate(`/books/${bookId}`);
  };

  const navigateToHistory = () => {
    navigate('/dashboard/history');
  };

  const getNotificationIcon = (type: string) => {
    const lowerType = type.toLowerCase();
    if (lowerType.includes('checkout')) {
      return <Avatar icon={<BookOutlined />} style={{ backgroundColor: '#52c41a' }} />;
    }
    if (lowerType.includes('return')) {
      return <Avatar icon={<CheckCircleOutlined />} style={{ backgroundColor: '#1677ff' }} />;
    }
    if (lowerType.includes('due') || lowerType.includes('reminder')) {
      return <Avatar icon={<ClockCircleOutlined />} style={{ backgroundColor: '#faad14' }} />;
    }
    if (lowerType.includes('overdue')) {
      return <Avatar icon={<ExclamationCircleOutlined />} style={{ backgroundColor: '#ff4d4f' }} />;
    }
    if (lowerType.includes('reservation')) {
      return <Avatar icon={<TagOutlined />} style={{ backgroundColor: '#722ed1' }} />;
    }
    if (lowerType.includes('fine')) {
      return <Avatar icon={<DollarOutlined />} style={{ backgroundColor: '#eb2f96' }} />;
    }
    if (lowerType.includes('payment')) {
      return <Avatar icon={<CreditCardOutlined />} style={{ backgroundColor: '#13c2c2' }} />;
    }
    return <Avatar icon={<BookOutlined />} style={{ backgroundColor: '#52c41a' }} />;
  };

  const mainContainerStyle: CSSProperties = {
    minHeight: '100vh',
    height: '100%',
    width: '100%',
    display: 'flex',
    flexDirection: 'column',
    padding: '24px',
    backgroundColor: '#f5f5f5'
  };

  const contentWrapperStyle: CSSProperties = {
    maxWidth: '800px',
    margin: '0 auto',
    width: '100%'
  };

  const pageHeaderStyle: CSSProperties = {
    marginBottom: '24px'
  };

  const headerTopRowStyle: CSSProperties = {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: '8px'
  };

  const headerActionsStyle: CSSProperties = {
    display: 'flex',
    gap: '12px',
    alignItems: 'center'
  };

  const notificationContentStyle: CSSProperties = {
    flex: 1,
    marginLeft: '12px'
  };

  return (
    <div style={mainContainerStyle}>
      {contextHolder}
      <div style={contentWrapperStyle}>
        <div style={pageHeaderStyle}>
          <Button
            type="link"
            icon={<ArrowLeftOutlined />}
            onClick={navigateToDashboard}
            style={{ paddingLeft: '0' }}
          >
            Back to Dashboard
          </Button>
          <div style={headerTopRowStyle}>
            <Typography.Title level={2} style={{ margin: '0' }}>
              Notifications
            </Typography.Title>
            <Badge count={unreadCount} showZero={false} color="#1677ff" />
          </div>
          <div style={headerActionsStyle}>
            <Segmented
              value={filterType}
              onChange={onFilterChange}
              options={[
                { label: 'All', value: 'all' },
                { label: 'Unread', value: 'unread' }
              ]}
            />
            <Button
              type="primary"
              ghost
              disabled={!hasUnread}
              icon={<CheckOutlined />}
              onClick={markAllAsRead}
            >
              Mark All as Read
            </Button>
          </div>
        </div>

        {loading ? (
          <Skeleton active avatar paragraph={{ rows: 2 }} />
        ) : filteredNotifications.length === 0 ? (
          <Empty
            description="You're all caught up! No notifications to display."
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            style={{ padding: '80px 0' }}
          />
        ) : (
          <List
            dataSource={filteredNotifications}
            loading={loading}
            locale={{ emptyText: 'No notifications' }}
            itemLayout="horizontal"
            renderItem={(item) => (
              <List.Item
                style={{ padding: 0, border: 'none', marginBottom: '8px' }}
                onClick={() => markAsRead(item)}
              >
                <Card
                  hoverable
                  size="small"
                  style={{
                    width: '100%',
                    borderLeft: item.is_read ? '3px solid transparent' : '3px solid #1677ff'
                  }}
                  bodyStyle={{ display: 'flex', alignItems: 'center', padding: '12px' }}
                >
                  {getNotificationIcon(item.type)}
                  <div style={notificationContentStyle}>
                    <Typography.Text strong style={{ display: 'block', marginBottom: '4px' }}>
                      {item.title}
                    </Typography.Text>
                    <Typography.Text type="secondary" style={{ display: 'block', marginBottom: '4px' }}>
                      {item.message}
                    </Typography.Text>
                    <Typography.Text type="secondary" style={{ fontSize: '12px' }}>
                      {new Date(item.created_at).toLocaleString()}
                    </Typography.Text>
                  </div>
                  {!item.is_read && <Badge status="processing" dot style={{ marginLeft: '8px' }} />}
                </Card>
              </List.Item>
            )}
          />
        )}
      </div>
    </div>
  );
}