'use client';

import React, { useState, useMemo } from 'react';
import {
  Paper,
  Stack,
  Title,
  Text,
  SegmentedControl,
  Box,
  Group,
  Badge,
  ScrollArea,
  ActionIcon,
  Tooltip,
} from '@mantine/core';
import { IconDeviceMobile, IconDeviceDesktop, IconCode } from '@tabler/icons-react';
import { EmailTemplate } from '../../types';

interface EmailPreviewProps {
  template: EmailTemplate | string;
  data?: any;
  showDeviceFrames?: boolean;
  className?: string;
}

export function EmailPreview({
  template,
  data = {},
  showDeviceFrames = true,
  className,
}: EmailPreviewProps) {
  const [viewMode, setViewMode] = useState<'desktop' | 'mobile' | 'html'>('desktop');
  const [format, setFormat] = useState<'html' | 'text'>('html');

  // Compile template
  const compiled = useMemo(() => {
    if (typeof template === 'string') {
      return {
        subject: 'No subject',
        html: '<p>Template not found</p>',
        text: 'Template not found',
      };
    }

    const subject = typeof template.subject === 'function'
      ? template.subject(data)
      : template.subject;

    const html = typeof template.body.html === 'function'
      ? template.body.html(data)
      : template.body.html;

    const text = template.body.text
      ? typeof template.body.text === 'function'
        ? template.body.text(data)
        : template.body.text
      : 'Text version not available';

    return { subject, html, text };
  }, [template, data]);

  const renderContent = () => {
    if (format === 'text') {
      return (
        <Box
          p="md"
          style={{
            fontFamily: 'monospace',
            whiteSpace: 'pre-wrap',
            backgroundColor: '#f8f9fa',
          }}
        >
          {compiled.text}
        </Box>
      );
    }

    if (viewMode === 'html') {
      return (
        <Box
          p="md"
          style={{
            fontFamily: 'monospace',
            fontSize: '12px',
            backgroundColor: '#1e1e1e',
            color: '#d4d4d4',
            overflow: 'auto',
          }}
        >
          <pre>{compiled.html}</pre>
        </Box>
      );
    }

    const content = (
      <Box
        style={{
          width: '100%',
          height: '100%',
          backgroundColor: 'white',
        }}
        dangerouslySetInnerHTML={{ __html: compiled.html }}
      />
    );

    if (!showDeviceFrames) {
      return content;
    }

    if (viewMode === 'mobile') {
      return (
        <Box
          style={{
            width: 375,
            height: 667,
            margin: '0 auto',
            border: '16px solid #333',
            borderRadius: 36,
            overflow: 'hidden',
            boxShadow: '0 0 0 2px #666',
          }}
        >
          <ScrollArea h={635}>{content}</ScrollArea>
        </Box>
      );
    }

    return (
      <Box
        style={{
          width: '100%',
          maxWidth: 1200,
          margin: '0 auto',
          border: '1px solid #e2e8f0',
          borderRadius: 8,
          overflow: 'hidden',
        }}
      >
        <Box
          style={{
            backgroundColor: '#f8f9fa',
            padding: '8px 16px',
            borderBottom: '1px solid #e2e8f0',
          }}
        >
          <Group gap="xs">
            <Box
              style={{
                width: 12,
                height: 12,
                borderRadius: '50%',
                backgroundColor: '#ff5f57',
              }}
            />
            <Box
              style={{
                width: 12,
                height: 12,
                borderRadius: '50%',
                backgroundColor: '#ffbd2e',
              }}
            />
            <Box
              style={{
                width: 12,
                height: 12,
                borderRadius: '50%',
                backgroundColor: '#28ca42',
              }}
            />
          </Group>
        </Box>
        <ScrollArea h={600}>{content}</ScrollArea>
      </Box>
    );
  };

  return (
    <Paper shadow="sm" radius="md" p="lg" className={className}>
      <Stack>
        <Group justify="space-between" align="center">
          <div>
            <Title order={4}>Email Preview</Title>
            <Text size="sm" c="dimmed">
              Subject: {compiled.subject}
            </Text>
          </div>
          
          <Group>
            <SegmentedControl
              value={format}
              onChange={(value) => setFormat(value as 'html' | 'text')}
              data={[
                { label: 'HTML', value: 'html' },
                { label: 'Text', value: 'text' },
              ]}
            />
            
            {format === 'html' && (
              <Group gap="xs">
                <Tooltip label="Desktop view">
                  <ActionIcon
                    variant={viewMode === 'desktop' ? 'filled' : 'default'}
                    onClick={() => setViewMode('desktop')}
                  >
                    <IconDeviceDesktop size={18} />
                  </ActionIcon>
                </Tooltip>
                
                <Tooltip label="Mobile view">
                  <ActionIcon
                    variant={viewMode === 'mobile' ? 'filled' : 'default'}
                    onClick={() => setViewMode('mobile')}
                  >
                    <IconDeviceMobile size={18} />
                  </ActionIcon>
                </Tooltip>
                
                <Tooltip label="HTML source">
                  <ActionIcon
                    variant={viewMode === 'html' ? 'filled' : 'default'}
                    onClick={() => setViewMode('html')}
                  >
                    <IconCode size={18} />
                  </ActionIcon>
                </Tooltip>
              </Group>
            )}
          </Group>
        </Group>

        <Box>{renderContent()}</Box>
      </Stack>
    </Paper>
  );
}