'use client';

import React from 'react';
import {
  Box,
  Group,
  Text,
  ActionIcon,
  ThemeIcon,
  Stack,
  Button,
  rem,
  Avatar,
  Progress,
  Badge,
  Anchor,
} from '@mantine/core';
import {
  IconX,
  IconCheck,
  IconAlertCircle,
  IconInfoCircle,
  IconExclamationCircle,
  IconExternalLink,
  IconClock,
  IconCircleCheck,
  IconCircleX,
  IconCircleDashed,
  IconCircleOff,
} from '@tabler/icons-react';
import { Notification, NotificationType } from '../../types';

interface NotificationItemProps {
  notification: Notification;
  onRead?: () => void;
  onDismiss?: () => void;
  onAction?: (action: any) => void;
}

export function NotificationItem({
  notification,
  onRead,
  onDismiss,
  onAction,
}: NotificationItemProps) {
  const getIcon = (type: NotificationType) => {
    switch (type) {
      case 'success':
        return <IconCheck size={16} />;
      case 'error':
        return <IconX size={16} />;
      case 'warning':
        return <IconExclamationCircle size={16} />;
      case 'loading':
        return <IconClock size={16} />;
      case 'info':
      default:
        return <IconInfoCircle size={16} />;
    }
  };

  const getStatusIcon = (type: string) => {
    switch (type) {
      case 'pending':
        return <IconCircleDashed size={16} />;
      case 'processing':
        return <IconClock size={16} />;
      case 'completed':
        return <IconCircleCheck size={16} />;
      case 'failed':
        return <IconCircleX size={16} />;
      case 'cancelled':
        return <IconCircleOff size={16} />;
      default:
        return <IconInfoCircle size={16} />;
    }
  };

  const getColor = (type: NotificationType) => {
    switch (type) {
      case 'success':
        return 'green';
      case 'error':
        return 'red';
      case 'warning':
        return 'yellow';
      case 'loading':
        return 'blue';
      case 'info':
      default:
        return 'blue';
    }
  };

  const getStatusColor = (type: string) => {
    switch (type) {
      case 'pending':
        return 'gray';
      case 'processing':
        return 'blue';
      case 'completed':
        return 'green';
      case 'failed':
        return 'red';
      case 'cancelled':
        return 'orange';
      default:
        return 'gray';
    }
  };

  const timeAgo = (date: Date) => {
    const seconds = Math.floor((new Date().getTime() - date.getTime()) / 1000);
    
    if (seconds < 60) return 'just now';
    if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
    if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
    return `${Math.floor(seconds / 86400)}d ago`;
  };

  const handleClick = () => {
    if (!notification.readAt && onRead) {
      onRead();
    }
  };

  return (
    <Box
      p="md"
      style={{
        borderBottom: '1px solid var(--mantine-color-gray-2)',
        backgroundColor: notification.readAt ? 'transparent' : 'var(--mantine-color-blue-0)',
        cursor: 'pointer',
        transition: 'background-color 150ms ease',
      }}
      onClick={handleClick}
    >
      <Group align="flex-start" gap="sm" wrap="nowrap">
        {notification.avatar ? (
          <Avatar
            src={notification.avatar.src}
            alt={notification.avatar.alt}
            color={notification.avatar.color}
            radius="xl"
            size="md"
          >
            {notification.avatar.icon || notification.avatar.name}
          </Avatar>
        ) : (
          <ThemeIcon
            color={getColor(notification.type)}
            variant="light"
            size="md"
            radius="xl"
          >
            {getIcon(notification.type)}
          </ThemeIcon>
        )}

        <Stack gap="xs" style={{ flex: 1 }}>
          <Group justify="space-between" gap="xs" wrap="nowrap">
            <Group gap="xs" wrap="nowrap">
              <Text fw={600} size="sm" lineClamp={1}>
                {notification.title}
              </Text>
              {notification.badge && (
                <Badge
                  color={notification.badge.color}
                  variant={notification.badge.variant || 'light'}
                  size={notification.badge.size || 'sm'}
                >
                  {notification.badge.label}
                </Badge>
              )}
            </Group>
            <Group gap="xs" wrap="nowrap">
              <Text size="xs" c="dimmed">
                {timeAgo(notification.createdAt)}
              </Text>
              {onDismiss && (
                <ActionIcon
                  size="sm"
                  variant="subtle"
                  color="gray"
                  onClick={(e) => {
                    e.stopPropagation();
                    onDismiss();
                  }}
                >
                  <IconX size={14} />
                </ActionIcon>
              )}
            </Group>
          </Group>

          {notification.message && (
            <Text size="sm" c="dimmed" lineClamp={2}>
              {notification.message}
            </Text>
          )}

          {notification.status && (
            <Group gap="xs">
              <ThemeIcon
                color={notification.status.color || getStatusColor(notification.status.type)}
                variant="light"
                size="sm"
                radius="xl"
              >
                {notification.status.icon || getStatusIcon(notification.status.type)}
              </ThemeIcon>
              <Text size="sm" c={notification.status.color || getStatusColor(notification.status.type)}>
                {notification.status.label || notification.status.type}
              </Text>
            </Group>
          )}

          {notification.progress && (
            <Box>
              {notification.progress.label && (
                <Text size="xs" c="dimmed" mb={4}>
                  {notification.progress.label}
                </Text>
              )}
              <Progress
                value={notification.progress.value}
                size="sm"
                color={notification.progress.color}
                animated={notification.progress.animated}
                striped={notification.progress.striped}
              />
            </Box>
          )}

          {notification.link && (
            <Anchor
              href={notification.link.href}
              target={notification.link.target || '_self'}
              size="sm"
              onClick={(e) => e.stopPropagation()}
            >
              <Group gap={4}>
                <Text>{notification.link.label || notification.link.href}</Text>
                {notification.link.external && <IconExternalLink size={14} />}
              </Group>
            </Anchor>
          )}

          {notification.actions && notification.actions.length > 0 && (
            <Group gap="xs" mt="xs">
              {notification.actions.map((action, index) => (
                <Button
                  key={index}
                  size="xs"
                  variant={action.style === 'primary' ? 'filled' : 'light'}
                  color={action.style === 'danger' ? 'red' : undefined}
                  leftSection={action.icon}
                  onClick={(e) => {
                    e.stopPropagation();
                    if (action.action === 'dismiss' && onDismiss) {
                      onDismiss();
                    } else if (typeof action.action === 'function') {
                      action.action();
                    } else if (onAction) {
                      onAction(action);
                    }
                  }}
                >
                  {action.label}
                </Button>
              ))}
            </Group>
          )}
        </Stack>
      </Group>
    </Box>
  );
}