import { useState, useMemo, useEffect, useCallback, CSSProperties } from 'react';
import { Card, Row, Col, Space, Button, Badge, Typography, List, Avatar, Checkbox, Segmented, Select, Modal, Form, Input, Empty, message } from 'antd';
import { PlusOutlined, CheckOutlined, DeleteOutlined, InfoCircleOutlined, WarningOutlined, AlertOutlined, ClockCircleOutlined, MessageOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useApi } from '@/hooks/useApi';
import { NotificationsService } from '@/services/notifications';
import { useAppContext } from '@/store/AppStore';
import { parseError } from '@/utils/errorHandler';
import { ROUTES } from '@/constants/routes';

interface Notification {
  id: string;
  title: string;
  message: string;
  notification_type: 'INFO' | 'WARNING' | 'ALERT' | 'REMINDER' | 'MESSAGE';
  related_entity_type: string | null;
  related_entity_id: string | null;
  user_id: string;
  is_read: boolean;
  read_at: string | null;
  created_at: string;
  updated_at: string;
}

const NotificationsListPage = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate();
  const { currentUser } = useAppContext();
  const [form] = Form.useForm();

  const [notificationsList, setNotificationsList] = useState<Notification[]>([]);
  const [loading, setLoading] = useState(false);
  const [filterReadStatus, setFilterReadStatus] = useState<'all' | 'unread'>('all');
  const [filterType, setFilterType] = useState<string>('all');
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [announcementModalVisible, setAnnouncementModalVisible] = useState(false);
  const [paginationOffset, setPaginationOffset] = useState(0);

  const { data: fetchedNotifications, loading: fetchLoading, error: fetchError, execute: fetchNotifications } = useApi(NotificationsService.list);

  useEffect(() => {
    if (currentUser?.id) {
      void fetchNotifications({ limit: 50, offset: paginationOffset, user_id: currentUser.id });
    }
  }, [fetchNotifications, paginationOffset, currentUser]);

  useEffect(() => {
    if (fetchedNotifications) {
      setNotificationsList(fetchedNotifications as Notification[]);
    }
  }, [fetchedNotifications]);

  useEffect(() => {
    setLoading(fetchLoading);
  }, [fetchLoading]);

  useEffect(() => {
    if (fetchError) {
      const { message: errorMessage } = parseError(fetchError);
      messageApi.error(errorMessage);
    }
  }, [fetchError, messageApi]);

  const filteredNotifications = useMemo(() => {
    return notificationsList.filter(n => 
      (filterReadStatus === 'all' || (filterReadStatus === 'unread' && !n.is_read)) &&
      (filterType === 'all' || n.notification_type === filterType)
    );
  }, [notificationsList, filterReadStatus, filterType]);

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

  const allSelected = useMemo(() => {
    return selectedIds.length > 0 && selectedIds.length === filteredNotifications.length;
  }, [selectedIds, filteredNotifications]);

  const handleFilterReadStatusChange = useCallback((value: string | number) => {
    setFilterReadStatus(value as 'all' | 'unread');
  }, []);

  const handleFilterTypeChange = useCallback((value: string) => {
    setFilterType(value);
  }, []);

  const handleToggleSelectNotification = useCallback((id: string) => {
    setSelectedIds(prev => 
      prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id]
    );
  }, []);

  const handleToggleSelectAll = useCallback(() => {
    if (allSelected) {
      setSelectedIds([]);
    } else {
      setSelectedIds(filteredNotifications.map(n => n.id));
    }
  }, [allSelected, filteredNotifications]);

  const handleOpenAnnouncementModal = useCallback(() => {
    setAnnouncementModalVisible(true);
  }, []);

  const handleCloseAnnouncementModal = useCallback(() => {
    setAnnouncementModalVisible(false);
    form.resetFields();
  }, [form]);

  const handleNotificationClick = useCallback(async (notification: Notification) => {
    if (!notification.is_read) {
      try {
        await NotificationsService.createMarkRead(notification.id, {});
        setNotificationsList(prev => 
          prev.map(n => n.id === notification.id ? { ...n, is_read: true } : n)
        );
      } catch (e) {
        const { message: errorMessage } = parseError(e);
        messageApi.error(errorMessage);
      }
    }

    if (notification.related_entity_type && notification.related_entity_id) {
      const entityTypeMap: Record<string, string> = {
        production: ROUTES.PRODUCTIONS,
        venue: ROUTES.VENUES,
        task: ROUTES.TASKS,
        booking: ROUTES.BOOKINGS,
      };
      const basePath = entityTypeMap[notification.related_entity_type.toLowerCase()];
      if (basePath) {
        navigate(`${basePath}/${notification.related_entity_id}`);
      }
    }
  }, [messageApi, navigate]);

  const handleMarkAllRead = useCallback(async () => {
    try {
      const unreadNotifications = notificationsList.filter(n => !n.is_read);
      for (const notification of unreadNotifications) {
        await NotificationsService.createMarkRead(notification.id, {});
      }
      setNotificationsList(prev => prev.map(n => ({ ...n, is_read: true })));
      messageApi.success('All notifications marked as read');
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage);
    }
  }, [notificationsList, messageApi]);

  const handleDeleteSelected = useCallback(async () => {
    Modal.confirm({
      title: 'Delete Selected Notifications',
      content: 'Are you sure you want to delete the selected notifications?',
      okText: 'Delete',
      okType: 'danger',
      cancelText: 'Cancel',
      onOk: async () => {
        try {
          for (const id of selectedIds) {
            await NotificationsService.delete(id);
          }
          setNotificationsList(prev => prev.filter(n => !selectedIds.includes(n.id)));
          setSelectedIds([]);
          messageApi.success('Selected notifications deleted');
        } catch (e) {
          const { message: errorMessage } = parseError(e);
          messageApi.error(errorMessage);
        }
      },
    });
  }, [selectedIds, messageApi]);

  const handleAnnouncementSubmit = useCallback(async () => {
    try {
      const values = await form.validateFields();
      if (!values.title) {
        messageApi.error('Title is required');
        return;
      }
      if (!values.message) {
        messageApi.error('Message is required');
        return;
      }

      await NotificationsService.create({
        title: values.title,
        message: values.message,
        notification_type: values.notification_type || 'INFO',
        user_id: currentUser?.id || '',
      });

      messageApi.success('Announcement sent successfully');
      setAnnouncementModalVisible(false);
      form.resetFields();
      if (currentUser?.id) {
        void fetchNotifications({ limit: 50, offset: paginationOffset, user_id: currentUser.id });
      }
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      messageApi.error(errorMessage);
    }
  }, [form, messageApi, currentUser, fetchNotifications, paginationOffset]);

  const getNotificationIcon = (type: string) => {
    const iconMap: Record<string, React.ReactNode> = {
      INFO: <InfoCircleOutlined />,
      WARNING: <WarningOutlined />,
      ALERT: <AlertOutlined />,
      REMINDER: <ClockCircleOutlined />,
      MESSAGE: <MessageOutlined />,
    };
    return iconMap[type] || <InfoCircleOutlined />;
  };

  const mainContainerStyle: CSSProperties = {
    minHeight: '100vh',
    width: '100%',
    background: '#f5f5f5',
    display: 'flex',
    flexDirection: 'column',
  };

  return (
    <div style={mainContainerStyle}>
      {contextHolder}
      <div style={{ padding: '24px 24px 0 24px' }}>
        <Row justify="space-between" align="middle" style={{ marginBottom: '16px' }}>
          <Col>
            <Space align="center">
              <Typography.Title level={2} style={{ margin: 0 }}>
                Notifications
              </Typography.Title>
              {unreadCount > 0 && (
                <Badge count={unreadCount} status="processing" style={{ marginLeft: '12px' }} />
              )}
            </Space>
          </Col>
          <Col>
            <Space size="middle">
              <Button type="primary" icon={<PlusOutlined />} onClick={handleOpenAnnouncementModal}>
                Create Announcement
              </Button>
            </Space>
          </Col>
        </Row>
      </div>

      <div style={{ padding: '0 24px 24px 24px' }}>
        <Card bordered={false} style={{ marginBottom: '16px' }}>
          <Row gutter={16} align="middle">
            <Col xs={24} sm={12} md={8}>
              <Segmented
                options={[
                  { label: 'All', value: 'all' },
                  { label: 'Unread', value: 'unread' },
                ]}
                value={filterReadStatus}
                onChange={handleFilterReadStatusChange}
                block
              />
            </Col>
            <Col xs={24} sm={12} md={8}>
              <Select
                placeholder="Filter by type"
                allowClear
                style={{ width: '100%' }}
                value={filterType}
                onChange={handleFilterTypeChange}
                options={[
                  { label: 'All Types', value: 'all' },
                  { label: 'Info', value: 'INFO' },
                  { label: 'Warning', value: 'WARNING' },
                  { label: 'Alert', value: 'ALERT' },
                  { label: 'Reminder', value: 'REMINDER' },
                  { label: 'Message', value: 'MESSAGE' },
                ]}
              />
            </Col>
            <Col xs={24} sm={24} md={8}>
              <Space size="small">
                <Button icon={<CheckOutlined />} size="middle" onClick={handleMarkAllRead}>
                  Mark All Read
                </Button>
                <Button
                  danger
                  icon={<DeleteOutlined />}
                  size="middle"
                  disabled={selectedIds.length === 0}
                  onClick={handleDeleteSelected}
                >
                  Delete Selected
                </Button>
              </Space>
            </Col>
          </Row>
        </Card>

        <Card bordered={false} bodyStyle={{ padding: 0 }}>
          {filteredNotifications.length === 0 ? (
            <Empty description="No notifications to display" style={{ padding: '48px 0' }} />
          ) : (
            <List
              itemLayout="horizontal"
              loading={loading}
              dataSource={filteredNotifications}
              locale={{ emptyText: 'No notifications' }}
              renderItem={(item) => (
                <List.Item
                  style={{
                    cursor: 'pointer',
                    padding: '16px 24px',
                    borderBottom: '1px solid #f0f0f0',
                    backgroundColor: item.is_read ? '#ffffff' : '#f0f0ff',
                  }}
                  onClick={() => handleNotificationClick(item)}
                >
                  <Space align="start" style={{ width: '100%' }}>
                    <Checkbox
                      checked={selectedIds.includes(item.id)}
                      onChange={(e) => {
                        e.stopPropagation();
                        handleToggleSelectNotification(item.id);
                      }}
                      onClick={(e) => e.stopPropagation()}
                      style={{ marginRight: '12px' }}
                    />
                    <Avatar size={40} icon={getNotificationIcon(item.notification_type)} />
                    <div style={{ flex: 1 }}>
                      <Typography.Text strong style={{ display: 'block', marginBottom: '4px' }}>
                        {item.title}
                      </Typography.Text>
                      <Typography.Paragraph
                        ellipsis={{ rows: 2 }}
                        type="secondary"
                        style={{ marginBottom: '4px' }}
                      >
                        {item.message}
                      </Typography.Paragraph>
                      <Typography.Text type="secondary" style={{ fontSize: '12px' }}>
                        {new Date(item.created_at).toLocaleString()}
                      </Typography.Text>
                    </div>
                    {!item.is_read && <Badge dot status="processing" />}
                  </Space>
                </List.Item>
              )}
            />
          )}
        </Card>
      </div>

      <Modal
        title="Create Announcement"
        open={announcementModalVisible}
        onCancel={handleCloseAnnouncementModal}
        onOk={handleAnnouncementSubmit}
        width={640}
        destroyOnClose
        okText="Send Announcement"
        cancelText="Cancel"
      >
        <Form form={form} layout="vertical">
          <Form.Item
            label="Title"
            name="title"
            rules={[{ required: true, message: 'Title is required' }]}
          >
            <Input placeholder="Enter announcement title" maxLength={200} />
          </Form.Item>
          <Form.Item
            label="Message"
            name="message"
            rules={[{ required: true, message: 'Message is required' }]}
          >
            <Input.TextArea
              placeholder="Enter announcement message"
              rows={6}
              maxLength={2000}
              showCount
            />
          </Form.Item>
          <Form.Item label="Target Audience" name="target_audience">
            <Select
              placeholder="Select target audience"
              mode="multiple"
              style={{ width: '100%' }}
              options={[
                { label: 'All Users', value: 'all_users' },
                { label: 'Administrators', value: 'ADMINISTRATOR' },
                { label: 'Venue Managers', value: 'VENUE_MANAGER' },
                { label: 'Production Managers', value: 'PRODUCTION_MANAGER' },
                { label: 'Technical Directors', value: 'TECHNICAL_DIRECTOR' },
                { label: 'Staff Members', value: 'STAFF_MEMBER' },
                { label: 'Performers', value: 'PERFORMER' },
              ]}
            />
          </Form.Item>
          <Form.Item label="Notification Type" name="notification_type" initialValue="INFO">
            <Select
              style={{ width: '100%' }}
              options={[
                { label: 'Info', value: 'INFO' },
                { label: 'Warning', value: 'WARNING' },
                { label: 'Alert', value: 'ALERT' },
                { label: 'Reminder', value: 'REMINDER' },
                { label: 'Message', value: 'MESSAGE' },
              ]}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default NotificationsListPage;