import React, { useState, useEffect, useRef } from 'react';
import Frame from 'react-frame-component';
import { Box, HStack, IconButton, Text, Tooltip, VStack, Badge } from '@chakra-ui/react';
import { FiMonitor, FiTablet, FiSmartphone, FiRotateCw, FiMaximize2 } from 'react-icons/fi';

export interface DevicePreset {
  name: string;
  width: number;
  height: number;
  userAgent: string;
  icon: React.ReactElement;
  category: 'mobile' | 'tablet' | 'desktop';
}

export const DEVICE_PRESETS: Record<string, DevicePreset> = {
  // Mobile devices
  iphone_se: {
    name: 'iPhone SE',
    width: 375,
    height: 667,
    userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15',
    icon: <FiSmartphone />,
    category: 'mobile',
  },
  iphone_14: {
    name: 'iPhone 14 Pro',
    width: 393,
    height: 852,
    userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15',
    icon: <FiSmartphone />,
    category: 'mobile',
  },
  pixel_7: {
    name: 'Pixel 7',
    width: 412,
    height: 915,
    userAgent: 'Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36',
    icon: <FiSmartphone />,
    category: 'mobile',
  },
  samsung_s23: {
    name: 'Samsung S23',
    width: 360,
    height: 800,
    userAgent: 'Mozilla/5.0 (Linux; Android 13; SM-S911B) AppleWebKit/537.36',
    icon: <FiSmartphone />,
    category: 'mobile',
  },
  
  // Tablets
  ipad_mini: {
    name: 'iPad Mini',
    width: 768,
    height: 1024,
    userAgent: 'Mozilla/5.0 (iPad; CPU OS 15_0 like Mac OS X) AppleWebKit/605.1.15',
    icon: <FiTablet />,
    category: 'tablet',
  },
  ipad_air: {
    name: 'iPad Air',
    width: 820,
    height: 1180,
    userAgent: 'Mozilla/5.0 (iPad; CPU OS 16_0 like Mac OS X) AppleWebKit/605.1.15',
    icon: <FiTablet />,
    category: 'tablet',
  },
  ipad_pro: {
    name: 'iPad Pro 12.9"',
    width: 1024,
    height: 1366,
    userAgent: 'Mozilla/5.0 (iPad; CPU OS 16_0 like Mac OS X) AppleWebKit/605.1.15',
    icon: <FiTablet />,
    category: 'tablet',
  },
  
  // Desktop
  desktop_1080: {
    name: 'Desktop 1080p',
    width: 1920,
    height: 1080,
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    icon: <FiMonitor />,
    category: 'desktop',
  },
  desktop_1440: {
    name: 'Desktop 1440p',
    width: 2560,
    height: 1440,
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    icon: <FiMonitor />,
    category: 'desktop',
  },
  laptop: {
    name: 'Laptop',
    width: 1366,
    height: 768,
    userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
    icon: <FiMonitor />,
    category: 'desktop',
  },
};

interface ViewportSimulatorProps {
  children: React.ReactNode;
  defaultDevice?: string;
  showControls?: boolean;
  customCSS?: string;
  onDeviceChange?: (device: DevicePreset) => void;
}

const ViewportSimulator: React.FC<ViewportSimulatorProps> = ({
  children,
  defaultDevice = 'desktop_1080',
  showControls = true,
  customCSS = '',
  onDeviceChange,
}) => {
  const [currentDevice, setCurrentDevice] = useState<string>(defaultDevice);
  const [isPortrait, setIsPortrait] = useState(true);
  const [scale, setScale] = useState(1);
  const containerRef = useRef<HTMLDivElement>(null);
  const frameRef = useRef<HTMLIFrameElement>(null);

  const device = DEVICE_PRESETS[currentDevice];
  const width = isPortrait ? device.width : device.height;
  const height = isPortrait ? device.height : device.width;

  // Auto-scale to fit container
  useEffect(() => {
    if (!containerRef.current) return;

    const updateScale = () => {
      const container = containerRef.current;
      if (!container) return;

      const containerWidth = container.clientWidth;
      const containerHeight = container.clientHeight - (showControls ? 80 : 0);

      // Calculate scale to fit both width and height
      const scaleX = containerWidth / (width + 40); // +40 for padding/borders
      const scaleY = containerHeight / (height + 40);
      const newScale = Math.min(scaleX, scaleY, 1); // Don't scale up, only down

      setScale(newScale);
    };

    updateScale();

    const resizeObserver = new ResizeObserver(updateScale);
    if (containerRef.current) {
      resizeObserver.observe(containerRef.current);
    }

    return () => resizeObserver.disconnect();
  }, [width, height, showControls]);

  // Change device
  const changeDevice = (deviceKey: string) => {
    setCurrentDevice(deviceKey);
    setIsPortrait(true);
    if (onDeviceChange) {
      onDeviceChange(DEVICE_PRESETS[deviceKey]);
    }
  };

  // Rotate device
  const rotateDevice = () => {
    setIsPortrait(!isPortrait);
  };

  // Reset to full width
  const resetToDesktop = () => {
    changeDevice('desktop_1080');
  };

  // Inject CSS into iframe
  const frameContent = `
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=${width}, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
        <style>
          * {
            box-sizing: border-box;
          }
          
          html, body {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            overflow-x: hidden;
            overflow-y: auto;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
          }

          /* Import parent styles if needed */
          @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
          
          body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
            background: #ffffff;
            color: #1a202c;
          }

          /* Responsive breakpoints - REAL media queries */
          @media (max-width: 767px) {
            /* Mobile styles */
            .container {
              padding: 16px !important;
            }
          }

          @media (min-width: 768px) and (max-width: 1023px) {
            /* Tablet styles */
            .container {
              padding: 24px !important;
            }
          }

          @media (min-width: 1024px) {
            /* Desktop styles */
            .container {
              padding: 32px !important;
            }
          }

          /* Custom CSS injection */
          ${customCSS}
        </style>
      </head>
      <body>
        <div id="frame-root"></div>
      </body>
    </html>
  `;

  return (
    <VStack
      ref={containerRef}
      width="100%"
      height="100%"
      spacing={0}
      align="stretch"
      bg="gray.50"
      position="relative"
    >
      {/* Controls */}
      {showControls && (
        <HStack
          spacing={2}
          p={3}
          bg="white"
          borderBottom="1px solid"
          borderColor="gray.200"
          flexWrap="wrap"
          justify="space-between"
        >
          <HStack spacing={2} flexWrap="wrap">
            {/* Mobile */}
            <Tooltip label="iPhone SE">
              <IconButton
                aria-label="iPhone SE"
                icon={<FiSmartphone />}
                size="sm"
                colorScheme={currentDevice === 'iphone_se' ? 'blue' : 'gray'}
                variant={currentDevice === 'iphone_se' ? 'solid' : 'outline'}
                onClick={() => changeDevice('iphone_se')}
              />
            </Tooltip>
            
            <Tooltip label="iPhone 14 Pro">
              <IconButton
                aria-label="iPhone 14 Pro"
                icon={<FiSmartphone />}
                size="sm"
                colorScheme={currentDevice === 'iphone_14' ? 'blue' : 'gray'}
                variant={currentDevice === 'iphone_14' ? 'solid' : 'outline'}
                onClick={() => changeDevice('iphone_14')}
              />
            </Tooltip>

            {/* Tablet */}
            <Tooltip label="iPad Mini">
              <IconButton
                aria-label="iPad Mini"
                icon={<FiTablet />}
                size="sm"
                colorScheme={currentDevice === 'ipad_mini' ? 'blue' : 'gray'}
                variant={currentDevice === 'ipad_mini' ? 'solid' : 'outline'}
                onClick={() => changeDevice('ipad_mini')}
              />
            </Tooltip>

            <Tooltip label="iPad Air">
              <IconButton
                aria-label="iPad Air"
                icon={<FiTablet />}
                size="sm"
                colorScheme={currentDevice === 'ipad_air' ? 'blue' : 'gray'}
                variant={currentDevice === 'ipad_air' ? 'solid' : 'outline'}
                onClick={() => changeDevice('ipad_air')}
              />
            </Tooltip>

            {/* Desktop */}
            <Tooltip label="Laptop">
              <IconButton
                aria-label="Laptop"
                icon={<FiMonitor />}
                size="sm"
                colorScheme={currentDevice === 'laptop' ? 'blue' : 'gray'}
                variant={currentDevice === 'laptop' ? 'solid' : 'outline'}
                onClick={() => changeDevice('laptop')}
              />
            </Tooltip>

            <Tooltip label="Desktop 1080p">
              <IconButton
                aria-label="Desktop"
                icon={<FiMonitor />}
                size="sm"
                colorScheme={currentDevice === 'desktop_1080' ? 'blue' : 'gray'}
                variant={currentDevice === 'desktop_1080' ? 'solid' : 'outline'}
                onClick={() => changeDevice('desktop_1080')}
              />
            </Tooltip>

            {/* Rotate */}
            {device.category !== 'desktop' && (
              <Tooltip label="Otočit zařízení">
                <IconButton
                  aria-label="Rotate"
                  icon={<FiRotateCw />}
                  size="sm"
                  onClick={rotateDevice}
                  colorScheme="purple"
                  variant="outline"
                />
              </Tooltip>
            )}

            {/* Reset */}
            <Tooltip label="Resetovat na desktop">
              <IconButton
                aria-label="Reset"
                icon={<FiMaximize2 />}
                size="sm"
                onClick={resetToDesktop}
                variant="ghost"
              />
            </Tooltip>
          </HStack>

          <HStack spacing={3}>
            <Badge colorScheme="blue" fontSize="xs">
              {device.name}
            </Badge>
            <Text fontSize="xs" color="gray.600">
              {width} × {height}px
            </Text>
            <Text fontSize="xs" color="gray.500">
              {(scale * 100).toFixed(0)}%
            </Text>
          </HStack>
        </HStack>
      )}

      {/* Viewport Frame */}
      <Box
        flex={1}
        display="flex"
        alignItems="center"
        justifyContent="center"
        p={4}
        overflow="auto"
        position="relative"
      >
        <Box
          style={{
            width: `${width}px`,
            height: `${height}px`,
            transform: `scale(${scale})`,
            transformOrigin: 'top center',
            transition: 'all 0.3s ease',
          }}
          boxShadow="0 10px 40px rgba(0,0,0,0.2)"
          borderRadius="8px"
          overflow="hidden"
          bg="white"
          position="relative"
        >
          <Frame
            ref={frameRef}
            initialContent={frameContent}
            style={{
              width: '100%',
              height: '100%',
              border: 'none',
              display: 'block',
            }}
            mountTarget="#frame-root"
          >
            {children}
          </Frame>
        </Box>
      </Box>
    </VStack>
  );
};

export default ViewportSimulator;
