import { useEffect, useState } from 'react';
import { List, Typography, Space, Button, Tag, Empty, Pagination, Card, Switch, Select, Skeleton, message } from 'antd';
import { CheckOutlined, DeleteOutlined, BellOutlined } from '@ant-design/icons';
import { useSocialStore } from '@/stores/social.store';
import { api } from '@/lib/api';
import type { NotificationPreferences } from '@/types/social';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';

dayjs.extend(relativeTime);

const TYPE_LABELS: Record<string, { label: string; color: string }> = {
  friend_request: { label: 'Friend Request', color: 'blue' },
  friend_accepted: { label: 'Accepted', color: 'green' },
  poke: { label: 'Poke', color: 'orange' },
  comment: { label: 'Comment', color: 'cyan' },
  upload_approved: { label: 'Approved', color: 'green' },
  upload_rejected: { label: 'Rejected', color: 'red' },
  achievement: { label: 'Achievement', color: 'gold' },
  system: { label: 'System', color: 'default' },
  shift_signup_confirmed: { label: 'Shift Signup', color: 'geekblue' },
  shift_reminder: { label: 'Shift Reminder', color: 'purple' },
  shift_cancelled: { label: 'Shift Cancelled', color: 'red' },
  canvass_session_summary: { label: 'Canvass Summary', color: 'volcano' },
  reengagement: { label: 'We Miss You', color: 'magenta' },
};

export default function NotificationsPage() {
  const {
    notifications, notificationsPagination, loadingNotifications,
    fetchNotifications, markNotificationRead, markAllNotificationsRead,
  } = useSocialStore();
  const [page, setPage] = useState(1);
  const [prefs, setPrefs] = useState<NotificationPreferences | null>(null);
  const [showPrefs, setShowPrefs] = useState(false);

  useEffect(() => {
    fetchNotifications(page);
  }, [page, fetchNotifications]);

  const loadPrefs = async () => {
    try {
      const { data } = await api.get<NotificationPreferences>('/social/notifications/preferences');
      setPrefs(data);
      setShowPrefs(true);
    } catch {
      message.error('Failed to load preferences');
    }
  };

  const updatePref = async (key: string, value: boolean | string) => {
    try {
      const { data } = await api.put<NotificationPreferences>('/social/notifications/preferences', { [key]: value });
      setPrefs(data);
    } catch {
      message.error('Failed to update preference');
    }
  };

  const deleteNotification = async (id: number) => {
    try {
      await api.delete(`/social/notifications/${id}`);
      fetchNotifications(page);
    } catch {
      message.error('Failed to delete notification');
    }
  };

  return (
    <div style={{ padding: '12px 0' }}>
      <Space style={{ width: '100%', justifyContent: 'space-between', marginBottom: 12 }}>
        <Typography.Title level={4} style={{ margin: 0 }}>Notifications</Typography.Title>
        <Space>
          <Button size="small" icon={<BellOutlined />} onClick={loadPrefs}>
            Preferences
          </Button>
          <Button size="small" icon={<CheckOutlined />} onClick={markAllNotificationsRead}>
            Mark All Read
          </Button>
        </Space>
      </Space>

      {showPrefs && prefs && (
        <Card size="small" style={{ marginBottom: 12 }}>
          <Typography.Text strong style={{ display: 'block', marginBottom: 8 }}>Notification Preferences</Typography.Text>
          <Space direction="vertical" style={{ width: '100%' }}>
            <Space style={{ justifyContent: 'space-between', width: '100%' }}>
              <span>Friend Requests</span>
              <Switch size="small" checked={prefs.enableFriendRequests} onChange={(v) => updatePref('enableFriendRequests', v)} />
            </Space>
            <Space style={{ justifyContent: 'space-between', width: '100%' }}>
              <span>Comments</span>
              <Switch size="small" checked={prefs.enableComments} onChange={(v) => updatePref('enableComments', v)} />
            </Space>
            <Space style={{ justifyContent: 'space-between', width: '100%' }}>
              <span>Achievements</span>
              <Switch size="small" checked={prefs.enableAchievements} onChange={(v) => updatePref('enableAchievements', v)} />
            </Space>
            <Space style={{ justifyContent: 'space-between', width: '100%' }}>
              <span>System Updates</span>
              <Switch size="small" checked={prefs.enableSystemUpdates} onChange={(v) => updatePref('enableSystemUpdates', v)} />
            </Space>
            <Space style={{ justifyContent: 'space-between', width: '100%' }}>
              <span>Email Notifications</span>
              <Switch size="small" checked={prefs.emailNotifications} onChange={(v) => updatePref('emailNotifications', v)} />
            </Space>
            <Space style={{ justifyContent: 'space-between', width: '100%' }}>
              <span>Email Digest Frequency</span>
              <Select
                size="small"
                style={{ width: 110 }}
                value={prefs.digestFrequency || 'none'}
                onChange={(v) => updatePref('digestFrequency', v)}
                options={[
                  { value: 'none', label: 'Off' },
                  { value: 'daily', label: 'Daily' },
                  { value: 'weekly', label: 'Weekly' },
                ]}
              />
            </Space>
          </Space>
        </Card>
      )}

      {loadingNotifications ? (
        <Skeleton active paragraph={{ rows: 5 }} />
      ) : notifications.length === 0 ? (
        <Empty description="No notifications yet" />
      ) : (
        <>
          <List
            dataSource={notifications}
            renderItem={(n) => {
              const typeInfo = TYPE_LABELS[n.type] || { label: n.type, color: 'default' };
              return (
                <List.Item
                  style={{
                    background: n.isRead ? undefined : 'rgba(52, 152, 219, 0.08)',
                    padding: '8px 12px',
                    borderRadius: 6,
                    marginBottom: 4,
                  }}
                  actions={[
                    !n.isRead && (
                      <Button
                        key="read"
                        type="text"
                        size="small"
                        icon={<CheckOutlined />}
                        onClick={() => markNotificationRead(n.id)}
                      />
                    ),
                    <Button
                      key="delete"
                      type="text"
                      size="small"
                      danger
                      icon={<DeleteOutlined />}
                      onClick={() => deleteNotification(n.id)}
                    />,
                  ].filter(Boolean)}
                >
                  <List.Item.Meta
                    title={
                      <Space>
                        <Typography.Text strong={!n.isRead}>{n.title}</Typography.Text>
                        <Tag color={typeInfo.color} style={{ fontSize: 11 }}>{typeInfo.label}</Tag>
                      </Space>
                    }
                    description={
                      <>
                        <Typography.Text type="secondary" style={{ fontSize: 13 }}>{n.message}</Typography.Text>
                        <br />
                        <Typography.Text type="secondary" style={{ fontSize: 11 }}>{dayjs(n.createdAt).fromNow()}</Typography.Text>
                      </>
                    }
                  />
                </List.Item>
              );
            }}
          />

          {notificationsPagination && notificationsPagination.totalPages > 1 && (
            <div style={{ textAlign: 'center', marginTop: 12 }}>
              <Pagination
                current={page}
                pageSize={20}
                total={notificationsPagination.total}
                onChange={setPage}
                size="small"
                showSizeChanger={false}
              />
            </div>
          )}
        </>
      )}
    </div>
  );
}
