'use client';

import React, { useState, useEffect } from 'react';
import { 
  Shield, 
  Scroll,
  TrafficCone,
  MessageSquare,
  Phone,
  Facebook,
  Instagram,
  Twitter,
  Youtube,
  MessageCircle,
  X,
  ChevronRight,
  ExternalLink
} from 'lucide-react'
import GlassmorphismButton from './GlassmorphismButton'

interface Settings {
  siteName?: string;
  siteDescription?: string;
  contactEmail?: string;
  contactPhone?: string;
  contactWhatsApp?: string;
  address?: string;
  workingHours?: string;
  heroTitle?: string;
  heroSubtitle?: string;
  heroDescription?: string;
  heroButtonText?: string;
  heroButtonLink?: string;
  heroSecondaryButtonText?: string;
  heroSecondaryButtonLink?: string;
  heroBackgroundImage?: string;
  siteLogo?: string;
  polresLogo?: string;
  metaTitle?: string;
  metaDescription?: string;
  metaKeywords?: string;
  ogImage?: string;
}

interface Slider {
  id: string;
  title: string;
  subtitle?: string;
  description?: string;
  imageFile?: string;
  imageUrl?: string;
  linkUrl?: string;
  displayType?: string;
  isActive: boolean;
  order: number;
}

interface SocialMedia {
  id: string;
  platform: string;
  name: string;
  url: string;
  username?: string;
  description?: string;
  icon?: string;
  isActive: boolean;
  order: number;
}

interface ServiceLink {
  id: string;
  title: string;
  subtitle?: string;
  description?: string;
  linkType: string;
  linkUrl?: string;
  linkPage?: string;
  iconFile?: string;
  iconUrl?: string;
  order: number;
  isActive: boolean;
  parentId?: string;
  children?: ServiceLink[]; // For submenu items
}

const defaultSettings: Settings = {
  siteName: 'Polres Wonosobo',
  siteDescription: 'Layanan Kepolisian Profesional',
  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: 'Kepolisian Resort Wonosobo',
  heroSubtitle: 'Layanan Profesional & Terpercaya',
  heroDescription: 'Institusi kepolisian yang berkomitmen memberikan pelayanan terbaik dengan standar profesionalisme tinggi',
  heroButtonText: 'Layanan Kami',
  heroButtonLink: '#layanan',
  heroSecondaryButtonText: 'Hubungi Kami',
  heroSecondaryButtonLink: '#kontak',
  heroBackgroundImage: '',
  siteLogo: '',
  polresLogo: ''
}

export default function CorporateLandingPage() {
  const [settings, setSettings] = useState<Settings>(defaultSettings)
  const [sliders, setSliders] = useState<Slider[]>([])
  const [socialMedia, setSocialMedia] = useState<SocialMedia[]>([])
  const [serviceLinks, setServiceLinks] = useState<ServiceLink[]>([])
  const [loading, setLoading] = useState(true)
  const [selectedService, setSelectedService] = useState<ServiceLink | null>(null)
  const [showSubmenuModal, setShowSubmenuModal] = useState(false)

  useEffect(() => {
    async function fetchData() {
      try {
        // Fetch settings
        const settingsResponse = await fetch('/api/settings')
        if (settingsResponse.ok) {
          const settingsResult = await settingsResponse.json()
          if (settingsResult.success && settingsResult.settings) {
            setSettings({ ...defaultSettings, ...settingsResult.settings })
          }
        }

        // Fetch sliders
        const slidersResponse = await fetch('/api/sliders')
        if (slidersResponse.ok) {
          const slidersResult = await slidersResponse.json()
          if (slidersResult.success && slidersResult.data) {
            // Filter only active sliders
            setSliders(slidersResult.data.filter((slider: Slider) => slider.isActive))
          }
        }

        // Fetch service links (Kelola Layanan) with children
        const serviceLinksResponse = await fetch('/api/service-links?includeChildren=true')
        if (serviceLinksResponse.ok) {
          const serviceLinksResult = await serviceLinksResponse.json()
          if (serviceLinksResult.success && serviceLinksResult.data) {
            // Filter only active service links
            const activeLinks = serviceLinksResult.data.filter((link: ServiceLink) => link.isActive)
            
            // The API already includes children, so we just need to organize them
            setServiceLinks(activeLinks)
          }
        }

        // Fetch social media
        const socialMediaResponse = await fetch('/api/social-media')
        if (socialMediaResponse.ok) {
          const socialMediaResult = await socialMediaResponse.json()
          if (socialMediaResult.success && socialMediaResult.data) {
            setSocialMedia(socialMediaResult.data)
          }
        }
      } catch (error) {
        console.error('Error fetching data:', error)
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [])

  // Get background image from sliders or fallback to settings
  const getBackgroundImage = () => {
    if (sliders && sliders.length > 0) {
      // Prioritize BACKGROUND_ONLY type sliders for background
      const backgroundSlider = sliders.find(slider => slider.displayType === 'BACKGROUND_ONLY') || sliders[0]
      const imagePath = backgroundSlider.imageFile || backgroundSlider.imageUrl
      if (imagePath) {
        const fullPath = imagePath.startsWith('/') ? imagePath : `/${imagePath}`
        console.log('Using background image:', fullPath, 'from slider:', backgroundSlider.title)
        return fullPath
      }
    }
    console.log('Using fallback background image')
    return settings.heroBackgroundImage
  }

  // Get icon and color based on platform
  const getSocialMediaIcon = (platform: string) => {
    switch (platform.toLowerCase()) {
      case 'facebook':
        return { icon: Facebook, color: 'bg-blue-700 hover:bg-blue-800' }
      case 'instagram':
        return { icon: Instagram, color: 'bg-pink-600 hover:bg-pink-700' }
      case 'twitter':
        return { icon: Twitter, color: 'bg-black hover:bg-gray-800' }
      case 'youtube':
        return { icon: Youtube, color: 'bg-red-600 hover:bg-red-700' }
      case 'tiktok':
        return { icon: Twitter, color: 'bg-black hover:bg-gray-800' } // Using Twitter as placeholder
      case 'linkedin':
        return { icon: Facebook, color: 'bg-blue-700 hover:bg-blue-800' } // Using Facebook as placeholder
      case 'whatsapp':
        return { icon: MessageCircle, color: 'bg-green-500 hover:bg-green-600' }
      case 'telegram':
        return { icon: MessageCircle, color: 'bg-blue-500 hover:bg-blue-600' }
      default:
        return { icon: Facebook, color: 'bg-gray-600 hover:bg-gray-700' }
    }
  }

  // Get icon and color based on service title/type
  const getServiceIcon = (title: string, linkType: string) => {
    const titleLower = title.toLowerCase()
    
    if (titleLower.includes('spkt')) {
      return { icon: Shield, color: 'bg-red-800 border-amber-400' }
    } else if (titleLower.includes('skck')) {
      return { icon: Scroll, color: 'bg-yellow-700 border-amber-400' }
    } else if (titleLower.includes('lalu lintas') || titleLower.includes('lalin') || titleLower.includes('sim') || titleLower.includes('stnk')) {
      return { icon: TrafficCone, color: 'bg-blue-700 border-amber-400' }
    } else if (titleLower.includes('chat') || titleLower.includes('live')) {
      return { icon: MessageSquare, color: 'bg-green-500' }
    } else if (titleLower.includes('call') || titleLower.includes('darurat') || titleLower.includes('110')) {
      return { icon: Phone, color: 'bg-red-600' }
    } else {
      // Default icons based on link type
      if (linkType === 'EXTERNAL') {
        return { icon: Scroll, color: 'bg-gradient-to-br from-amber-600 to-orange-700 border-amber-400' }
      } else {
        return { icon: Shield, color: 'bg-gradient-to-br from-blue-600 to-purple-700 border-amber-400' }
      }
    }
  }

  // Get service link URL based on link type
  const getServiceLinkUrl = (service: ServiceLink) => {
    switch (service.linkType) {
      case 'EXTERNAL':
        return service.linkUrl || '#'
      case 'INTERNAL':
        return service.linkPage || service.linkUrl || '#'
      case 'SUBMENU':
        return '#' // Submenu items handled by modal
      default:
        return service.linkUrl || '#'
    }
  }

  // Handle service click
  const handleServiceClick = (service: ServiceLink) => {
    if (service.linkType === 'SUBMENU' && service.children && service.children.length > 0) {
      setSelectedService(service)
      setShowSubmenuModal(true)
    } else {
      const url = getServiceLinkUrl(service)
      if (url && url !== '#') {
        if (service.linkType === 'EXTERNAL') {
          // Handle special URL schemes
          if (url.startsWith('tel:') || url.startsWith('mailto:') || url.startsWith('sms:') || url.startsWith('callto:')) {
            window.location.href = url
          } else {
            // For http, https, ftp, and other web links, open in new tab
            window.open(url, '_blank', 'noopener,noreferrer')
          }
        } else {
          window.location.href = url
        }
      }
    }
  }

  // Handle submenu item click
  const handleSubmenuClick = (submenuItem: ServiceLink) => {
    const url = getServiceLinkUrl(submenuItem)
    if (url && url !== '#') {
      if (submenuItem.linkType === 'EXTERNAL') {
        // Handle special URL schemes
        if (url.startsWith('tel:') || url.startsWith('mailto:') || url.startsWith('sms:') || url.startsWith('callto:')) {
          window.location.href = url
        } else {
          // For http, https, ftp, and other web links, open in new tab
          window.open(url, '_blank', 'noopener,noreferrer')
        }
      } else {
        window.location.href = url
      }
    }
    setShowSubmenuModal(false)
    setSelectedService(null)
  }

  // Close modal
  const closeModal = () => {
    setShowSubmenuModal(false)
    setSelectedService(null)
  }

  const whatsappNumber = settings.contactWhatsApp?.replace(/[^\d]/g, '') || '6281234567890'
  const whatsappMessage = 'Halo%20Polres%20Wonosobo,%20saya%20ingin%20bertanya%20mengenai%20layanan%20yang%20tersedia.'

  if (loading) {
    return (
      <div className="bg-gray-900 min-h-screen flex items-center justify-center">
        <div className="text-white text-xl">Loading...</div>
      </div>
    )
  }

  return (
    <div className="min-h-screen flex flex-col relative" style={{ fontFamily: 'Inter, sans-serif' }}>
      {/* Background Container */}
      <div 
        className="absolute inset-0 z-[-20] bg-cover bg-center bg-no-repeat"
        style={{
          backgroundImage: `url('${getBackgroundImage() || 'https://picsum.photos/seed/polres-wonosobo/1200/800.jpg'}')`,
          filter: 'brightness(1.2) contrast(1.05) saturate(1.1)',
          backgroundColor: '#1a1a1a' // Dark fallback background color
        }}
      />
      
      {/* Background Overlay - Gradasi sangat halus dari bawah ke atas */}
      <div 
        className="absolute inset-0 z-[-10]"
        style={{
          background: 'linear-gradient(to top, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0.15) 40%, rgba(0, 0, 0, 0.05) 70%, transparent 100%)'
        }}
      />
      
      {/* Gold Effect Overlay - Sangat subtle dari atas */}
      <div 
        className="absolute inset-0 z-[-5]"
        style={{
          background: 'radial-gradient(ellipse at center top, rgba(255, 192, 0, 0.1) 0%, rgba(255, 192, 0, 0.05) 30%, transparent 60%)',
          pointerEvents: 'none'
        }}
      />

      {/* Main Content */}
      <main className="flex-grow flex flex-col items-center justify-end px-6 py-4 text-center relative z-10">
        
        {/* Services Grid - Menggunakan data dari Kelola Layanan */}
        <section className="w-full max-w-6xl mb-4">
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-2 lg:gap-3 justify-items-stretch">
            
            {/* Dynamic Services dari ServiceLinks (Kelola Layanan) */}
            {serviceLinks.length > 0 ? (
              serviceLinks.map((service) => {
                const { icon: Icon, color } = getServiceIcon(service.title, service.linkType)
                const hasSubmenu = service.linkType === 'SUBMENU' && service.children && service.children.length > 0
                const isExternal = service.linkType === 'EXTERNAL'
                
                return (
                  <div 
                    key={service.id} 
                    className="glassmorphism-button cursor-pointer transform transition-all duration-300 hover:scale-105 p-3 w-full"
                    onClick={() => handleServiceClick(service)}
                  >
                    {/* Service Icon - Use actual logo without background */}
                    <div className="w-16 h-16 mb-3 flex items-center justify-center relative">
                      {service.iconFile || service.iconUrl ? (
                        <img 
                          src={service.iconFile || service.iconUrl}
                          alt={service.title}
                          className="w-full h-full object-contain"
                        />
                      ) : (
                        <div className={`w-12 h-12 ${color.includes('border') ? 'border-2 p-1.5 rounded-full' : 'rounded-full'} ${color.includes('gradient') ? color : `${color} flex items-center justify-center`} text-sm font-bold shadow-lg relative`}>
                          <Icon className="w-7 h-7 text-white" />
                        </div>
                      )}
                      {hasSubmenu && (
                        <div className="absolute -top-1 -right-1 w-3 h-3 bg-amber-400 rounded-full flex items-center justify-center">
                          <ChevronRight className="w-2 h-2 text-black" />
                        </div>
                      )}
                      {isExternal && (
                        <div className="absolute -bottom-1 -right-1 w-3 h-3 bg-green-400 rounded-full flex items-center justify-center">
                          <ExternalLink className="w-2 h-2 text-black" />
                        </div>
                      )}
                    </div>
                    <span className="text-xs font-bold block leading-tight mb-1">Layanan</span>
                    <span className="text-sm font-bold block leading-tight">{service.title}</span>
                  </div>
                )
              })
            ) : (
              // Fallback default services jika tidak ada data
              <>
                {/* Layanan SPKT */}
                <GlassmorphismButton href="#" className="p-3 w-full">
                  <div className="w-16 h-16 mb-3 border-2 border-amber-400 p-1.5 rounded-full bg-red-800 flex items-center justify-center text-sm font-bold shadow-lg">
                    <Shield className="w-7 h-7 text-white" />
                  </div>
                  <span className="text-xs font-bold block leading-tight mb-1">Layanan</span>
                  <span className="text-sm font-bold block leading-tight">SPKT</span>
                </GlassmorphismButton>

                {/* Layanan SKCK */}
                <GlassmorphismButton href="#" className="p-3 w-full">
                  <div className="w-16 h-16 mb-3 border-2 border-amber-400 p-1.5 rounded-full bg-yellow-700 flex items-center justify-center text-sm font-bold shadow-lg">
                    <Scroll className="w-7 h-7 text-white" />
                  </div>
                  <span className="text-xs font-bold block leading-tight mb-1">Layanan</span>
                  <span className="text-sm font-bold block leading-tight">SKCK</span>
                </GlassmorphismButton>

                {/* Layanan Lalu Lintas */}
                <GlassmorphismButton href="#" className="p-3 w-full">
                  <div className="w-16 h-16 mb-3 border-2 border-amber-400 p-1.5 rounded-full bg-blue-700 flex items-center justify-center text-sm font-bold shadow-lg">
                    <TrafficCone className="w-7 h-7 text-white" />
                  </div>
                  <span className="text-xs font-bold block leading-tight mb-1">Layanan</span>
                  <span className="text-sm font-bold block leading-tight">Lalu Lintas</span>
                </GlassmorphismButton>

                {/* Live Chat */}
                <GlassmorphismButton href="#" className="p-3 w-full">
                  <div className="w-16 h-16 mb-3 bg-green-500 rounded-full flex items-center justify-center shadow-lg">
                    <MessageSquare className="w-7 h-7 text-white fill-current" />
                  </div>
                  <span className="text-xs font-bold block leading-tight mb-1">Layanan</span>
                  <span className="text-sm font-bold block leading-tight">Live Chat</span>
                </GlassmorphismButton>
              </>
            )}
          </div>
        </section>

        {/* Social Media Section - Dynamic dari Database */}
        <section className="w-full max-w-lg mb-2">
          <h3 className="text-lg font-semibold text-amber-300 mb-4 tracking-wider uppercase">Ikuti Kami di Media Sosial</h3>
          <div className="flex justify-center space-x-6">
            {socialMedia.length > 0 ? (
              socialMedia.map((social) => {
                const { icon: Icon, color } = getSocialMediaIcon(social.platform)
                return (
                  <a 
                    key={social.id}
                    href={social.url} 
                    target="_blank" 
                    rel="noopener noreferrer"
                    className={`w-12 h-12 ${color} rounded-full flex items-center justify-center text-white shadow-xl transition duration-300`}
                    title={social.name || social.platform}
                  >
                    {social.icon ? (
                      <img 
                        src={social.icon}
                        alt={social.name || social.platform}
                        className="w-full h-full object-contain p-2"
                      />
                    ) : (
                      <Icon className="w-6 h-6" />
                    )}
                  </a>
                )
              })
            ) : (
              // Fallback default social media jika tidak ada data
              <>
                <a href="#" target="_blank" className="w-12 h-12 bg-blue-700 rounded-full flex items-center justify-center text-white shadow-xl hover:bg-blue-800 transition duration-300">
                  <Facebook className="w-6 h-6" />
                </a>
                <a href="#" target="_blank" className="w-12 h-12 bg-pink-600 rounded-full flex items-center justify-center text-white shadow-xl hover:bg-pink-700 transition duration-300">
                  <Instagram className="w-6 h-6" />
                </a>
                <a href="#" target="_blank" className="w-12 h-12 bg-black rounded-full flex items-center justify-center text-white shadow-xl hover:bg-gray-800 transition duration-300">
                  <Twitter className="w-6 h-6" />
                </a>
                <a href="#" target="_blank" className="w-12 h-12 bg-red-600 rounded-full flex items-center justify-center text-white shadow-xl hover:bg-red-700 transition duration-300">
                  <Youtube className="w-6 h-6" />
                </a>
              </>
            )}
          </div>
        </section>
      </main>

      {/* Submenu Modal */}
      {showSubmenuModal && selectedService && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          {/* Backdrop */}
          <div 
            className="absolute inset-0 bg-black bg-opacity-75 backdrop-blur-sm"
            onClick={closeModal}
          />
          
          {/* Modal Content */}
          <div className="relative bg-gray-900 bg-opacity-95 backdrop-blur-md border border-amber-400 rounded-2xl p-6 max-w-2xl w-full max-h-[80vh] overflow-y-auto shadow-2xl">
            {/* Header */}
            <div className="flex items-center justify-between mb-6">
              <div>
                <h2 className="text-2xl font-bold text-amber-300">
                  {selectedService.title}
                </h2>
                {selectedService.subtitle && (
                  <p className="text-gray-300 mt-1">{selectedService.subtitle}</p>
                )}
                {selectedService.description && (
                  <p className="text-gray-400 text-sm mt-2">{selectedService.description}</p>
                )}
              </div>
              <button
                onClick={closeModal}
                className="w-10 h-10 bg-red-600 hover:bg-red-700 rounded-full flex items-center justify-center text-white transition-colors duration-200"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            
            {/* Submenu Items */}
            <div className="space-y-3">
              {selectedService.children && selectedService.children.length > 0 ? (
                selectedService.children
                  .sort((a, b) => a.order - b.order)
                  .map((submenuItem) => {
                    const { icon: Icon, color } = getServiceIcon(submenuItem.title, submenuItem.linkType)
                    const isExternal = submenuItem.linkType === 'EXTERNAL'
                    
                    return (
                      <div
                        key={submenuItem.id}
                        onClick={() => handleSubmenuClick(submenuItem)}
                        className="flex items-center justify-between p-4 bg-gray-800 bg-opacity-50 hover:bg-opacity-70 border border-gray-700 hover:border-amber-400 rounded-xl cursor-pointer transition-all duration-200 group"
                      >
                        <div className="flex items-center space-x-4">
                          {/* Submenu Icon - Use actual logo without background */}
                          <div className="w-10 h-10 flex items-center justify-center">
                            {submenuItem.iconFile || submenuItem.iconUrl ? (
                              <img 
                                src={submenuItem.iconFile || submenuItem.iconUrl}
                                alt={submenuItem.title}
                                className="w-full h-full object-contain"
                              />
                            ) : (
                              <div className={`w-10 h-10 ${color.includes('border') ? 'border-2 p-1 rounded-full' : 'rounded-full'} ${color.includes('gradient') ? color : `${color} flex items-center justify-center`} text-xs font-bold`}>
                                <Icon className="w-5 h-5 text-white" />
                              </div>
                            )}
                          </div>
                          <div>
                            <h3 className="text-white font-semibold group-hover:text-amber-300 transition-colors">
                              {submenuItem.title}
                            </h3>
                            {submenuItem.subtitle && (
                              <p className="text-gray-400 text-sm">{submenuItem.subtitle}</p>
                            )}
                            {submenuItem.description && (
                              <p className="text-gray-500 text-xs mt-1">{submenuItem.description}</p>
                            )}
                          </div>
                        </div>
                        
                        <div className="flex items-center space-x-2">
                          {isExternal && (
                            <span className="text-xs text-green-400 bg-green-400 bg-opacity-20 px-2 py-1 rounded-full">
                              Eksternal
                            </span>
                          )}
                          <ChevronRight className="w-5 h-5 text-gray-400 group-hover:text-amber-300 transition-colors" />
                        </div>
                      </div>
                    )
                  })
              ) : (
                <div className="text-center py-8">
                  <p className="text-gray-400">Tidak ada submenu tersedia</p>
                </div>
              )}
            </div>
            
            {/* Footer */}
            <div className="mt-6 pt-4 border-t border-gray-700">
              <p className="text-center text-gray-500 text-sm">
                Klik pada submenu untuk melanjutkan
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Floating Action Button (FAB) WhatsApp - Sesuai Template */}
      <a href={`https://wa.me/${whatsappNumber}?text=${whatsappMessage}`} 
         target="_blank" 
         className="fixed bottom-5 right-5 z-100 rounded-full w-14 h-14 flex items-center justify-center transition-transform duration-300"
         style={{
           backgroundColor: '#25D366',
           boxShadow: '0 4px 10px rgba(0, 0, 0, 0.5), 0 0 20px #25D366'
         }}
         onMouseEnter={(e) => {
           e.currentTarget.style.transform = 'scale(1.1)'
         }}
         onMouseLeave={(e) => {
           e.currentTarget.style.transform = 'scale(1)'
         }}
         title="Hubungi Kami">
        <MessageCircle className="w-8 h-8 text-white fill-white" />
      </a>

      {/* Footer - Gradasi Corporate #050400 ke #c38c14 */}
      <footer className="p-3 text-center text-xs font-medium text-white relative z-10"
              style={{
                background: 'linear-gradient(90deg, #050400 0%, #c38c14 100%)',
                boxShadow: '0 0 20px rgba(195, 140, 20, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.1)',
                borderTop: '1px solid rgba(195, 140, 20, 0.3)'
              }}>
        POLRES WONOSOBO TULUS DAN RELIGIUS
      </footer>
    </div>
  )
}