'use client';

import React, { useEffect } from 'react';
import {
  Box,
  Group,
  Text,
  ActionIcon,
  ThemeIcon,
  Stack,
  Button,
  Progress,
  Badge,
  Anchor,
  Avatar,
  Transition,
  Paper,
} 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 ToastProps {
  notification: Notification;
  onDismiss?: () => void;
  onAction?: (action: any) => void;
  position?: 'top-left' | 'top-center' | 'top-right' | 'bottom-left' | 'bottom-center' | 'bottom-right';
  duration?: number;
}

export function Toast({
  notification,
  onDismiss,
  onAction,
  position = 'top-right',
  duration = 5000,
}: ToastProps) {
  const [mounted, setMounted] = React.useState(false);

  useEffect(() => {
    setMounted(true);
    
    if (duration && duration > 0 && notification.type !== 'loading') {
      const timer = setTimeout(() => {
        handleDismiss();
      }, duration);
      
      return () => clearTimeout(timer);
    }
  }, [duration, notification.type]);

  const handleDismiss = () => {
    setMounted(false);
    setTimeout(() => {
      onDismiss?.();
    }, 300);
  };

  const getIcon = (type: NotificationType) => {
    switch (type) {
      case 'success':
        return <IconCheck size={20} />;
      case 'error':
        return <IconX size={20} />;
      case 'warning':
        return <IconExclamationCircle size={20} />;
      case 'loading':
        return <IconClock size={20} />;
      case 'info':
      default:
        return <IconInfoCircle size={20} />;
    }
  };

  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';
    }
  };

  return (
    <Transition
      mounted={mounted}
      transition="slide-down"
      duration={300}
      timingFunction="ease"
    >
      {(styles) => (
        <Paper
          shadow="lg"
          p="md"
          radius="md"
          style={{
            ...styles,
            minWidth: 350,
            maxWidth: 450,
          }}
        >
          <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="filled"
                size="lg"
                radius="xl"
              >
                {getIcon(notification.type)}
              </ThemeIcon>
            )}

            <Stack gap={8} style={{ flex: 1 }}>
              <Group justify="space-between" gap="xs" wrap="nowrap">
                <Group gap="xs" wrap="nowrap">
                  <Text fw={600} size="sm">
                    {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>
                <ActionIcon
                  size="sm"
                  variant="subtle"
                  color="gray"
                  onClick={handleDismiss}
                >
                  <IconX size={16} />
                </ActionIcon>
              </Group>

              {notification.message && (
                <Text size="sm" c="dimmed">
                  {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={4}>
                  {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') {
                          handleDismiss();
                        } else if (typeof action.action === 'function') {
                          action.action();
                        } else if (onAction) {
                          onAction(action);
                        }
                      }}
                    >
                      {action.label}
                    </Button>
                  ))}
                </Group>
              )}
            </Stack>
          </Group>
        </Paper>
      )}
    </Transition>
  );
}