'use client';
import {AnimatePresence, motion} from 'framer-motion';
import {gsap} from 'gsap';
import {DrawSVGPlugin} from 'gsap/DrawSVGPlugin';
import {usePathname} from 'next/navigation';
import React, {useEffect, useRef, useState} from 'react';
import styled from 'styled-components';
import theme from "@/styles/theme";
import dcTheme from "@/styles/dc-theme";

// Register GSAP plugin
gsap.registerPlugin(DrawSVGPlugin);

const PreloaderWrapper = styled(motion.div)`
    position: ${dcTheme.position.type.fixed};
    top: ${dcTheme.numericScale.values[0]};
    left: ${dcTheme.numericScale.values[0]};
    right: ${dcTheme.numericScale.values[0]};
    bottom: ${dcTheme.numericScale.values[0]};

    z-index: ${dcTheme.zIndex.topMost};
    background: ${dcTheme.colors.theme.preloaderBackground};
    ${dcTheme.layouts.flexCenter}
    height: ${dcTheme.numericScale.height.screen};
    overflow: ${dcTheme.overflow.hidden};
    flex-direction: ${dcTheme.flex.col};
    pointer-events: ${dcTheme.numericScale.cursor.none};
    backface-visibility: ${dcTheme.overflow.hidden};
    will-change: ${dcTheme.numericScale.willChange.transform}, ${dcTheme.numericScale.willChange.opacity};


    .text-container {
        ${dcTheme.components.preloader.textContainer}
    }

    .logo-container {
        ${dcTheme.layouts.flexCenter}
        svg {
            height: ${dcTheme.numericScale.height.auto};
            path {
                stroke: #2F4F3E;
                stroke-width: ${dcTheme.numericScale.stroke['0.5']};
                fill: ${dcTheme.fills.transparent};
                stroke-dasharray: ${dcTheme.numericScale.stroke.dashArrayFull};
                stroke-dashoffset: ${dcTheme.numericScale.stroke.dashOffsetFull};
            }
        }
    }

    .main-text {
        ${dcTheme.components.preloader.title}
        .word {
            display: ${dcTheme.display.inlineBlock};
            margin-right: ${dcTheme.numericScale.margin.custom('clamp(0.1em, 2vw, 0.3em)')};
            overflow: ${dcTheme.overflow.hidden};
            .char {
                display: ${dcTheme.display.inlineBlock};
                transform: ${dcTheme.transforms.translateY('100%')};
                transition: ${dcTheme.numericScale.transitions.mainTransition};
                will-change: ${dcTheme.numericScale.willChange.transform};
            }
        }
    }

    .sub-text {
        font-family: ${theme.fonts.inherit};
        font-size: clamp(0.8rem, 2.5vw, 1.1rem);
        font-weight: ${theme.fontWeights.light};
        color: ${theme.colors.metallicBronze};
        letter-spacing: clamp(0.05em, 1vw, 0.1em);
        text-transform: ${theme.textTransform.uppercase};
        text-align: ${theme.textAlign.center};
        overflow: ${theme.overflow.hidden};
        max-width: 90vw;
        line-height: 1.3;

        .char {
            display: ${theme.display.inlineBlock};
            transform: translateY(100%);
            transition: ${theme.mainTransition};
            will-change: ${theme.willChange.transform};
        }
    }

    .progress-container {
        display: ${theme.display.flex};
        align-items: ${theme.textAlign.center};
        max-width: 90vw;
        font-size: clamp(0.75rem, 1.5vw, 1rem);
        color: ${theme.colors.metallicBronze};
        letter-spacing: 0.05em;
        margin-top: 1rem;

        .progress-line {
            width: 120px;
            height: 2px;
            background: ${dcTheme.colors.theme.primary["0"]};
            position: ${dcTheme.position.type.relative};
            overflow: ${dcTheme.overflow.hidden};

            &::after {
                content: '';
                position: ${dcTheme.position.type.absolute};
                inset: ${dcTheme.position.offset["0"]};
                background: ${dcTheme.colors.theme.primary["0"]};
                transition: ${dcTheme.numericScale.transitions.mainTransition};
            }
        }
    }

    @media (max-width: 768px) {
        .main-text {
            font-size: ${dcTheme.typography.sizes.custom('clamp(2rem, 12vw, 4rem)')};
        }

        .progress-container {
            bottom: ${dcTheme.position.offset.custom('2rem')};
        }
    }
`;


const BackgroundPattern = styled.div`
    position: ${dcTheme.position.type.absolute};
    top: ${dcTheme.position.offset["0"]};
    left: ${dcTheme.position.offset["0"]};
    right: ${dcTheme.position.offset["0"]};
    bottom: ${dcTheme.position.offset["0"]};
    z-index: ${dcTheme.numericScale.zIndex["10"]};
    background-image: ${dcTheme.colors.theme.preloadBackgroundPattern};
    animation: ${dcTheme.animations.keyframes.rotate360} ${dcTheme.numericScale.duration.preloaderDurationMain} ${dcTheme.numericScale.transitions.default} infinite;`;

const AnimatedText = ({text, className, delay = 0}) => {
    const words = text.split(' ');

    return (
        <div className={className}>
            {words.map((word, wordIndex) => (
                <span key={wordIndex} className="word">
          {word.split('').map((char, charIndex) => (
              <span
                  key={charIndex}
                  className="char"
                  style={{
                      transitionDelay:
                          `${delay + (wordIndex * 50) + (charIndex * 30)}ms`

                  }}
              >
              {char}
            </span>
          ))}
                    {wordIndex < words.length - 1 && (
                        <span
                            className="char"
                            style={{
                                transitionDelay:
                                    `${delay + (wordIndex * 50) + (word.length * 30)}ms`

                            }}
                        >
              &nbsp;
            </span>
                    )}
        </span>
            ))}
        </div>
    );
};

const Preloader = ({onComplete}) => {
    const [isVisible, setIsVisible] = useState(true);
    const [progress, setProgress] = useState(0);
    const [textAnimated, setTextAnimated] = useState(false);
    const [svgAnimated, setSvgAnimated] = useState(false);
    const pathname = usePathname();
    const intervalRef = useRef(null);
    const timeoutRef = useRef(null);
    const progressLineRef = useRef(null);
    const svgRef = useRef(null);

    // Preloader variants with bottom-to-top masking exit
    const preloaderVariants = {
        initial: {
            clipPath: dcTheme.numericScale.clipPath.preloaderInitial,
        },
        exit: {
            clipPath: dcTheme.numericScale.clipPath.preloaderExit,
            transition: {
                duration: 0.8,
                ease: dcTheme.numericScale.transitions.defaultEase,
            },
        },
    };

    // Content exit variants - elements move up slightly as they disappear
    const contentExitVariants = {
        initial: {
            opacity: 1,
            y: 0,
        },
        exit: {
            opacity: 0,
            y: -40,
            transition: {
                duration: 0.8,
                ease: dcTheme.numericScale.transitions.defaultEase,
            },
        },
    };

    // SVG Draw Animation
    useEffect(() => {
        if (!svgRef.current) return;

        const svg = svgRef.current;
        const paths = svg.querySelectorAll('path');

        // Create timeline for SVG animation
        const tl = gsap.timeline({
            onComplete: () => {
                setSvgAnimated(true);
                // Start text animation after SVG completes
                setTextAnimated(true);
                const chars = document.querySelectorAll('.char');
                chars.forEach((char) => {
                    char.style.transform = `translateY(0)`;
                });
            }
        });

        // Set initial state
        gsap.set(paths, {
            drawSVG: 0,
            fill: dcTheme.fills.transparent
        });

        // Animate drawing
        tl.to(paths, {
            drawSVG: "100%",
            duration: 2,
            stagger: 0.3,
            ease: dcTheme.numericScale.transitions.defaultEase
        })
            // Fill the paths after drawing
            .to(paths, {
                fill: '#2F4F3E',
                duration: 0.5,
                stagger: 0.1,
                ease: dcTheme.numericScale.transitions.defaultEase
            }, "-=0.5")
            // Scale up slightly for emphasis
            .to(svg, {
                scale: 1.1,
                duration: 0.5,
                ease: dcTheme.numericScale.transitions.defaultEase
            })
            // Scale back to normal
            .to(svg, {
                scale: 1,
                duration: 0.3,
                ease: dcTheme.numericScale.transitions.defaultEase
            });

        return () => {
            tl.kill();
        };
    }, []);

    // Update progress line
    useEffect(() => {
        if (progressLineRef.current) {
            progressLineRef.current.style.width =
                `${progress}%`
            ;
        }
    }, [progress]);

    useEffect(() => {
        // Wait for SVG animation to start before beginning progress
        if (!svgAnimated) return;

        if (intervalRef.current || timeoutRef.current) {
            return;
        }

        const startTime = Date.now();
        const duration = 3000; // Reduced since SVG takes initial time

        intervalRef.current = setInterval(() => {
            const elapsed = Date.now() - startTime;
            const progressPercent = Math.min((elapsed / duration) * 100, 100);

            let easedProgress;
            if (progressPercent < 30) {
                easedProgress = progressPercent * 0.3;
            } else if (progressPercent < 70) {
                easedProgress = 9 + (progressPercent - 30) * 1.5;
            } else {
                easedProgress = 69 + (progressPercent - 70);
            }

            setProgress(Math.floor(Math.min(easedProgress, 100)));

            if (progressPercent >= 100) {
                clearInterval(intervalRef.current);
                intervalRef.current = null;

                timeoutRef.current = setTimeout(() => {
                    setIsVisible(false);

                    // Call onComplete after the exit animation finishes
                    setTimeout(() => {
                        if (onComplete) {
                            onComplete();
                        }
                    }, 1200); // Match the exit animation duration
                }, 500); // Small delay before starting exit animation
            }
        }, 16);

        return () => {
            if (intervalRef.current) {
                clearInterval(intervalRef.current);
                intervalRef.current = null;
            }
            if (timeoutRef.current) {
                clearTimeout(timeoutRef.current);
                timeoutRef.current = null;
            }
        };
    }, [svgAnimated, onComplete]);

    return (
        <AnimatePresence mode="wait">
            {isVisible && (
                <PreloaderWrapper
                    key="preloader"
                    variants={preloaderVariants}
                    initial="initial"
                    animate="initial"
                    exit="exit"
                >
                    <BackgroundPattern/>
                    <motion.div
                        className="text-container"
                        variants={contentExitVariants}
                        initial="initial"
                        exit="exit"
                    >
                        <div className="logo-container">
                            <svg
                                ref={svgRef}
                                id="Component_15"
                                data-name="Component 15"
                                xmlns="http://www.w3.org/2000/svg"
                                width="80"
                                height="110"
                                viewBox="0 0 40 55.001"
                            >
                                <path
                                    id="Union_1"
                                    data-name="Union 1"
                                    d="M0,54.732V22.853H6.576V49.315H17.587V44.591h5.875V54.732ZM0,22.853V0H40V22.853Zm6.576-6.574H33V5.806H6.576Z"
                                />
                                <path
                                    id="Path_1511"
                                    data-name="Path 1511"
                                    d="M3370,1398.793V1390h22.412v23.5h-5.58v-18.726h-10.957v4.018Z"
                                    transform="translate(-3352.413 -1358.5)"
                                />
                            </svg>
                        </div>

                        <AnimatedText
                            text="Palmal Group of Industries Ltd"
                            className="sub-text"
                            delay={100}
                        />
                    </motion.div>

                    <motion.div
                        className="progress-container"
                        variants={contentExitVariants}
                        initial="initial"
                        exit="exit"
                    >
                        <div className="progress-line">
                            <div
                                ref={progressLineRef}
                                style={{
                                    position: dcTheme.position.type.absolute,
                                    top: dcTheme.position.offset["0"],
                                    left: dcTheme.position.offset["0"],
                                    width: dcTheme.position.offset["0"],
                                    height: dcTheme.numericScale.height.auto,
                                    background: dcTheme.colors.primaryColor,
                                    transition: dcTheme.numericScale.transitions.mainTransition,
                                }}
                            />
                        </div>
                    </motion.div>
                </PreloaderWrapper>
            )}
        </AnimatePresence>
    );
};

export default React.memo(Preloader);