'use client';

import React, { useEffect } from 'react';
import { createPortal } from 'react-dom';
import { X, ZoomIn, ZoomOut, RotateCcw } from 'lucide-react';
import { TransformWrapper, TransformComponent, useControls } from 'react-zoom-pan-pinch';

import { Button } from '@djangocfg/ui-core/components';
import { applyMermaidTextColors } from '../utils/mermaid-helpers';

interface MermaidFullscreenModalProps {
    isOpen: boolean;
    svgContent: string;
    isVertical: boolean;
    theme: string;
    chart: string;
    fullscreenRef: React.RefObject<HTMLDivElement | null>;
    onClose: () => void;
    onBackdropClick: (e: React.MouseEvent) => void;
}

// Zoom controls component
function ZoomControls() {
    const { zoomIn, zoomOut, resetTransform } = useControls();

    return (
        <div className="absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2 z-10">
            <Button variant="secondary" size="icon" onClick={() => zoomOut()}>
                <ZoomOut className="h-4 w-4" />
            </Button>
            <Button variant="secondary" size="icon" onClick={() => resetTransform()}>
                <RotateCcw className="h-4 w-4" />
            </Button>
            <Button variant="secondary" size="icon" onClick={() => zoomIn()}>
                <ZoomIn className="h-4 w-4" />
            </Button>
        </div>
    );
}

export const MermaidFullscreenModal: React.FC<MermaidFullscreenModalProps> = ({
    isOpen,
    svgContent,
    isVertical,
    theme,
    fullscreenRef,
    onClose,
    onBackdropClick,
}) => {
    // Apply text colors
    useEffect(() => {
        if (isOpen && fullscreenRef.current) {
            const getCSSVariable = (variable: string) => {
                if (typeof document === 'undefined') return '';
                const value = getComputedStyle(document.documentElement).getPropertyValue(variable).trim();
                return value ? `hsl(${value})` : '';
            };

            const textColor = theme === 'dark'
                ? getCSSVariable('--foreground') || 'hsl(0 0% 90%)'
                : getCSSVariable('--foreground') || 'hsl(222.2 84% 4.9%)';

            applyMermaidTextColors(fullscreenRef.current, textColor);
        }
    }, [isOpen, theme, isVertical, fullscreenRef, svgContent]);

    // Handle escape key
    useEffect(() => {
        if (!isOpen) return;

        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.key === 'Escape') onClose();
        };

        document.addEventListener('keydown', handleKeyDown);
        return () => document.removeEventListener('keydown', handleKeyDown);
    }, [isOpen, onClose]);

    if (!isOpen || typeof document === 'undefined') return null;

    return createPortal(
        <div
            className="fixed inset-0 z-9999 bg-background/95 backdrop-blur-sm"
            onClick={onBackdropClick}
        >
            {/* Close button */}
            <Button
                variant="ghost"
                size="icon"
                className="absolute top-4 right-4 z-10"
                onClick={onClose}
            >
                <X className="h-5 w-5" />
            </Button>

            {/* Zoomable diagram */}
            <TransformWrapper
                initialScale={1}
                minScale={0.1}
                maxScale={10}
                centerOnInit
                wheel={{ step: 0.1 }}
                pinch={{ step: 5 }}
                doubleClick={{ mode: 'reset' }}
            >
                <ZoomControls />
                <TransformComponent
                    wrapperStyle={{
                        width: '100%',
                        height: '100%',
                    }}
                    contentStyle={{
                        width: '100%',
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                    }}
                >
                    <div
                        ref={fullscreenRef}
                        className="p-8"
                        dangerouslySetInnerHTML={{ __html: svgContent }}
                        onClick={(e) => e.stopPropagation()}
                    />
                </TransformComponent>
            </TransformWrapper>
        </div>,
        document.body
    );
};
