'use client'

import { useEffect, useState } from 'react'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { 
  AlertTriangle,
  CheckCircle
} from 'lucide-react'
import { useRouter } from 'next/navigation'
import { AdminSidebar } from '@/components/admin-sidebar'
import { SystemSettingsForm } from '@/components/SystemSettingsForm'
import { useLoading } from '@/contexts/LoadingContext'

interface SystemSettings {
  id?: string;
  // General Settings
  siteName: string
  siteUrl?: string
  siteDescription: string
  timezone: string
  dateFormat: string
  timeFormat: string
  
  // Brand Settings
  siteLogo?: string
  siteIcon?: string
  polresLogo?: string
  polresLogo2?: string
  runningText?: string
  
  // System Settings
  maintenanceMode: boolean
  allowRegistration: boolean
  emailVerification: boolean
  sessionTimeout: number
  
  // Email Settings
  smtpHost?: string
  smtpPort?: number
  smtpUser?: string
  smtpPassword?: string
  emailFrom?: string
  emailFromName?: string
  
  // SEO Settings
  metaTitle?: string
  metaDescription?: string
  metaKeywords?: string
  ogImage?: string
  
  // Contact Settings
  contactEmail: string
  contactPhone: string
  contactWhatsApp: string
  address: string
  workingHours: string
  
  // Hero Section
  heroTitle: string
  heroSubtitle: string
  heroDescription: string
  heroBackgroundImage: string
  heroButtonText: string
  heroButtonLink: string
  heroSecondaryButtonText: string
  heroSecondaryButtonLink: string
  
  // Kapolres Profile Settings
  kapolresName: string
  kapolresNRP: string
  kapolresPangkat: string
  kapolresSignature?: string
  
  // Format Penomoran per Kategori
  skckNumberFormat: string
  spktNumberFormat: string
  lalinNumberFormat: string
  skckSequence: number
  spktSequence: number
  lalinSequence: number
  
  // Legacy fields for compatibility
  contactPhone?: string
  contactWhatsApp?: string
  address?: string
  workingHours?: string
  language?: string
  emailNotifications?: boolean
  smsNotifications?: boolean
  autoAssignment?: boolean
  maxFileSize?: number
  allowedFileTypes?: string[]
  passwordMinLength?: number
  requireEmailVerification?: boolean
  siteLogo?: string
  siteIcon?: string
}

export default function AdminSettings() {
  const router = useRouter()
  const { startLoading, stopLoading } = useLoading()
  const [user, setUser] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [message, setMessage] = useState('')
  const [messageType, setMessageType] = useState<'success' | 'error'>('success')
  const [settings, setSettings] = useState<SystemSettings>({
    // General Settings
    siteName: '',
    siteUrl: '',
    siteDescription: '',
    timezone: 'Asia/Jakarta',
    dateFormat: 'DD/MM/YYYY',
    timeFormat: '24h',
    
    // Brand Settings
    siteLogo: '',
    siteIcon: '',
    polresLogo: '',
    polresLogo2: '',
    runningText: '',
    
    // System Settings
    maintenanceMode: false,
    allowRegistration: true,
    emailVerification: true,
    sessionTimeout: 30,
    
    // Email Settings
    smtpHost: '',
    smtpPort: 587,
    smtpUser: '',
    smtpPassword: '',
    emailFrom: '',
    emailFromName: '',
    
    // SEO Settings
    metaTitle: '',
    metaDescription: '',
    metaKeywords: '',
    ogImage: '',
    
    // Contact Settings
    contactEmail: '',
    contactPhone: '',
    contactWhatsApp: '',
    address: '',
    workingHours: '',
    
    // Hero Section
    heroTitle: 'Sistem Pelayanan Digital',
    heroSubtitle: 'Polres Wonosobo',
    heroDescription: 'Layanan pengajuan dokumen kepolisian secara online yang mudah, cepat, dan terpercaya',
    heroBackgroundImage: '/hero-bg.jpg',
    heroButtonText: 'Lihat Layanan',
    heroButtonLink: '#layanan',
    heroSecondaryButtonText: 'Lacak Pengajuan',
    heroSecondaryButtonLink: '/lacak',
    
    // Kapolres Profile Settings
    kapolresName: 'AKBP. Dr. Budi Purnama, S.I.K., M.H.',
    kapolresNRP: '87050168',
    kapolresPangkat: 'AKBP',
    kapolresSignature: '',
    
    // Format Penomoran per Kategori
    skckNumberFormat: 'SKCK-{YYYY}{MM}{DD}-{seq:4}',
    spktNumberFormat: 'SPKT-{YYYY}{MM}{DD}-{seq:4}',
    lalinNumberFormat: 'LL-{YYYY}{MM}{DD}-{seq:4}',
    skckSequence: 1,
    spktSequence: 1,
    lalinSequence: 1,
    
    // Legacy defaults
    language: 'id',
    emailNotifications: true,
    smsNotifications: false,
    autoAssignment: false,
    maxFileSize: 50,
    allowedFileTypes: ['pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx'],
    passwordMinLength: 8,
    requireEmailVerification: true,
    siteLogo: '',
    siteIcon: '',
    polresLogo: ''
  })

  useEffect(() => {
    // Check authentication
    const token = localStorage.getItem('adminToken')
    const userData = localStorage.getItem('adminUser')
    
    if (!token || !userData) {
      router.push('/admin/login')
      return
    }

    try {
      setUser(JSON.parse(userData))
    } catch (error) {
      router.push('/admin/login')
      return
    }

    fetchSettings()
  }, [router])

  const fetchSettings = async () => {
    try {
      const token = localStorage.getItem('adminToken')
      const response = await fetch('/api/admin/settings', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })

      if (response.ok) {
        const data = await response.json()
        if (data.settings) {
          // Map database fields to new interface structure
          const mappedSettings = {
            ...data.settings,
            // Map brand settings - now using same field names
            siteLogo: data.settings.siteLogo || '',
            siteIcon: data.settings.siteIcon || '',
            polresLogo: data.settings.polresLogo || '',
            polresLogo2: data.settings.polresLogo2 || '',
            runningText: data.settings.runningText || '',
            // Map legacy fields for compatibility
            allowRegistration: data.settings.allowRegistration ?? true,
            emailVerification: data.settings.requireEmailVerification ?? true,
            dateFormat: data.settings.dateFormat || 'DD/MM/YYYY',
            timeFormat: data.settings.timeFormat || '24h',
            siteUrl: data.settings.siteUrl || '',
            smtpHost: data.settings.smtpHost || '',
            smtpPort: data.settings.smtpPort || 587,
            smtpUser: data.settings.smtpUser || '',
            smtpPassword: data.settings.smtpPassword || '',
            emailFrom: data.settings.emailFrom || '',
            emailFromName: data.settings.emailFromName || '',
            metaTitle: data.settings.metaTitle || '',
            metaDescription: data.settings.metaDescription || '',
            metaKeywords: data.settings.metaKeywords || '',
            ogImage: data.settings.ogImage || '',
            // Kapolres settings
            kapolresName: data.settings.kapolresName || 'AKBP. Dr. Budi Purnama, S.I.K., M.H.',
            kapolresNRP: data.settings.kapolresNRP || '87050168',
            kapolresPangkat: data.settings.kapolresPangkat || 'AKBP',
            kapolresSignature: data.settings.kapolresSignature || '',
            // Format penomoran per kategori
            skckNumberFormat: data.settings.skckNumberFormat || 'SKCK-{YYYY}{MM}{DD}-{seq:4}',
            spktNumberFormat: data.settings.spktNumberFormat || 'SPKT-{YYYY}{MM}{DD}-{seq:4}',
            lalinNumberFormat: data.settings.lalinNumberFormat || 'LL-{YYYY}{MM}{DD}-{seq:4}',
            skckSequence: data.settings.skckSequence || 1,
            spktSequence: data.settings.spktSequence || 1,
            lalinSequence: data.settings.lalinSequence || 1
          }
          setSettings(mappedSettings)
        }
      } else if (response.status === 401) {
        localStorage.removeItem('adminToken')
        localStorage.removeItem('adminUser')
        router.push('/admin/login')
      } else {
        setMessage('Gagal memuat pengaturan')
        setMessageType('error')
      }
    } catch (error) {
      console.error('Error fetching settings:', error)
      setMessage('Terjadi kesalahan saat memuat pengaturan')
      setMessageType('error')
    } finally {
      setLoading(false)
    }
  }

  const handleSave = async (formData: SystemSettings) => {
    startLoading('Menyimpan pengaturan...')
    
    try {
      const token = localStorage.getItem('adminToken')
      
      // Map new interface fields to database schema
      const payload = {
        ...formData,
        // Map brand settings - now using same field names
        siteLogo: formData.siteLogo,
        siteIcon: formData.siteIcon,
        polresLogo: formData.polresLogo,
        polresLogo2: formData.polresLogo2,
        runningText: formData.runningText,
        // Map new fields to legacy fields for compatibility
        requireEmailVerification: formData.emailVerification,
        language: 'id', // Always use Indonesian
        // Ensure all required legacy fields are included
        emailNotifications: formData.emailNotifications ?? true,
        smsNotifications: formData.smsNotifications ?? false,
        autoAssignment: formData.autoAssignment ?? false,
        maxFileSize: formData.maxFileSize ?? 5,
        allowedFileTypes: formData.allowedFileTypes ?? ['pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx'],
        passwordMinLength: formData.passwordMinLength ?? 8,
      }
      
      const response = await fetch('/api/admin/settings', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(payload)
      })

      if (response.ok) {
        const data = await response.json()
        setMessage(data.message || 'Pengaturan berhasil disimpan!')
        setMessageType('success')
        setSettings(formData)
        // Refresh settings to get the latest data
        fetchSettings()
      } else {
        const errorData = await response.json()
        setMessage(errorData.error || 'Gagal menyimpan pengaturan')
        setMessageType('error')
      }
    } catch (error) {
      console.error('Error saving settings:', error)
      setMessage('Terjadi kesalahan jaringan')
      setMessageType('error')
    } finally {
      stopLoading()
      // Clear message after 3 seconds
      setTimeout(() => setMessage(''), 3000)
    }
  }

  if (loading) {
    return (
      <AdminSidebar user={user}>
        <div className="flex items-center justify-center h-64">
          <div className="text-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-amber-600 mx-auto"></div>
            <p className="mt-2 text-gray-600">Memuat pengaturan...</p>
          </div>
        </div>
      </AdminSidebar>
    )
  }

  return (
    <AdminSidebar user={user}>
      <div className="max-w-6xl mx-auto">
        {/* Header */}
        <div className="mb-6">
          <h2 className="text-2xl font-bold text-gray-900">Pengaturan Sistem</h2>
          <p className="text-gray-600">Kelola konfigurasi dan preferensi sistem</p>
        </div>

        {/* Alert Messages */}
        {message && (
          <Alert className={`mb-6 ${messageType === 'error' ? 'border-red-200 bg-red-50' : 'border-green-200 bg-green-50'}`}>
            {messageType === 'error' ? (
              <AlertTriangle className="h-4 w-4 text-red-600" />
            ) : (
              <CheckCircle className="h-4 w-4 text-green-600" />
            )}
            <AlertDescription className={messageType === 'error' ? 'text-red-800' : 'text-green-800'}>
              {message}
            </AlertDescription>
          </Alert>
        )}

        {/* Settings Form */}
        <SystemSettingsForm
          initialData={settings}
          onSubmit={handleSave}
          isLoading={saving}
        />
      </div>
    </AdminSidebar>
  )
}