'use client'
import { useEffect, useState } from 'react';
import Image from 'next/image';
import { Button } from '@/components/ui/button';
import { ChevronDown, GraduationCap, ArrowLeft, ArrowRight, FileText, Calendar as CalendarIcon } from 'lucide-react';
import { useLanguage } from '@/contexts/LanguageContext';
import { useRouter } from 'next/navigation';
import { motion, useScroll, useTransform } from 'framer-motion';
import heroCampus from '@/assets/hero-new.jpg';
import { resolveMediaUrl } from '@/services/shared/media-url';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";

type HeroCmsContent = {
  badgeAr?: string
  badgeEn?: string
  titlePrimaryAr?: string
  titlePrimaryEn?: string
  titleSecondaryAr?: string
  titleSecondaryEn?: string
  descriptionAr?: string
  descriptionEn?: string
  image?: string
  backgroundType?: string
  backgroundImage?: string
  backgroundVideo?: string
  backgroundOverlayOpacity?: string | number
}

export const HeroSection = ({ hero }: { hero?: HeroCmsContent }) => {
  const { t, language } = useLanguage();
  const router = useRouter();
  const { scrollY } = useScroll();
  const y = useTransform(scrollY, [0, 500], [0, 150]);
  const opacity = useTransform(scrollY, [0, 800], [1, 0]);
  const [isMounted, setIsMounted] = useState(false);

  const heroData: HeroCmsContent = {
    badgeAr: 'مرحباً بكم في جامعة الجيل الجديد',
    badgeEn: 'Welcome to AJ JEEL ALJADEED UNIVERSITY',
    titlePrimaryAr: 'جامعة الجيل الجديد',
    titlePrimaryEn: 'ALJEEL AL JADEED',
    titleSecondaryAr: 'الجامعة',
    titleSecondaryEn: 'UNIVERSITY',
    descriptionAr: 'مؤسسة تعليمية رائدة تهدف إلى إعداد خريجين متخصصين ومؤهلين علميًا وتقنيًا لخدمة المجتمع',
    descriptionEn: 'A leading educational institution aiming to prepare specialized and scientifically qualified graduates to serve the community',
    image: '',
    backgroundType: 'none',
    backgroundImage: '',
    backgroundVideo: '',
    backgroundOverlayOpacity: 0.45,
    ...(hero || {}),
  };

  const heroBackgroundType = String(heroData.backgroundType || 'none').toLowerCase();
  const heroBackgroundImage = resolveMediaUrl(heroData.backgroundImage);
  const heroBackgroundVideo = resolveMediaUrl(heroData.backgroundVideo);
  const heroOverlayOpacityRaw = Number(heroData.backgroundOverlayOpacity);
  const heroOverlayOpacity = Number.isFinite(heroOverlayOpacityRaw)
    ? Math.max(0, Math.min(1, heroOverlayOpacityRaw))
    : 0.45;
  const hasHeroBackgroundImage = heroBackgroundType === 'image' && Boolean(heroBackgroundImage);
  const hasHeroBackgroundVideo = heroBackgroundType === 'video' && Boolean(heroBackgroundVideo);

  useEffect(() => {
    setIsMounted(true);
  }, []);

  const scrollToAbout = () => {
    document.querySelector('#about')?.scrollIntoView({ behavior: 'smooth' });
  };

  return (
    <section id="hero" className="relative h-screen min-h-[700px] flex items-center justify-center overflow-hidden">
      {/* Background Container */}
      <div className="absolute inset-0 w-full h-full bg-black">
        {(hasHeroBackgroundImage || hasHeroBackgroundVideo) && (
          <div className="absolute inset-0">
            {hasHeroBackgroundImage && (
              <img src={heroBackgroundImage} alt="" className="h-full w-full object-cover" loading="eager" />
            )}
            {hasHeroBackgroundVideo && (
              <video
                className="h-full w-full object-cover"
                src={heroBackgroundVideo}
                autoPlay
                muted
                loop
                playsInline
                preload="metadata"
              />
            )}
            <div className="absolute inset-0 bg-black" style={{ opacity: heroOverlayOpacity }} />
          </div>
        )}

        <motion.div
          className="relative w-full h-full overflow-hidden"
          style={{ y }}
        >
          <Image
            src={heroData.image || heroCampus}
            alt={t('الحرم الجامعي', 'University Campus')}
            fill
            priority
            quality={100}
            className="object-cover"
            sizes="100vw"
          />
          <div className="absolute inset-0 bg-black/30"></div>
        </motion.div>
      </div>

      {/* Particles */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        {isMounted && [...Array(15)].map((_, i) => (
          <motion.div
            key={i}
            className="absolute w-1 h-1 bg-secondary/30 rounded-full"
            initial={{
              x: `${Math.random() * 100}%`,
              y: `${Math.random() * 100}%`,
              opacity: Math.random() * 0.4 + 0.1,
            }}
            animate={{
              y: [`${Math.random() * 100}%`, `${Math.random() * 100}%`],
              opacity: [0.1, 0.4, 0.1],
            }}
            transition={{ duration: Math.random() * 10 + 15, repeat: Infinity, ease: "linear" }}
          />
        ))}
      </div>

      {/* Main Content - Centered with Top Weight */}
      <div className="absolute inset-0 z-20 flex flex-col items-center justify-start pt-16 sm:pt-20 md:pt-24">
        <motion.div
          className="container mx-auto px-4 text-center text-white"
          style={{ opacity }}
        >
          <div className="max-w-4xl mx-auto space-y-4 md:space-y-6">
            <div className="inline-flex items-center gap-2 bg-white/10 backdrop-blur-md px-3 py-1 sm:px-4 sm:py-1.5 rounded-full text-[10px] sm:text-xs font-medium border border-white/20">
              <GraduationCap className="w-3.5 h-3.5 sm:w-4 sm:h-4 text-secondary" />
              {t(heroData.badgeAr || '', heroData.badgeEn || '')}
            </div>

            <h1 className="text-3xl sm:text-5xl md:text-6xl lg:text-7xl font-display font-bold leading-tight tracking-tight">
              <span className="bg-gradient-to-r from-white via-secondary to-white bg-clip-text text-transparent drop-shadow-2xl">
                {t(heroData.titlePrimaryAr || '', heroData.titlePrimaryEn || '')}
              </span>
              <span className="block text-xl sm:text-3xl md:text-4xl text-secondary drop-shadow-lg mt-1 sm:mt-2 font-medium">
                {t(heroData.titleSecondaryAr || '', heroData.titleSecondaryEn || '')}
              </span>
            </h1>

            <div className="flex justify-center">
              <div className="bg-secondary/10 px-4 py-1 sm:px-6 sm:py-1.5 rounded-full border border-secondary/30 backdrop-blur-sm">
                <span className="text-secondary font-display text-sm sm:text-lg md:text-xl font-bold tracking-[0.1em] sm:tracking-[0.2em] uppercase">
                  {t('لأجيال واعدة', 'FOR PROMISING GENERATIONS')}
                </span>
              </div>
            </div>

            <p className="text-sm sm:text-base md:text-xl text-white/80 max-w-2xl mx-auto leading-relaxed px-4">
              {t(heroData.descriptionAr || '', heroData.descriptionEn || '')}
            </p>

            <div className="flex justify-center pt-2 sm:pt-4">
              <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                <Button
                  size="lg"
                  onClick={() => router.push('/admission')}
                  className="bg-secondary text-primary hover:bg-secondary/90 text-sm sm:text-base md:text-lg px-8 sm:px-10 py-5 sm:py-7 md:py-8 rounded-xl sm:rounded-2xl shadow-xl shadow-secondary/20 group font-bold"
                >
                  {t('التقديم الآن', 'Apply Now')}
                  {language === 'ar' ? (
                    <ArrowLeft className="w-5 h-5 mr-3 transition-transform group-hover:-translate-x-1" />
                  ) : (
                    <ArrowRight className="w-5 h-5 ml-3 transition-transform group-hover:translate-x-1" />
                  )}
                </Button>
              </motion.div>
            </div>
          </div>
        </motion.div>
      </div>

      {/* Bottom Cards - Responsive Layout */}
      <div className="absolute inset-x-0 bottom-6 sm:bottom-10 z-20">
        <div className="container mx-auto px-3 sm:px-4">
          <div className="flex flex-row overflow-x-auto sm:overflow-visible gap-2 sm:gap-4 max-w-5xl mx-auto justify-start sm:justify-center items-stretch snap-x snap-mandatory pb-2 no-scrollbar sm:pb-0">
            {/* Colleges Card */}
            <motion.button
              onClick={() => router.push('/colleges')}
              className="flex-shrink-0 w-[140px] xs:w-[170px] sm:flex-1 sm:max-w-[220px] group relative p-2 sm:p-4 bg-white/[0.03] backdrop-blur-md border border-white/10 rounded-xl sm:rounded-2xl flex flex-col items-center gap-2 sm:gap-3 hover:bg-secondary/10 hover:border-secondary/30 transition-all duration-500 shadow-2xl snap-center"
              whileHover={{ y: -4 }}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.2 }}
            >
              <div className="w-8 h-8 sm:w-10 sm:h-10 rounded-lg sm:rounded-xl bg-secondary/10 flex items-center justify-center text-secondary group-hover:bg-secondary group-hover:text-primary transition-all duration-500">
                <GraduationCap className="w-3.5 h-3.5 sm:w-5 sm:h-5" />
              </div>
              <div className="text-center">
                <span className="block font-bold text-[10px] sm:text-sm group-hover:text-secondary transition-colors">{t('استكشف الكليات', 'Explore Colleges')}</span>
                <span className="hidden sm:block text-[9px] text-white/30 group-hover:text-secondary/60 transition-colors">{t('تخصصاتنا المتميزة', 'Our programs')}</span>
              </div>
            </motion.button>

            {/* Student Results Card */}
            <motion.button
              onClick={() => window.open('https://result.yemenexam.com/', '_blank')}
              className="flex-shrink-0 w-[140px] xs:w-[170px] sm:flex-1 sm:max-w-[220px] group relative p-2 sm:p-4 bg-white/[0.03] backdrop-blur-md border border-white/10 rounded-xl sm:rounded-2xl flex flex-col items-center gap-2 sm:gap-3 hover:bg-white/10 hover:border-white/20 transition-all duration-500 shadow-2xl snap-center"
              whileHover={{ y: -4 }}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.3 }}
            >
              <div className="w-8 h-8 sm:w-10 sm:h-10 rounded-lg sm:rounded-xl bg-white/5 flex items-center justify-center text-white group-hover:bg-white group-hover:text-primary transition-all duration-500">
                <FileText className="w-3.5 h-3.5 sm:w-5 sm:h-5" />
              </div>
              <div className="text-center">
                <span className="block font-bold text-[10px] sm:text-sm">{t('نتائج الطلاب', 'Student Results')}</span>
                <span className="hidden sm:block text-[9px] text-white/30 line-clamp-1">{t('بوابة النتائج', 'Results portal')}</span>
              </div>
            </motion.button>

            {/* Academic Calendar Card */}
            <Dialog>
              <DialogTrigger asChild>
                <motion.button
                  className="flex-shrink-0 w-[140px] xs:w-[170px] sm:flex-1 sm:max-w-[220px] group relative p-2 sm:p-4 bg-white/[0.03] backdrop-blur-md border border-white/10 rounded-xl sm:rounded-2xl flex flex-col items-center gap-2 sm:gap-3 hover:bg-white/10 hover:border-white/20 transition-all duration-500 shadow-2xl snap-center"
                  whileHover={{ y: -4 }}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.4 }}
                >
                  <div className="w-8 h-8 sm:w-10 sm:h-10 rounded-lg sm:rounded-xl bg-white/5 flex items-center justify-center text-white group-hover:bg-white group-hover:text-primary transition-all duration-500">
                    <CalendarIcon className="w-3.5 h-3.5 sm:w-5 sm:h-5" />
                  </div>
                  <div className="text-center">
                    <span className="block font-bold text-[10px] sm:text-sm">{t('التقويم الجامعي', 'Academic Calendar')}</span>
                    <span className="hidden sm:block text-[9px] text-white/30 line-clamp-1">{t('مواعيد الدراسة', 'Schedule')}</span>
                  </div>
                </motion.button>
              </DialogTrigger>
              <DialogContent className="max-w-4xl w-[95vw] h-[80vh] flex flex-col p-0 overflow-hidden bg-background/95 backdrop-blur-lg border-secondary/20">
                <DialogHeader className="p-6 border-b border-border/50 flex flex-row items-center justify-between">
                  <DialogTitle className="text-2xl font-display font-bold flex items-center gap-3">
                    <CalendarIcon className="w-6 h-6 text-secondary" />
                    {t('التقويم الجامعي للعام 2024-2025', 'Academic Calendar 2024-2025')}
                  </DialogTitle>
                </DialogHeader>
                <div className="flex-1 relative bg-muted/30 overflow-auto p-4 flex items-start justify-center">
                  <div className="relative w-full max-w-3xl aspect-[1/1.4] bg-white shadow-2xl rounded-lg overflow-hidden border border-border/50 text-center flex items-center justify-center">
                    <div className="p-10">
                      <CalendarIcon className="w-16 h-16 text-muted-foreground/30 mx-auto mb-4" />
                      <p className="text-muted-foreground font-medium">
                        {t('سيتم رفع التقويم الرسمي فور صدوره من الوزارة', 'The official calendar will be uploaded as soon as it is issued by the Ministry')}
                      </p>
                    </div>
                  </div>
                </div>
              </DialogContent>
            </Dialog>
          </div>
        </div>
      </div>

    </section>
  );
};
