'use client';

import { useState, useEffect, use } from 'react';
import Link from 'next/link';
import { useTranslations } from 'next-intl';
import { ResourceCard } from '@/components/ResourceCard';
import { getLessons } from '@/lib/actions/lessonActions';
import { getCheatsheets } from '@/lib/actions/cheatsheetActions';
import { getCategories } from '@/lib/actions/categoryActions';
import {
  Search,
  Sparkles,
  Code2,
  FileCheck2,
  Layers,
  Download,
  Users,
  CheckCircle2,
  ArrowRight,
  ShieldAlert,
  Zap,
  Loader2
} from 'lucide-react';
import { YoutubeIcon as Youtube } from '@/components/icons/YoutubeIcon';

export default function HomePage({ params }: { params: Promise<{ locale: string }> }) {
  const { locale } = use(params);
  const t = useTranslations('hero');
  const sec = useTranslations('sections');
  const feat = useTranslations('features');

  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);

  const [categories, setCategories] = useState<any[]>([]);
  const [lessons, setLessons] = useState<any[]>([]);
  const [cheatsheets, setCheatsheets] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    getCategories().then(setCategories);
  }, []);

  useEffect(() => {
    async function loadData() {
      setLoading(true);
      const [fetchedLessons, fetchedCheatsheets] = await Promise.all([
        getLessons({ query: searchQuery, category: selectedCategory || undefined }),
        getCheatsheets()
      ]);
      setLessons(fetchedLessons);
      setCheatsheets(fetchedCheatsheets);
      setLoading(false);
    }
    loadData();
  }, [searchQuery, selectedCategory]);

  const featuredVideo = lessons.find((v) => v.isFeatured) || lessons[0];

  return (
    <div className="flex-1 flex flex-col space-y-16 pb-20">
      
      {/* HERO SECTION */}
      <section className="relative overflow-hidden pt-12 pb-16 bg-gradient-to-b from-slate-900/80 via-slate-950 to-slate-950 border-b border-slate-800/80">
        
        {/* Glow Effects */}
        <div className="absolute top-1/4 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[300px] bg-red-600/10 blur-[140px] pointer-events-none rounded-full" />
        <div className="absolute top-1/3 left-1/4 w-[300px] h-[200px] bg-indigo-600/10 blur-[120px] pointer-events-none rounded-full" />

        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 relative z-10 text-center space-y-8">
          
          {/* Badge */}
          <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-red-500/10 border border-red-500/20 text-red-400 text-xs font-bold shadow-inner">
            <Youtube className="w-4 h-4 fill-red-400" />
            <span>{t('badge')}</span>
          </div>

          {/* Main Heading */}
          <h1 className="text-4xl sm:text-6xl lg:text-7xl font-extrabold text-white tracking-tight leading-[1.15] max-w-4xl mx-auto">
            {t('title')}
          </h1>

          {/* Subtitle */}
          <p className="text-base sm:text-lg text-slate-400 max-w-2xl mx-auto font-normal leading-relaxed">
            {t('subtitle')}
          </p>

          {/* Search Bar */}
          <div className="max-w-2xl mx-auto relative group">
            <div className="absolute -inset-1 rounded-2xl bg-gradient-to-r from-red-600 via-rose-500 to-indigo-600 opacity-30 group-hover:opacity-60 blur-lg transition duration-500" />
            <div className="relative flex items-center bg-slate-900 border border-slate-700/80 rounded-2xl p-2 shadow-2xl">
              <Search className="w-5 h-5 text-slate-400 ml-3 flex-shrink-0" />
              <input
                type="text"
                placeholder={t('searchPlaceholder')}
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full bg-transparent px-3 py-2 text-sm text-white placeholder-slate-500 focus:outline-none"
              />
              {searchQuery && (
                <button
                  onClick={() => setSearchQuery('')}
                  className="px-3 py-1 text-xs text-slate-400 hover:text-white bg-slate-800 rounded-lg mr-1"
                >
                  Clear
                </button>
              )}
            </div>
          </div>

          {/* Category Chips */}
          <div className="flex flex-wrap items-center justify-center gap-2 pt-2">
            <button
              onClick={() => setSelectedCategory(null)}
              className={`px-4 py-1.5 rounded-full text-xs font-bold transition-all ${
                selectedCategory === null
                  ? 'bg-red-600 text-white shadow-lg shadow-red-600/30 ring-2 ring-red-400/50'
                  : 'bg-slate-900 hover:bg-slate-800 text-slate-300 border border-slate-800'
              }`}
            >
              All Topics
            </button>
            {categories.map((cat) => (
              <button
                key={cat.id || cat.name}
                onClick={() => setSelectedCategory(selectedCategory === cat.name ? null : cat.name)}
                className={`px-4 py-1.5 rounded-full text-xs font-bold transition-all ${
                  selectedCategory === cat.name
                    ? 'bg-red-600 text-white shadow-lg shadow-red-600/30 ring-2 ring-red-400/50'
                    : 'bg-slate-900 hover:bg-slate-800 text-slate-300 border border-slate-800'
                }`}
              >
                {cat.name}
              </button>
            ))}
          </div>

          {/* Statistics Bar */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 pt-6 max-w-4xl mx-auto border-t border-slate-800/80">
            <div className="p-4 rounded-xl bg-slate-900/40 border border-slate-800/60 text-center">
              <div className="text-2xl font-black text-white flex items-center justify-center gap-1.5">
                <Youtube className="w-5 h-5 text-red-500" />
                <span>120+</span>
              </div>
              <div className="text-xs text-slate-400 mt-1 font-medium">{t('statVideos')}</div>
            </div>

            <div className="p-4 rounded-xl bg-slate-900/40 border border-slate-800/60 text-center">
              <div className="text-2xl font-black text-white flex items-center justify-center gap-1.5">
                <Download className="w-5 h-5 text-emerald-400" />
                <span>100K+</span>
              </div>
              <div className="text-xs text-slate-400 mt-1 font-medium">{t('statDownloads')}</div>
            </div>

            <div className="p-4 rounded-xl bg-slate-900/40 border border-slate-800/60 text-center">
              <div className="text-2xl font-black text-white flex items-center justify-center gap-1.5">
                <Users className="w-5 h-5 text-sky-400" />
                <span>50K+</span>
              </div>
              <div className="text-xs text-slate-400 mt-1 font-medium">{t('statSubscribers')}</div>
            </div>

            <div className="p-4 rounded-xl bg-slate-900/40 border border-slate-800/60 text-center">
              <div className="text-2xl font-black text-white flex items-center justify-center gap-1.5">
                <Zap className="w-5 h-5 text-amber-400" />
                <span>99.8%</span>
              </div>
              <div className="text-xs text-slate-400 mt-1 font-medium">{t('statSatisfaction')}</div>
            </div>
          </div>

        </div>
      </section>

      {/* FEATURED LESSON BANNER */}
      {featuredVideo && !selectedCategory && !searchQuery && (
        <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 w-full">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-xl font-extrabold text-white flex items-center gap-2">
              <Sparkles className="w-5 h-5 text-red-500" />
              <span>{sec('featured')}</span>
            </h2>
          </div>

          <div className="relative rounded-3xl bg-slate-900/80 border border-slate-800 overflow-hidden shadow-2xl p-6 sm:p-8 grid grid-cols-1 lg:grid-cols-12 gap-8 items-center">
            
            {/* Thumbnail preview */}
            <div className="lg:col-span-7 relative aspect-video rounded-2xl overflow-hidden bg-slate-950 group">
              <img
                src={featuredVideo.thumbnailUrl}
                alt={featuredVideo.title}
                className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
              />
              <div className="absolute inset-0 bg-slate-950/40 flex items-center justify-center">
                <Link
                  href={`/${locale}/dersler/${featuredVideo.slug}`}
                  className="w-16 h-16 rounded-full bg-red-600 hover:bg-red-500 text-white flex items-center justify-center shadow-xl shadow-red-600/40 transition-all hover:scale-110"
                >
                  <Youtube className="w-8 h-8 fill-white ml-0.5" />
                </Link>
              </div>
            </div>

            {/* Info & CTA */}
            <div className="lg:col-span-5 space-y-4">
              <div className="inline-block px-3 py-1 rounded-full bg-red-500/10 text-red-400 text-xs font-bold border border-red-500/20">
                {featuredVideo.category}
              </div>

              <h3 className="text-2xl font-black text-white leading-tight">
                {featuredVideo.title}
              </h3>

              <p className="text-xs text-slate-300 leading-relaxed">
                {featuredVideo.summary}
              </p>

              <div className="space-y-2 pt-2">
                <div className="text-xs font-semibold text-slate-400">Files Included:</div>
                <div className="flex flex-wrap gap-2">
                  {featuredVideo.codeSnippets.map((snip: any) => (
                    <span key={snip.fileName} className="px-2.5 py-1 rounded-lg bg-slate-800 text-slate-300 text-[11px] font-mono border border-slate-700">
                      {snip.fileName}
                    </span>
                  ))}
                </div>
              </div>

              <div className="pt-4 flex flex-wrap gap-3">
                <Link
                  href={`/${locale}/dersler/${featuredVideo.slug}`}
                  className="px-5 py-3 rounded-xl bg-red-600 hover:bg-red-500 text-white text-xs font-bold flex items-center gap-2 shadow-lg shadow-red-600/30 transition-all"
                >
                  <span>Explore Code & Notes</span>
                  <ArrowRight className="w-4 h-4" />
                </Link>

                <a
                  href={featuredVideo.youtubeUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="px-4 py-3 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-200 text-xs font-bold flex items-center gap-2 transition-colors border border-slate-700"
                >
                  <Youtube className="w-4 h-4 text-red-500" />
                  <span>Watch on YouTube</span>
                </a>
              </div>
            </div>

          </div>
        </section>
      )}

      {/* ALL LESSONS GRID */}
      <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 w-full space-y-6">
        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
          <div>
            <h2 className="text-2xl font-extrabold text-white flex items-center gap-2">
              <Code2 className="w-6 h-6 text-red-500" />
              <span>{sec('allLessons')}</span>
            </h2>
            <p className="text-xs text-slate-400 mt-1">
              {lessons.length} tutorials found in database {selectedCategory && `(${selectedCategory})`}
            </p>
          </div>

          <Link
            href={`/${locale}/dersler`}
            className="text-xs font-bold text-red-400 hover:text-red-300 flex items-center gap-1 transition-colors"
          >
            <span>View All Lessons</span>
            <ArrowRight className="w-3.5 h-3.5" />
          </Link>
        </div>

        {loading ? (
          <div className="p-12 text-center text-slate-400 flex items-center justify-center gap-2">
            <Loader2 className="w-5 h-5 animate-spin text-red-500" />
            <span>Loading tutorials...</span>
          </div>
        ) : lessons.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {lessons.map((lesson) => (
              <ResourceCard key={lesson.id} lesson={lesson} locale={locale} />
            ))}
          </div>
        ) : (
          <div className="p-12 text-center bg-slate-900/40 rounded-2xl border border-slate-800 space-y-3">
            <ShieldAlert className="w-10 h-10 text-slate-500 mx-auto" />
            <h3 className="text-base font-bold text-white">No Tutorials Found</h3>
            <p className="text-xs text-slate-400 max-w-sm mx-auto">
              Try adjusting your search terms or clearing selected filters.
            </p>
            <button
              onClick={() => { setSearchQuery(''); setSelectedCategory(null); }}
              className="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-xs font-bold text-white rounded-lg transition-colors"
            >
              Reset Filters
            </button>
          </div>
        )}
      </section>

      {/* AYRIS.TECH YOUTUBE CHANNEL FEATURES */}
      <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 w-full">
        <div className="bg-gradient-to-br from-slate-900 via-slate-950 to-slate-900 rounded-3xl border border-slate-800 p-8 sm:p-12 space-y-8 shadow-2xl relative overflow-hidden">
          
          <div className="absolute top-0 right-0 w-96 h-96 bg-red-600/5 blur-[120px] pointer-events-none rounded-full" />

          <div className="text-center space-y-3 max-w-2xl mx-auto">
            <span className="text-xs font-bold uppercase tracking-widest text-red-400 bg-red-500/10 px-3 py-1 rounded-full border border-red-500/20">
              Creator Innovation
            </span>
            <h2 className="text-3xl sm:text-4xl font-black text-white tracking-tight">
              {sec('whyUsTitle')}
            </h2>
            <p className="text-xs sm:text-sm text-slate-400">
              {sec('whyUsSubtitle')}
            </p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 pt-4">
            
            {/* Feature 1 */}
            <div className="p-6 rounded-2xl bg-slate-900/80 border border-slate-800 space-y-3 hover:border-red-500/40 transition-colors">
              <div className="w-10 h-10 rounded-xl bg-red-500/10 text-red-400 flex items-center justify-center">
                <Layers className="w-5 h-5" />
              </div>
              <h3 className="font-bold text-white text-base">{feat('codeTabsTitle')}</h3>
              <p className="text-xs text-slate-400 leading-relaxed">{feat('codeTabsDesc')}</p>
            </div>

            {/* Feature 2 */}
            <div className="p-6 rounded-2xl bg-slate-900/80 border border-slate-800 space-y-3 hover:border-red-500/40 transition-colors">
              <div className="w-10 h-10 rounded-xl bg-emerald-500/10 text-emerald-400 flex items-center justify-center">
                <Youtube className="w-5 h-5" />
              </div>
              <h3 className="font-bold text-white text-base">{feat('chaptersTitle')}</h3>
              <p className="text-xs text-slate-400 leading-relaxed">{feat('chaptersDesc')}</p>
            </div>

            {/* Feature 3 */}
            <div className="p-6 rounded-2xl bg-slate-900/80 border border-slate-800 space-y-3 hover:border-red-500/40 transition-colors">
              <div className="w-10 h-10 rounded-xl bg-sky-500/10 text-sky-400 flex items-center justify-center">
                <Download className="w-5 h-5" />
              </div>
              <h3 className="font-bold text-white text-base">{feat('zipDownloadTitle')}</h3>
              <p className="text-xs text-slate-400 leading-relaxed">{feat('zipDownloadDesc')}</p>
            </div>

            {/* Feature 4 */}
            <div className="p-6 rounded-2xl bg-slate-900/80 border border-slate-800 space-y-3 hover:border-red-500/40 transition-colors">
              <div className="w-10 h-10 rounded-xl bg-amber-500/10 text-amber-400 flex items-center justify-center">
                <FileCheck2 className="w-5 h-5" />
              </div>
              <h3 className="font-bold text-white text-base">{feat('noDocsTitle')}</h3>
              <p className="text-xs text-slate-400 leading-relaxed">{feat('noDocsDesc')}</p>
            </div>

          </div>

        </div>
      </section>

      {/* FEATURED CHEATSHEETS PREVIEW */}
      <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 w-full space-y-6">
        <div className="flex items-center justify-between">
          <h2 className="text-2xl font-extrabold text-white flex items-center gap-2">
            <FileCheck2 className="w-6 h-6 text-red-500" />
            <span>{sec('cheatsheetsTitle')}</span>
          </h2>

          <Link
            href={`/${locale}/rehberler`}
            className="text-xs font-bold text-red-400 hover:text-red-300 flex items-center gap-1 transition-colors"
          >
            <span>Explore All Cheatsheets</span>
            <ArrowRight className="w-3.5 h-3.5" />
          </Link>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {cheatsheets.map((cs) => (
            <div key={cs.id} className="p-6 rounded-2xl bg-slate-900/60 border border-slate-800 space-y-4 hover:bg-slate-900 transition-colors">
              <div className="flex items-center justify-between">
                <span className="text-[11px] font-semibold text-red-400 bg-red-500/10 px-2.5 py-0.5 rounded-full border border-red-500/20">
                  {cs.category}
                </span>
              </div>

              <h3 className="font-bold text-white text-base">{cs.title}</h3>
              <p className="text-xs text-slate-400 line-clamp-2">{cs.description}</p>

              <div className="space-y-2 pt-2 border-t border-slate-800">
                {cs.items.slice(0, 3).map((item: any, idx: number) => (
                  <div key={idx} className="bg-slate-950 p-2 rounded-lg text-xs font-mono text-slate-300 flex items-center justify-between">
                    <span className="text-red-300 font-bold truncate max-w-[200px]">{item.command}</span>
                    <span className="text-[10px] text-slate-500 truncate">{item.description}</span>
                  </div>
                ))}
              </div>

              <Link
                href={`/${locale}/rehberler`}
                className="w-full py-2 flex items-center justify-center gap-1.5 text-xs font-bold text-slate-300 hover:text-white bg-slate-800 hover:bg-slate-700 rounded-xl transition-colors"
              >
                <span>Open Cheatsheet</span>
                <ArrowRight className="w-3.5 h-3.5" />
              </Link>
            </div>
          ))}
        </div>
      </section>

    </div>
  );
}
