import { db } from '@/lib/db'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import Link from 'next/link'
import { Metadata } from 'next'
import { generateSEOMetadata, generateJsonLd } from '@/lib/seo'
import { SafeImage } from '@/components/SafeImage'
import { 
  FileText, 
  Search, 
  Car, 
  Shield, 
  MapPin, 
  Phone, 
  Mail, 
  Clock,
  CheckCircle,
  Users,
  TrendingUp,
  ArrowRight,
  Star,
  Zap,
  Lock,
  MessageCircle,
  ExternalLink,
  Globe,
  Award,
  BarChart3
} from 'lucide-react'
import Image from 'next/image'
import WhatsAppFloat from '@/components/WhatsAppFloat'

async function getServices() {
  try {
    const services = await db.service.findMany({
      where: { status: 'ACTIVE' },
      orderBy: { title: 'asc' }
    })
    return services
  } catch (error) {
    console.error('Error fetching services:', error)
    return []
  }
}

interface Service {
  id: string
  title: string
  slug: string
  description: string
  category?: string
  iconUrl?: string
  linkType?: 'INTERNAL' | 'EXTERNAL'
  linkUrl?: string
  isNewTab?: boolean
}

async function getSettings() {
  try {
    const settings = await db.systemSettings.findFirst({
      select: {
        siteName: true,
        siteDescription: true,
        contactEmail: true,
        contactPhone: true,
        contactWhatsApp: true,
        address: true,
        workingHours: true,
        heroTitle: true,
        heroSubtitle: true,
        heroDescription: true,
        heroButtonText: true,
        heroButtonLink: true,
        heroSecondaryButtonText: true,
        heroSecondaryButtonLink: true,
        heroBackgroundImage: true,
        siteLogo: true,
        polresLogo: true,
        metaTitle: true,
        metaDescription: true,
        metaKeywords: true,
        ogImage: true
      }
    })
    return settings || {}
  } catch (error) {
    console.error('Error fetching settings:', error)
    return {}
  }
}

export async function generateMetadata(): Promise<Metadata> {
  try {
    const settings = await db.systemSettings.findFirst({
      select: {
        metaTitle: true,
        metaDescription: true,
        metaKeywords: true,
        ogImage: true,
        siteName: true,
        heroTitle: true
      }
    })
    
    const seoSettings = {
      metaTitle: settings?.metaTitle || undefined,
      metaDescription: settings?.metaDescription || undefined,
      metaKeywords: settings?.metaKeywords || undefined,
      ogImage: settings?.ogImage || undefined,
      siteName: settings?.siteName || undefined,
      siteUrl: undefined,
    }

    return generateSEOMetadata(seoSettings, settings?.heroTitle || 'Sistem Pelayanan Digital Modern')
  } catch (error) {
    console.error('Error fetching SEO settings:', error)
    
    return {
      title: "Polres Wonosobo - Sistem Pelayanan Digital Modern",
      description: "Platform digital kepolisian modern dengan teknologi terkini untuk kemudahan layanan masyarakat",
      keywords: "polres wonosobo, pelayanan digital, teknologi polisi, layanan online",
    }
  }
}

export default async function ModernLandingPage() {
  const services = await getServices()
  const settings = await getSettings()

  const defaultSettings = {
    siteName: 'Polres Wonosobo',
    siteDescription: 'Platform Digital Kepolisian Modern',
    contactEmail: 'polreswonosobo@polri.go.id',
    contactPhone: '(0286) 321001',
    contactWhatsApp: '+62 812-3456-7890',
    address: 'Jl. Pahlawan No. 15, Wonosobo',
    workingHours: 'Senin - Jumat: 08:00 - 16:00',
    heroTitle: 'Platform Digital Kepolisian',
    heroSubtitle: 'Era Modern Layanan Prima',
    heroDescription: 'Menghadirkan inovasi teknologi dalam pelayanan kepolisian untuk kemudahan dan kenyamanan masyarakat',
    heroButtonText: 'Jelajahi Layanan',
    heroButtonLink: '#layanan',
    heroSecondaryButtonText: 'Dashboard',
    heroSecondaryButtonLink: '/dashboard',
    heroBackgroundImage: '/hero-bg-modern.jpg',
    siteLogo: '',
    polresLogo: ''
  }

  const mergedSettings = { ...defaultSettings, ...settings }

  const getServiceIcon = (service: Service) => {
    switch (service.slug) {
      case 'skck':
        return <FileText className="w-10 h-10" />
      case 'spkt':
        return <Shield className="w-10 h-10" />
      case 'lalu-lintas':
        return <Car className="w-10 h-10" />
      default:
        return <Globe className="w-10 h-10" />
    }
  }

  const features = [
    {
      icon: <BarChart3 className="w-8 h-8" />,
      title: "Dashboard Analytics",
      description: "Pantau statistik dan analitik layanan secara real-time dengan visualisasi data yang interaktif",
      color: "from-blue-500 to-cyan-500",
      bgColor: "bg-blue-50"
    },
    {
      icon: <Zap className="w-8 h-8" />,
      title: "Lightning Fast",
      description: "Proses pengajuan dokumen dengan kecepatan tinggi menggunakan teknologi cloud computing",
      color: "from-yellow-500 to-orange-500",
      bgColor: "bg-yellow-50"
    },
    {
      icon: <Award className="w-8 h-8" />,
      title: "Certified Secure",
      description: "Sistem dengan sertifikasi keamanan internasional dan enkripsi data end-to-end",
      color: "from-green-500 to-emerald-500",
      bgColor: "bg-green-50"
    },
    {
      icon: <Users className="w-8 h-8" />,
      title: "AI Assistant",
      description: "Dukungan AI chatbot 24/7 untuk membantu menjawab pertanyaan dan panduan pengajuan",
      color: "from-purple-500 to-pink-500",
      bgColor: "bg-purple-50"
    }
  ]

  const stats = [
    { number: "15,000+", label: "Pengguna Aktif", icon: <Users className="w-6 h-6" /> },
    { number: "99.9%", label: "Uptime", icon: <BarChart3 className="w-6 h-6" /> },
    { number: "500ms", label: "Response Time", icon: <Zap className="w-6 h-6" /> },
    { number: "100+", label: "Integrasi API", icon: <Globe className="w-6 h-6" /> }
  ]

  const jsonLd = generateJsonLd({
    metaTitle: mergedSettings.metaTitle || undefined,
    metaDescription: mergedSettings.metaDescription || undefined,
    metaKeywords: mergedSettings.metaKeywords || undefined,
    ogImage: mergedSettings.ogImage || undefined,
    siteName: mergedSettings.siteName || undefined,
    siteUrl: mergedSettings.siteUrl || undefined,
  }, 'organization')

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-blue-900 to-slate-900">
      
      {/* Modern Hero Section */}
      <section className="relative min-h-screen flex items-center justify-center overflow-hidden">
        <div className="absolute inset-0">
          <div className="absolute inset-0 bg-gradient-to-r from-blue-600/20 to-purple-600/20" />
          <div className="absolute inset-0 bg-[url('/grid.svg')] opacity-10" />
        </div>
        
        <div className="relative z-10 text-center text-white px-4 max-w-6xl mx-auto">
          <div className="mb-8">
            <Badge className="bg-gradient-to-r from-cyan-500 to-blue-500 text-white border-0 px-6 py-2 text-sm font-semibold">
              🚀 Next Generation Platform
            </Badge>
          </div>
          
          <h1 className="text-6xl md:text-8xl font-bold mb-6 leading-tight bg-gradient-to-r from-white to-blue-200 bg-clip-text text-transparent">
            {mergedSettings.heroTitle || 'Platform Digital Kepolisian'}
          </h1>
          
          <h2 className="text-3xl md:text-5xl font-semibold mb-8 text-cyan-300">
            {mergedSettings.heroSubtitle || 'Era Modern Layanan Prima'}
          </h2>
          
          <p className="text-xl md:text-2xl mb-12 max-w-4xl mx-auto text-gray-300 leading-relaxed">
            {mergedSettings.heroDescription || 'Menghadirkan inovasi teknologi dalam pelayanan kepolisian untuk kemudahan dan kenyamanan masyarakat'}
          </p>
          
          <div className="flex flex-col sm:flex-row gap-6 justify-center mb-12">
            <Link href={mergedSettings.heroButtonLink || '#layanan'}>
              <Button size="lg" className="bg-gradient-to-r from-cyan-500 to-blue-500 hover:from-cyan-600 hover:to-blue-600 text-white px-10 py-4 text-lg font-semibold rounded-2xl hover:scale-105 transition-all shadow-2xl">
                {mergedSettings.heroButtonText || 'Jelajahi Layanan'}
                <ArrowRight className="ml-2 h-5 w-5" />
              </Button>
            </Link>
            <Link href={mergedSettings.heroSecondaryButtonLink || '/dashboard'}>
              <Button size="lg" variant="outline" className="border-white/20 text-white hover:bg-white/10 hover:text-white px-10 py-4 text-lg font-semibold rounded-2xl hover:scale-105 transition-all backdrop-blur-sm">
                {mergedSettings.heroSecondaryButtonText || 'Dashboard'}
                <BarChart3 className="ml-2 h-5 w-5" />
              </Button>
            </Link>
          </div>

          {/* Floating Cards */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6 max-w-4xl mx-auto">
            {stats.map((stat, index) => (
              <div key={index} className="bg-white/10 backdrop-blur-md rounded-2xl p-6 border border-white/20">
                <div className="flex items-center justify-between mb-2">
                  <div className="text-cyan-400">
                    {stat.icon}
                  </div>
                  <div className="text-2xl font-bold text-white">
                    {stat.number}
                  </div>
                </div>
                <div className="text-gray-300 text-sm">
                  {stat.label}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Animated Background Elements */}
        <div className="absolute top-20 left-10 w-72 h-72 bg-blue-500/20 rounded-full blur-3xl animate-pulse" />
        <div className="absolute bottom-20 right-10 w-96 h-96 bg-purple-500/20 rounded-full blur-3xl animate-pulse delay-1000" />
      </section>

      {/* Modern Features Section */}
      <section className="py-24 px-4 bg-gradient-to-b from-transparent to-white/5">
        <div className="max-w-7xl mx-auto">
          <div className="text-center mb-20">
            <Badge className="mb-6 bg-gradient-to-r from-cyan-500 to-blue-500 text-white border-0">
              ⚡ Advanced Features
            </Badge>
            <h2 className="text-5xl md:text-6xl font-bold text-white mb-6">
              Teknologi Terkini
            </h2>
            <p className="text-xl text-gray-300 max-w-4xl mx-auto">
              Platform kami dilengkapi dengan teknologi terdepan untuk memberikan pengalaman layanan yang superior
            </p>
          </div>

          <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-8">
            {features.map((feature, index) => (
              <Card key={index} className={`group bg-white/10 backdrop-blur-md border-white/20 hover:bg-white/15 transition-all duration-300 hover:scale-105 rounded-3xl overflow-hidden`}>
                <div className={`h-2 bg-gradient-to-r ${feature.color}`} />
                <CardHeader className="text-center pb-6">
                  <div className={`mx-auto mb-6 p-4 rounded-2xl ${feature.bgColor} group-hover:scale-110 transition-transform`}>
                    <div className={`bg-gradient-to-r ${feature.color} bg-clip-text text-transparent`}>
                      {feature.icon}
                    </div>
                  </div>
                  <CardTitle className="text-2xl font-bold text-white">{feature.title}</CardTitle>
                </CardHeader>
                <CardContent>
                  <p className="text-gray-300 text-center leading-relaxed">
                    {feature.description}
                  </p>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      </section>

      {/* Services Grid Section */}
      <section id="layanan" className="py-24 px-4 bg-gradient-to-b from-white/5 to-transparent">
        <div className="max-w-7xl mx-auto">
          <div className="text-center mb-20">
            <Badge className="mb-6 bg-gradient-to-r from-purple-500 to-pink-500 text-white border-0">
              🎯 Digital Services
            </Badge>
            <h2 className="text-5xl md:text-6xl font-bold text-white mb-6">
              Layanan Digital
            </h2>
            <p className="text-xl text-gray-300 max-w-4xl mx-auto">
              Akses berbagai layanan kepolisian dengan platform digital yang modern dan efisien
            </p>
          </div>

          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
            {services.length > 0 ? (
              services.map((service) => (
                <Card key={service.id} className="group bg-white/10 backdrop-blur-md border-white/20 hover:bg-white/15 transition-all duration-300 hover:scale-105 rounded-3xl overflow-hidden">
                  <div className="h-2 bg-gradient-to-r from-purple-500 to-pink-500" />
                  <CardHeader className="text-center pb-6">
                    <div className="mx-auto mb-6 p-3 bg-gradient-to-br from-purple-500 to-pink-500 rounded-2xl text-white w-24 h-24 flex items-center justify-center group-hover:scale-110 transition-transform shadow-2xl">
                      <div className="w-12 h-12 flex items-center justify-center">
                        {getServiceIcon(service)}
                      </div>
                    </div>
                    <CardTitle className="text-2xl font-bold text-white">{service.title}</CardTitle>
                    <Badge className="w-fit mx-auto bg-green-500/20 text-green-300 hover:bg-green-500/30 border-green-500/30">
                      <CheckCircle className="w-3 h-3 mr-1" />
                      Available
                    </Badge>
                  </CardHeader>
                  <CardContent>
                    <CardDescription className="text-center mb-6 text-gray-300 leading-relaxed">
                      {service.description}
                    </CardDescription>
                    <div className="text-center">
                      {service.linkType === 'EXTERNAL' ? (
                        <a 
                          href={service.linkUrl || '#'}
                          target={service.isNewTab ? '_blank' : '_self'}
                          rel={service.isNewTab ? 'noopener noreferrer' : ''}
                          className="inline-block w-full"
                        >
                          <Button className="w-full bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white px-6 py-3 rounded-2xl font-semibold hover:scale-105 transition-all shadow-xl">
                            {service.isNewTab && <ExternalLink className="mr-2 h-4 w-4" />}
                            Apply Now
                            <ArrowRight className="ml-2 h-4 w-4" />
                          </Button>
                        </a>
                      ) : (
                        <Link href={service.linkUrl || `/ajuan/${service.slug}`}>
                          <Button className="w-full bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white px-6 py-3 rounded-2xl font-semibold hover:scale-105 transition-all shadow-xl">
                            Apply Now
                            <ArrowRight className="ml-2 h-4 w-4" />
                          </Button>
                        </Link>
                      )}
                    </div>
                  </CardContent>
                </Card>
              ))
            ) : (
              [
                {
                  id: '1',
                  title: 'SKCK Digital',
                  slug: 'skck',
                  description: 'Surat Keterangan Catatan Kriminal dengan proses digital yang cepat dan aman',
                  category: 'skck'
                },
                {
                  id: '2',
                  title: 'SPKT Online',
                  slug: 'spkt',
                  description: 'Surat Pemberitahuan Kepolisian Terpadu dengan sistem integrasi data',
                  category: 'spkt'
                },
                {
                  id: '3',
                  title: 'Smart Traffic',
                  slug: 'lalu-lintas',
                  description: 'Layanan lalu lintas cerdas dengan monitoring real-time dan analitik',
                  category: 'lalu-lintas'
                }
              ].map((service) => (
                <Card key={service.id} className="group bg-white/10 backdrop-blur-md border-white/20 hover:bg-white/15 transition-all duration-300 hover:scale-105 rounded-3xl overflow-hidden">
                  <div className="h-2 bg-gradient-to-r from-purple-500 to-pink-500" />
                  <CardHeader className="text-center pb-6">
                    <div className="mx-auto mb-6 p-3 bg-gradient-to-br from-purple-500 to-pink-500 rounded-2xl text-white w-24 h-24 flex items-center justify-center group-hover:scale-110 transition-transform shadow-2xl">
                      <div className="w-12 h-12 flex items-center justify-center">
                        {getServiceIcon(service)}
                      </div>
                    </div>
                    <CardTitle className="text-2xl font-bold text-white">{service.title}</CardTitle>
                    <Badge className="w-fit mx-auto bg-green-500/20 text-green-300 hover:bg-green-500/30 border-green-500/30">
                      <CheckCircle className="w-3 h-3 mr-1" />
                      Available
                    </Badge>
                  </CardHeader>
                  <CardContent>
                    <CardDescription className="text-center mb-6 text-gray-300 leading-relaxed">
                      {service.description}
                    </CardDescription>
                    <div className="text-center">
                      {service.linkType === 'EXTERNAL' ? (
                        <a 
                          href={service.linkUrl || '#'}
                          target={service.isNewTab ? '_blank' : '_self'}
                          rel={service.isNewTab ? 'noopener noreferrer' : ''}
                          className="inline-block w-full"
                        >
                          <Button className="w-full bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white px-6 py-3 rounded-2xl font-semibold hover:scale-105 transition-all shadow-xl">
                            {service.isNewTab && <ExternalLink className="mr-2 h-4 w-4" />}
                            Apply Now
                            <ArrowRight className="ml-2 h-4 w-4" />
                          </Button>
                        </a>
                      ) : (
                        <Link href={service.linkUrl || `/ajuan/${service.slug}`}>
                          <Button className="w-full bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white px-6 py-3 rounded-2xl font-semibold hover:scale-105 transition-all shadow-xl">
                            Apply Now
                            <ArrowRight className="ml-2 h-4 w-4" />
                          </Button>
                        </Link>
                      )}
                    </div>
                  </CardContent>
                </Card>
              ))
            )}
          </div>
        </div>
      </section>

      {/* Modern CTA Section */}
      <section className="py-24 px-4 bg-gradient-to-r from-purple-600/20 to-pink-600/20 backdrop-blur-sm">
        <div className="max-w-4xl mx-auto text-center text-white">
          <h2 className="text-5xl md:text-6xl font-bold mb-6 bg-gradient-to-r from-white to-purple-200 bg-clip-text text-transparent">
            Ready to Experience?
          </h2>
          <p className="text-xl mb-12 text-gray-300 max-w-2xl mx-auto">
            Bergabunglah dengan ribuan pengguna yang telah merasakan kemudahan platform digital kepolisian modern
          </p>
          <div className="flex flex-col sm:flex-row gap-6 justify-center">
            <Link href="#layanan">
              <Button size="lg" className="bg-gradient-to-r from-cyan-500 to-blue-500 hover:from-cyan-600 hover:to-blue-600 text-white px-12 py-4 text-lg font-semibold rounded-2xl hover:scale-105 transition-all shadow-2xl">
                Get Started
                <ArrowRight className="ml-2 h-5 w-5" />
              </Button>
            </Link>
            <Link href="/lacak">
              <Button size="lg" variant="outline" className="border-white/20 text-white hover:bg-white/10 hover:text-white px-12 py-4 text-lg font-semibold rounded-2xl hover:scale-105 transition-all backdrop-blur-sm">
                Track Application
                <Search className="ml-2 h-5 w-5" />
              </Button>
            </Link>
          </div>
        </div>
      </section>

      {/* Modern Footer */}
      <footer className="bg-slate-900/50 backdrop-blur-md text-white py-16 px-4 border-t border-white/10">
        <div className="max-w-7xl mx-auto">
          <div className="grid md:grid-cols-4 gap-8 mb-12">
            <div className="md:col-span-2">
              <h3 className="text-3xl font-bold mb-4 bg-gradient-to-r from-cyan-400 to-blue-400 bg-clip-text text-transparent">
                {mergedSettings.siteName || 'Polres Wonosobo'}
              </h3>
              <p className="text-gray-300 mb-6 leading-relaxed max-w-md">
                {mergedSettings.siteDescription || 'Platform digital kepolisian modern dengan teknologi terkini untuk kemudahan layanan masyarakat.'}
              </p>
              <div className="flex space-x-4">
                <Badge className="bg-gradient-to-r from-cyan-500 to-blue-500 text-white border-0">
                  <Award className="w-3 h-3 mr-1" />
                  Certified
                </Badge>
                <Badge className="bg-gradient-to-r from-green-500 to-emerald-500 text-white border-0">
                  <Shield className="w-3 h-3 mr-1" />
                  Secure
                </Badge>
              </div>
            </div>
            
            <div>
              <h4 className="text-lg font-semibold mb-4 text-cyan-400">Quick Access</h4>
              <div className="space-y-3 text-gray-300">
                <div className="hover:text-white transition-colors cursor-pointer flex items-center gap-2">
                  <div className="w-2 h-2 bg-cyan-400 rounded-full" />
                  Dashboard Analytics
                </div>
                <div className="hover:text-white transition-colors cursor-pointer flex items-center gap-2">
                  <div className="w-2 h-2 bg-cyan-400 rounded-full" />
                  Service Catalog
                </div>
                <div className="hover:text-white transition-colors cursor-pointer flex items-center gap-2">
                  <div className="w-2 h-2 bg-cyan-400 rounded-full" />
                  API Documentation
                </div>
                <div className="hover:text-white transition-colors cursor-pointer flex items-center gap-2">
                  <div className="w-2 h-2 bg-cyan-400 rounded-full" />
                  Status Monitor
                </div>
              </div>
            </div>
            
            <div>
              <h4 className="text-lg font-semibold mb-4 text-cyan-400">Contact</h4>
              <div className="space-y-3 text-gray-300">
                <div className="flex items-center gap-3 hover:text-white transition-colors">
                  <MapPin className="w-5 h-5 text-cyan-400" />
                  <span className="text-sm">{mergedSettings.address || 'Jl. Pahlawan No. 15, Wonosobo'}</span>
                </div>
                <div className="flex items-center gap-3 hover:text-white transition-colors">
                  <Phone className="w-5 h-5 text-cyan-400" />
                  <span className="text-sm">{mergedSettings.contactPhone || '(0286) 321001'}</span>
                </div>
                <div className="flex items-center gap-3 hover:text-white transition-colors">
                  <Mail className="w-5 h-5 text-cyan-400" />
                  <span className="text-sm">{mergedSettings.contactEmail || 'polreswonosobo@polri.go.id'}</span>
                </div>
                <div className="flex items-center gap-3 hover:text-white transition-colors">
                  <MessageCircle className="w-5 h-5 text-cyan-400" />
                  <span className="text-sm">{mergedSettings.contactWhatsApp || '+62 812-3456-7890'}</span>
                </div>
              </div>
            </div>
          </div>
          
          <div className="border-t border-white/10 pt-8">
            <div className="flex flex-col md:flex-row justify-between items-center">
              <p className="text-gray-400 mb-4 md:mb-0 text-sm">
                &copy; 2024 {mergedSettings.siteName || 'Polres Wonosobo'}. All rights reserved.
              </p>
              <div className="flex space-x-6 text-gray-400 text-sm">
                <span className="hover:text-white transition-colors cursor-pointer">Privacy Policy</span>
                <span className="hover:text-white transition-colors cursor-pointer">Terms of Service</span>
                <span className="hover:text-white transition-colors cursor-pointer">Support</span>
              </div>
            </div>
          </div>
        </div>
      </footer>

      {/* Floating WhatsApp Button */}
      <WhatsAppFloat />
    </div>
    </>
  )
}