import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useRoutes, Link, useParams, useNavigate } from 'react-router';
import { AnimatePresence, motion } from 'framer-motion';
import { Skill } from '../Skills';
import { CustomInfra, CustomVeggie, CustomStripe, CustomDocker } from './custom';

type ProjectType = 'professional' | 'personal';

const Experience = () => {
    const { t } = useTranslation();
    const [activeTab, setActiveTab] = useState<ProjectType>('professional');
    
    const professionalExperiences = [
        {
            period: '2024',
            title: 'experience.project1.title',
            company: 'experience.project1.company',
            description: 'experience.project1.description',
            tasks: ['experience.project1.task1', 'experience.project1.task2', 'experience.project1.task3'],
            skills: ['Docker', 'Docker Compose', 'PHP', 'Apache', 'MySQL', 'VSCode'],
            customContent: <CustomDocker t={t} />
        },
        {
            period: '2024',
            title: 'experience.project2.title',
            company: 'experience.project2.company',
            description: 'experience.project2.description',
            tasks: ['experience.project2.task1', 'experience.project2.task2'],
            skills: ['Stripe', 'PHP', 'MySQL', 'JavaScript', 'jQuery', 'Webhooks'],
            customContent: <CustomStripe t={t} />
        },
        {
            period: '2025',
            title: 'experience.project3.title',
            company: 'experience.project3.company',
            description: 'experience.project3.description',
            detailedDescription: 'experience.project3.detailedDescription',
            tasks: ['experience.project3.task1', 'experience.project3.task2'],
            skills: ['Stripe', 'Node.js', 'JavaScript', 'Webhooks', 'Make', 'Cloudflare'],
            customContent: <CustomVeggie t={t} />
        }
    ];

    const personalExperiences = [
        {
            period: '2025',
            title: 'experience.project4.title',
            company: 'experience.project4.company',
            description: 'experience.project4.description',
            tasks: ['experience.project4.task1', 'experience.project4.task2'],
            skills: ['Docker', 'Git', 'CI/CD', 'Ansible', 'Terraform'],
            customContent: <CustomInfra t={t} />
        }
    ];

    const currentExperiences = activeTab === 'professional' ? professionalExperiences : personalExperiences;

    const routes = useRoutes(['/', '/experiences/:xpId'].map((path) => ({
        path,
        element: (
            <>
                <div className="max-w-4xl mx-auto px-8">
                    <h2 className="text-4xl font-bold mb-8 text-accent" id="experience">{t('experience.title')}</h2>
                    
                    {/* Tabs */}
                    <div className="flex gap-4 mb-8 border-b border-secondary/20">
                        <button
                            onClick={() => setActiveTab('professional')}
                            className={`relative px-6 py-3 font-medium transition-colors ${
                                activeTab === 'professional'
                                    ? 'text-accent'
                                    : 'text-secondary/60 hover:text-secondary'
                            }`}
                        >
                            {t('experience.tabs.professional')}
                            {activeTab === 'professional' && (
                                <motion.div
                                    layoutId="activeTab"
                                    className="absolute bottom-0 left-0 right-0 h-0.5 bg-accent"
                                    transition={{ type: "spring", stiffness: 380, damping: 30 }}
                                />
                            )}
                        </button>
                        <button
                            onClick={() => setActiveTab('personal')}
                            className={`relative px-6 py-3 font-medium transition-colors ${
                                activeTab === 'personal'
                                    ? 'text-accent'
                                    : 'text-secondary/60 hover:text-secondary'
                            }`}
                        >
                            {t('experience.tabs.personal')}
                            {activeTab === 'personal' && (
                                <motion.div
                                    layoutId="activeTab"
                                    className="absolute bottom-0 left-0 right-0 h-0.5 bg-accent"
                                    transition={{ type: "spring", stiffness: 380, damping: 30 }}
                                />
                            )}
                        </button>
                    </div>

                    <AnimatePresence mode="wait">
                        <motion.div
                            key={activeTab}
                            initial={{ opacity: 0, y: 20 }}
                            animate={{ opacity: 1, y: 0 }}
                            exit={{ opacity: 0, y: -20 }}
                            transition={{ duration: 0.3 }}
                            className="space-y-8"
                        >
                            <ExperiencesList experiences={currentExperiences} t={t} />
                        </motion.div>
                    </AnimatePresence>
                </div>
            </>
        )
    })));

    return (
        <>
            {routes}
        </>
    );
};

interface Experience {
    period: string;
    title: string;
    company: string;
    description: string;
    tasks: string[];
    detailedDescription?: string;
    skills?: string[];
    customContent?: React.ReactNode;
}

interface ExperiencesListProps {
    experiences: Experience[];
    t: (key: string) => string
}

const ExperiencesList = ({ experiences, t }: ExperiencesListProps) => {
    const { xpId } = useParams() as { xpId?: number };
    return <div className=' flex  flex-col space-y-8'>
        {experiences.map((exp, index) => <ExperienceSummary key={index} index={index} exp={exp} t={t} />)}
        <AnimatePresence mode="wait">
            {xpId !== undefined && <DetailedExperience t={t} exp={experiences[xpId]} />}
        </AnimatePresence>
    </div>
}

interface ExperienceSummaryProps {
    index: number;
    exp: Experience;
    t: (key: string) => string;
}

const ExperienceSummary = ({ index, exp, t }: ExperienceSummaryProps) => {

    return <Link to={`/experiences/${index}`}>
        <motion.div 
            layoutId={`experience-${index}`} 
            key={index} 
            className="bg-primary p-6 rounded-lg border border-secondary/10 hover:border-accent/50 transition-colors cursor-pointer relative group"
            transition={{ type: "spring", stiffness: 350, damping: 35 }}
        >
            <div className="flex flex-col md:flex-row md:justify-between md:items-start mb-4">
                <motion.div 
                    layoutId={`experience-header-${index}`}
                    transition={{ type: "spring", stiffness: 350, damping: 35 }}
                    className="flex-1"
                >
                    <h3 className="text-2xl font-semibold text-secondary mb-1">{t(exp.title)}</h3>
                    <p className="text-accent font-medium">{t(exp.company)}</p>
                </motion.div>
                <div className="flex items-center gap-3 mt-2 md:mt-0">
                    <motion.span 
                        layoutId={`experience-period-${index}`}
                        className="text-secondary/60 text-sm md:text-base"
                        transition={{ type: "spring", stiffness: 350, damping: 35 }}
                    >
                        {exp.period}
                    </motion.span>
                    <motion.svg 
                        xmlns="http://www.w3.org/2000/svg" 
                        className="h-5 w-5 text-accent opacity-60 group-hover:opacity-100 transition-opacity" 
                        fill="none" 
                        viewBox="0 0 24 24" 
                        stroke="currentColor"
                        whileHover={{ scale: 1.2 }}
                        layoutId={`experience-icon-${index}`}
                        transition={{ type: "spring", stiffness: 350, damping: 35 }}
                        whileTap={{ scale: 0.9 }}
                    >
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4" />
                    </motion.svg>
                </div>
            </div>
            <motion.p 
                initial={{ opacity: 1 }}
                className="text-secondary/70 mb-4"
            >
                {t(exp.description)}
            </motion.p>
            <motion.ul 
                initial={{ opacity: 1 }}
                className="list-disc list-inside space-y-2 text-secondary/60"
            >
                {exp.tasks.map((task, taskIndex) => (
                    <li key={taskIndex}>{t(task)}</li>
                ))}
            </motion.ul>
        </motion.div>
    </Link>
};

interface DetailedExperienceProps {
    t: (key: string) => string;
    exp: Experience;
}

const DetailedExperience = ({ t, exp }: DetailedExperienceProps) => {
    const { xpId } = useParams();
    const navigate = useNavigate();
    useEffect(() => {
        // Prevent background scrolling when detailed view is open
        document.body.style.overflow = 'hidden';

        const handleEscape = (e: KeyboardEvent) => {
            if (e.key === 'Escape') {
                navigate('/');
            }
        };

        document.addEventListener('keydown', handleEscape);

        return () => {
            document.body.style.overflow = 'auto';
            document.removeEventListener('keydown', handleEscape);
        };
    }, []);

    const handleBackgroundClick = (e: React.MouseEvent) => {
        if(e.target === e.currentTarget) {
            navigate('/');
        }
    }
    return <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        transition={{ duration: 0.3, ease: "easeInOut" }}
        className='fixed top-0 left-0 w-full h-full bg-black bg-opacity-80 flex flex-col items-center justify-center z-0 backdrop-blur-sm'
        onClick={handleBackgroundClick}
        
    >
        <motion.div 
            layoutId={`experience-${xpId}`} 
            className="bg-primary p-8 rounded-lg border border-accent/50 w-4/5 h-4/5 lg:h-3/4 lg:w-6/10 overflow-y-auto relative" 
            transition={{ type: "spring", stiffness: 350, damping: 35 }}
        >
            <div className="flex flex-row md:justify-between md:items-start mb-6">
                <motion.div 
                    layoutId={`experience-header-${xpId}`}
                    transition={{ type: "spring", stiffness: 350, damping: 35 }}
                    className="flex-1"
                >
                    <h3 className="text-xl md:text-2xl font-semibold text-secondary mb-1">{t(exp.title)}</h3>
                    <p className="text-accent font-medium">{t(exp.company)}</p>
                </motion.div>
                
                <div className="flex items-start gap-3 mt-2 md:mt-0">
                    <motion.button
                        onClick={() => navigate('/')}
                        className="p-2 rounded-full hover:bg-accent/10 transition-colors group"
                        layoutId={`experience-icon-${xpId}`}
                        transition={{ type: "spring", stiffness: 350, damping: 35 }}
                        whileHover={{ scale: 1.1 }}
                        whileTap={{ scale: 0.9 }}
                    >
                        <svg 
                            xmlns="http://www.w3.org/2000/svg" 
                            className="h-6 w-6 text-accent group-hover:text-accent/80" 
                            fill="none" 
                            viewBox="0 0 24 24" 
                            stroke="currentColor"
                        >
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </motion.button>
                </div>
            </div>
            
            <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                transition={{ duration: 0.15 }}
            >
                {/* <h4 className="text-xl font-semibold text-secondary mb-4">{t('experience.additional_details')}</h4> */}
                {/* <p className="text-secondary/70">{t(exp.detailedDescription!)}</p> */}
                {exp.customContent}
                {exp.skills && exp.skills.length > 0 && (
                    <div className="mb-4 mt-4">
                        <h5 className="text-lg font-semibold text-secondary mb-2">{t('experience.skills_used')}</h5>
                        <div className='flex gap-2 flex-wrap'>
                            {exp.skills.map((skill, skillIndex) => (
                                <Skill key={skillIndex} name={skill} />
                            ))}
                        </div>
                    </div>
                )}
            </motion.div>
        </motion.div>
    </motion.div>;
};

export default Experience;
