import React, { useState, useEffect, useRef, useMemo } from 'react'
import Editor from 'react-simple-code-editor'
import Prism from 'prismjs'
import 'prismjs/components/prism-ini'
import 'prismjs/themes/prism-tomorrow.css'
import { IconButton, Box, Typography, Tooltip } from '@mui/material'
import { KeyboardArrowDown as DownIcon, KeyboardArrowUp as UpIcon } from '@mui/icons-material'

interface PhpIniCodeEditorProps {
    value: string
    onChange: (value: string) => void
    searchTerm?: string
}

const PhpIniCodeEditor: React.FC<PhpIniCodeEditorProps> = ({ value, onChange, searchTerm }) => {
    const editorRef = useRef<HTMLDivElement>(null)
    const [matches, setMatches] = useState<number[]>([])
    const [currentIndex, setCurrentIndex] = useState(0)

    const cleanSearchTerm = useMemo(() => searchTerm?.trim().toLowerCase() || '', [searchTerm])

    // Find all matches when searchTerm or value changes
    useEffect(() => {
        if (cleanSearchTerm.length > 1) {
            const indices: number[] = []
            let pos = value.toLowerCase().indexOf(cleanSearchTerm)
            while (pos !== -1) {
                indices.push(pos)
                pos = value.toLowerCase().indexOf(cleanSearchTerm, pos + 1)
            }
            setMatches(indices)
            setCurrentIndex(indices.length > 0 ? 0 : -1)
        } else {
            setMatches([])
            setCurrentIndex(-1)
        }
    }, [cleanSearchTerm, value])

    const scrollToMatch = (index: number) => {
        if (index >= 0 && index < matches.length && editorRef.current) {
            const startPos = matches[index]
            const linesBefore = value.substring(0, startPos).split('\n').length
            const lineHeight = 21
            const container = editorRef.current
            container.scrollTop = (linesBefore - 5) * lineHeight
        }
    }

    useEffect(() => {
        if (currentIndex !== -1) {
            scrollToMatch(currentIndex)
        }
    }, [currentIndex])

    const handleNext = () => {
        if (matches.length > 0) {
            setCurrentIndex(prev => (prev + 1) % matches.length)
        }
    }

    const handlePrev = () => {
        if (matches.length > 0) {
            setCurrentIndex(prev => (prev - 1 + matches.length) % matches.length)
        }
    }

    const highlightWithSearch = (code: string) => {
        let highlighted = Prism.highlight(code, Prism.languages.ini, 'ini')

        if (cleanSearchTerm.length > 1) {
            const escapedSearch = cleanSearchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
            const regex = new RegExp(`(${escapedSearch})(?![^<]*>)`, 'gi')
            let matchCounter = 0

            highlighted = highlighted.replace(regex, (match) => {
                const isCurrent = matchCounter === currentIndex
                matchCounter++
                return `<mark class="search-match ${isCurrent ? 'active-match' : ''}">${match}</mark>`
            })
        }

        return highlighted
    }

    // Keyboard support
    const handleKeyDown = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter' && cleanSearchTerm.length > 1) {
            e.preventDefault()
            if (e.shiftKey) handlePrev()
            else handleNext()
        }
    }

    const totalLines = useMemo(() => value.split('\n').length, [value])

    return (
        <Box sx={{ position: 'relative', display: 'flex', flexDirection: 'column', height: '450px', bgcolor: '#1a1a1a' }}>
            {/* Search Navigation Bar */}
            {cleanSearchTerm.length > 1 && (
                <Box sx={{
                    position: 'absolute',
                    top: 10,
                    right: 30, // Leave space for scrollbar/markers
                    zIndex: 10,
                    bgcolor: '#333',
                    borderRadius: '4px',
                    display: 'flex',
                    alignItems: 'center',
                    px: 1,
                    py: 0.5,
                    boxShadow: '0 4px 12px rgba(0,0,0,0.5)',
                    border: '1px solid rgba(255,255,255,0.1)'
                }}>
                    <Typography variant="caption" sx={{ color: '#aaa', mr: 1, minWidth: '40px', textAlign: 'center', userSelect: 'none' }}>
                        {matches.length > 0 ? `${currentIndex + 1} / ${matches.length}` : '0 / 0'}
                    </Typography>
                    <Tooltip title="Önceki (Shift+Enter)">
                        <IconButton size="small" onClick={handlePrev} sx={{ color: '#fff' }}>
                            <UpIcon fontSize="small" />
                        </IconButton>
                    </Tooltip>
                    <Tooltip title="Sonraki (Enter)">
                        <IconButton size="small" onClick={handleNext} sx={{ color: '#fff' }}>
                            <DownIcon fontSize="small" />
                        </IconButton>
                    </Tooltip>
                </Box>
            )}

            {/* Scrollbar Markers (Minimap style) */}
            <Box sx={{
                position: 'absolute',
                top: 0,
                right: 0,
                width: '12px',
                height: '100%',
                zIndex: 5,
                pointerEvents: 'none',
                bgcolor: 'rgba(255,255,255,0.02)'
            }}>
                {matches.map((pos, i) => {
                    const line = value.substring(0, pos).split('\n').length
                    const topPercent = (line / totalLines) * 100
                    return (
                        <Box
                            key={i}
                            sx={{
                                position: 'absolute',
                                top: `${topPercent}%`,
                                left: 2,
                                width: '8px',
                                height: '2px',
                                bgcolor: i === currentIndex ? '#ff9800' : '#ffcf00',
                                boxShadow: i === currentIndex ? '0 0 4px #ff9800' : 'none'
                            }}
                        />
                    )
                })}
            </Box>

            <div
                ref={editorRef}
                onKeyDown={handleKeyDown}
                style={{
                    flexGrow: 1,
                    overflow: 'auto',
                    fontFamily: '"Fira code", "Fira Mono", monospace',
                    fontSize: '14px',
                    scrollBehavior: 'smooth'
                }}
            >
                <Editor
                    key={cleanSearchTerm + currentIndex} // Key for re-highlighting active match
                    value={value}
                    onValueChange={code => onChange(code)}
                    highlight={highlightWithSearch}
                    padding={15}
                    style={{
                        fontFamily: '"Fira code", "Fira Mono", monospace',
                        fontSize: 14,
                        minHeight: '100%',
                        outline: 'none'
                    }}
                    textareaClassName="ini-editor-textarea"
                    preClassName="ini-editor-pre"
                />
            </div>
            <style>{`
                .ini-editor-textarea {
                    outline: none !important;
                    caret-color: #fff !important;
                }
                .ini-editor-pre {
                    pointer-events: none;
                }
                .token.comment { color: #6a9955; }
                .token.section { color: #569cd6; font-weight: bold; }
                .token.attr-name { color: #9cdcfe; }
                .token.attr-value { color: #ce9178; }
                .token.punctuation { color: #d4d4d4; }
                .token.important { color: #569cd6; }
                .search-match {
                    background: rgba(255, 207, 0, 0.3) !important;
                    color: inherit !important;
                    border-radius: 1px;
                }
                .active-match {
                    background: #ff9800 !important;
                    color: #000 !important;
                    box-shadow: 0 0 8px rgba(255, 152, 0, 0.8);
                    font-weight: bold;
                }
            `}</style>
        </Box>
    )
}

export default PhpIniCodeEditor
