'use client'

import { useState, useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import * as z from 'zod'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Switch } from '@/components/ui/switch'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { Settings, Globe, FileText, Star, ImageIcon, Type, Shield, Upload, User, Hash, Phone, MessageCircle, AlertTriangle, CheckCircle, Car, FileCheck, Clock, MapPin, Mail, Calendar, Users, HelpCircle, ThumbsUp, Info, Zap, Bell, Home, Search, Menu, X, ChevronRight, ArrowRight, Play, Pause, Volume2, Wifi, Battery, Signal, Settings as SettingsIcon } from 'lucide-react'
import { ImageUpload } from '@/components/ImageUpload'

const systemSettingsSchema = z.object({
  // General Settings
  siteName: z.string().min(1, 'Site name is required'),
  siteUrl: z.string().url('Invalid URL').optional().or(z.literal('')),
  siteDescription: z.string().optional(),
  timezone: z.string().default('UTC'),
  dateFormat: z.string().default('YYYY-MM-DD'),
  timeFormat: z.string().default('24h'),
  
  // Brand Settings
  siteLogo: z.string().optional(),
  siteIcon: z.string().optional(),
  polresLogo: z.string().optional(),
  polresLogo2: z.string().optional(),
  runningText: z.string().optional(),
  
  // System Settings
  maintenanceMode: z.boolean().default(false),
  allowRegistration: z.boolean().default(true),
  emailVerification: z.boolean().default(true),
  sessionTimeout: z.number().min(5).max(1440).default(30),
  
  // Email Settings
  smtpHost: z.string().optional(),
  smtpPort: z.number().optional(),
  smtpUser: z.string().optional(),
  smtpPassword: z.string().optional(),
  emailFrom: z.string().email().optional().or(z.literal('')),
  emailFromName: z.string().optional(),
  
  // SEO Settings
  metaTitle: z.string().optional(),
  metaDescription: z.string().optional(),
  metaKeywords: z.string().optional(),
  ogImage: z.string().optional(),
  
  // Contact Settings
  contactEmail: z.string().email().optional().or(z.literal('')),
  contactPhone: z.string().optional(),
  contactWhatsApp: z.string().optional(),
  address: z.string().optional(),
  workingHours: z.string().optional(),
  
  // Hero Section
  heroTitle: z.string().optional(),
  heroSubtitle: z.string().optional(),
  heroDescription: z.string().optional(),
  heroBackgroundImage: z.string().optional(),
  heroButtonText: z.string().optional(),
  heroButtonLink: z.string().optional(),
  heroSecondaryButtonText: z.string().optional(),
  heroSecondaryButtonLink: z.string().optional(),
  
  // Kapolres Profile Settings
  kapolresName: z.string().optional(),
  kapolresNRP: z.string().optional(),
  kapolresPangkat: z.string().optional(),
  kapolresSignature: z.string().optional(),
  
  // Format Penomoran per Kategori
  skckNumberFormat: z.string().optional(),
  spktNumberFormat: z.string().optional(),
  lalinNumberFormat: z.string().optional(),
  skckSequence: z.number().optional(),
  spktSequence: z.number().optional(),
  lalinSequence: z.number().optional(),
})

type SystemSettingsValues = z.infer<typeof systemSettingsSchema>

interface SystemSettingsFormProps {
  initialData?: Partial<SystemSettingsValues>
  onSubmit: (data: SystemSettingsValues) => Promise<void>
  isLoading?: boolean
}

export function SystemSettingsForm({ initialData, onSubmit, isLoading = false }: SystemSettingsFormProps) {
  const [activeTab, setActiveTab] = useState('general')
  const [uploadedLogo, setUploadedLogo] = useState<string | null>(null)
  const [uploadedIcon, setUploadedIcon] = useState<string | null>(null)

  const form = useForm<SystemSettingsValues>({
    resolver: zodResolver(systemSettingsSchema),
    defaultValues: {
      siteName: '',
      siteUrl: '',
      siteDescription: '',
      timezone: 'UTC',
      dateFormat: 'YYYY-MM-DD',
      timeFormat: '24h',
      siteLogo: '',
      siteIcon: '',
      polresLogo: '',
      polresLogo2: '',
      runningText: '',
      maintenanceMode: false,
      allowRegistration: true,
      emailVerification: true,
      sessionTimeout: 30,
      smtpHost: '',
      smtpPort: 587,
      smtpUser: '',
      smtpPassword: '',
      emailFrom: '',
      emailFromName: '',
      metaTitle: '',
      metaDescription: '',
      metaKeywords: '',
      ogImage: '',
      contactEmail: '',
      contactPhone: '',
      contactWhatsApp: '',
      address: '',
      workingHours: '',
      heroTitle: '',
      heroSubtitle: '',
      heroDescription: '',
      heroBackgroundImage: '',
      heroButtonText: '',
      heroButtonLink: '',
      heroSecondaryButtonText: '',
      heroSecondaryButtonLink: '',
      // 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,
      ...initialData,
    },
  })

  useEffect(() => {
    if (initialData) {
      form.reset(initialData)
    }
  }, [initialData, form])

  const handleSubmit = async (values: SystemSettingsValues) => {
    await onSubmit(values)
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6">
        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList className="grid w-full grid-cols-6">
            <TabsTrigger value="general" className="flex items-center gap-2">
              <Settings className="h-4 w-4" />
              General
            </TabsTrigger>
            <TabsTrigger value="brand" className="flex items-center gap-2">
              <Star className="h-4 w-4" />
              Brand
            </TabsTrigger>
            <TabsTrigger value="hero" className="flex items-center gap-2">
              <ImageIcon className="h-4 w-4" />
              Hero
            </TabsTrigger>
            <TabsTrigger value="kapolres" className="flex items-center gap-2">
              <User className="h-4 w-4" />
              Kapolres
            </TabsTrigger>
            <TabsTrigger value="numbering" className="flex items-center gap-2">
              <Type className="h-4 w-4" />
              Numbering
            </TabsTrigger>
            <TabsTrigger value="seo" className="flex items-center gap-2">
              <Globe className="h-4 w-4" />
              SEO & Contact
            </TabsTrigger>
          </TabsList>

          <TabsContent value="general" className="space-y-6">
            {/* General Settings */}
            <Card>
              <CardHeader>
                <CardTitle>General Settings</CardTitle>
                <CardDescription>
                  Basic configuration for your website
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <FormField
                    control={form.control}
                    name="siteName"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Site Name</FormLabel>
                        <FormControl>
                          <Input placeholder="My Site" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="siteUrl"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Site URL</FormLabel>
                        <FormControl>
                          <Input placeholder="https://example.com" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="timezone"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Timezone</FormLabel>
                        <Select onValueChange={field.onChange} defaultValue={field.value}>
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue placeholder="Select timezone" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            <SelectItem value="UTC">UTC</SelectItem>
                            <SelectItem value="Asia/Jakarta">Asia/Jakarta</SelectItem>
                            <SelectItem value="Asia/Shanghai">Asia/Shanghai</SelectItem>
                            <SelectItem value="America/New_York">America/New_York</SelectItem>
                            <SelectItem value="Europe/London">Europe/London</SelectItem>
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="dateFormat"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Date Format</FormLabel>
                        <FormControl>
                          <Input placeholder="YYYY-MM-DD" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="timeFormat"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Time Format</FormLabel>
                        <Select onValueChange={field.onChange} defaultValue={field.value}>
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue placeholder="Select format" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            <SelectItem value="24h">24-hour</SelectItem>
                            <SelectItem value="12h">12-hour</SelectItem>
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <FormField
                  control={form.control}
                  name="siteDescription"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Site Description</FormLabel>
                      <FormControl>
                        <Textarea 
                          placeholder="Describe your website" 
                          className="resize-none" 
                          {...field} 
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </CardContent>
            </Card>

            {/* System Settings */}
            <Card>
              <CardHeader>
                <CardTitle>System Configuration</CardTitle>
                <CardDescription>
                  Configure system-wide settings and behavior
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <FormField
                    control={form.control}
                    name="maintenanceMode"
                    render={({ field }) => (
                      <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                        <div className="space-y-0.5">
                          <FormLabel className="text-base">Maintenance Mode</FormLabel>
                          <FormDescription>
                            Put the site in maintenance mode
                          </FormDescription>
                        </div>
                        <FormControl>
                          <Switch
                            checked={field.value}
                            onCheckedChange={field.onChange}
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="allowRegistration"
                    render={({ field }) => (
                      <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                        <div className="space-y-0.5">
                          <FormLabel className="text-base">Allow Registration</FormLabel>
                          <FormDescription>
                            Allow new users to register
                          </FormDescription>
                        </div>
                        <FormControl>
                          <Switch
                            checked={field.value}
                            onCheckedChange={field.onChange}
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="emailVerification"
                    render={({ field }) => (
                      <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                        <div className="space-y-0.5">
                          <FormLabel className="text-base">Email Verification</FormLabel>
                          <FormDescription>
                            Require email verification for new accounts
                          </FormDescription>
                        </div>
                        <FormControl>
                          <Switch
                            checked={field.value}
                            onCheckedChange={field.onChange}
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="sessionTimeout"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Session Timeout (minutes)</FormLabel>
                        <FormControl>
                          <Input
                            type="number"
                            placeholder="30"
                            {...field}
                            onChange={(e) => field.onChange(parseInt(e.target.value) || 30)}
                          />
                        </FormControl>
                        <FormDescription>
                          User session timeout in minutes
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </CardContent>
            </Card>

            {/* Email Settings */}
            <Card>
              <CardHeader>
                <CardTitle>Email Configuration</CardTitle>
                <CardDescription>
                  Configure SMTP settings for email notifications
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <FormField
                    control={form.control}
                    name="smtpHost"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>SMTP Host</FormLabel>
                        <FormControl>
                          <Input placeholder="smtp.gmail.com" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="smtpPort"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>SMTP Port</FormLabel>
                        <FormControl>
                          <Input
                            type="number"
                            placeholder="587"
                            {...field}
                            onChange={(e) => field.onChange(parseInt(e.target.value) || 587)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="smtpUser"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>SMTP Username</FormLabel>
                        <FormControl>
                          <Input placeholder="email@example.com" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="smtpPassword"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>SMTP Password</FormLabel>
                        <FormControl>
                          <Input type="password" placeholder="••••••••" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="emailFrom"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>From Email</FormLabel>
                        <FormControl>
                          <Input placeholder="noreply@example.com" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="emailFromName"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>From Name</FormLabel>
                        <FormControl>
                          <Input placeholder="My Site" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="brand" className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>Brand Settings</CardTitle>
                <CardDescription>
                  Customize your website's visual identity
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-8">
                {/* Website Logo */}
                <div className="space-y-3">
                  <FormField
                    control={form.control}
                    name="siteLogo"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Website Logo</FormLabel>
                        <FormControl>
                          <ImageUpload
                            value={field.value}
                            onChange={(url) => {
                              field.onChange(url)
                              setUploadedLogo(url)
                            }}
                            onRemove={() => {
                              field.onChange('')
                              setUploadedLogo(null)
                            }}
                            type="logo"
                            accept="image/*"
                            maxSize={5}
                            previewSize="medium"
                            compact={true}
                          />
                        </FormControl>
                        <FormDescription>
                          Main website logo displayed in header. Recommended size: 200x60px, max 50MB.
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                {/* Favicon */}
                <div className="space-y-3">
                  <FormField
                    control={form.control}
                    name="siteIcon"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Favicon</FormLabel>
                        <FormControl>
                          <ImageUpload
                            value={field.value}
                            onChange={(url) => {
                              field.onChange(url)
                              setUploadedIcon(url)
                            }}
                            onRemove={() => {
                              field.onChange('')
                              setUploadedIcon(null)
                            }}
                            type="icon"
                            accept="image/x-icon,image/png"
                            maxSize={2}
                            previewSize="small"
                            compact={true}
                          />
                        </FormControl>
                        <FormDescription>
                          Browser tab icon. Recommended size: 32x32px or 16x16px, max 2MB.
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                {/* Polres Logo */}
                <div className="space-y-3">
                  <FormField
                    control={form.control}
                    name="polresLogo"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Polres Branding Logo</FormLabel>
                        <FormControl>
                          <ImageUpload
                            value={field.value}
                            onChange={field.onChange}
                            onRemove={() => field.onChange('')}
                            type="polres"
                            accept="image/*"
                            maxSize={5}
                            previewSize="medium"
                            compact={true}
                          />
                        </FormControl>
                        <FormDescription>
                          Official Polres branding logo for official documents. Recommended size: 200x200px, max 50MB.
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </CardContent>
            </Card>

            {/* Additional Polres Logo */}
            <Card>
              <CardHeader>
                <CardTitle>Additional POLRI Logo</CardTitle>
                <CardDescription>
                  Additional POLRI logo for specific sections or alternative branding
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-8">
                <div className="space-y-3">
                  <FormField
                    control={form.control}
                    name="polresLogo2"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Additional POLRI Logo</FormLabel>
                        <FormControl>
                          <ImageUpload
                            value={field.value}
                            onChange={field.onChange}
                            onRemove={() => field.onChange('')}
                            type="polres2"
                            accept="image/*"
                            maxSize={5}
                            previewSize="medium"
                            compact={true}
                          />
                        </FormControl>
                        <FormDescription>
                          Additional POLRI logo for specific sections. Recommended size: 200x200px, max 50MB.
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </CardContent>
            </Card>

            {/* Running Text Settings */}
            <Card>
              <CardHeader>
                <CardTitle>Running Text Settings</CardTitle>
                <CardDescription>
                  Configure the running text displayed on the landing page
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Icon Picker */}
                <div className="space-y-3">
                  <FormLabel className="text-sm font-medium">Quick Icons (Click to add)</FormLabel>
                  <div className="flex flex-wrap gap-2 p-3 bg-gray-50 rounded-lg border">
                    <IconInsertButton icon="🚨" label="Police" insertText={form.getValues('runningText') || ''} fieldName="runningText" form={form} />
                    <IconInsertButton icon="📞" label="Phone" insertText={form.getValues('runningText') || ''} fieldName="runningText" form={form} />
                    <IconInsertButton icon="💬" label="Chat" insertText={form.getValues('runningText') || ''} fieldName="runningText" form={form} />
                    <IconInsertButton icon="📋" label="Document" insertText={form.getValues('runningText') || ''} fieldName="runningText" form={form} />
                    <IconInsertButton icon="🛡️" label="Shield" insertText={form.getValues('runningText') || ''} fieldName="runningText" form={form} />
                    <IconInsertButton icon="🚗" label="Car" insertText={form.getValues('runningText') || ''} fieldName="runningText" form={form} />
                    <IconInsertButton icon="👮" label="Officer" insertText={form.getValues('runningText') || ''} fieldName="runningText" form={form} />
                    <IconInsertButton icon="🏢" label="Building" insertText={form.getValues('runningText') || ''} fieldName="runningText" form={form} />
                    <IconInsertButton icon="📧" label="Email" insertText={form.getValues('runningText') || ''} fieldName="runningText" form={form} />
                    <IconInsertButton icon="🌐" label="Website" insertText={form.getValues('runningText') || ''} fieldName="runningText" form={form} />
                    <IconInsertButton icon="⏰" label="Time" insertText={form.getValues('runningText') || ''} fieldName="runningText" form={form} />
                    <IconInsertButton icon="📍" label="Location" insertText={form.getValues('runningText') || ''} fieldName="runningText" form={form} />
                    <IconInsertButton icon="✅" label="Check" insertText={form.getValues('runningText') || ''} fieldName="runningText" form={form} />
                    <IconInsertButton icon="⚡" label="Fast" insertText={form.getValues('runningText') || ''} fieldName="runningText" form={form} />
                    <IconInsertButton icon="🔔" label="Bell" insertText={form.getValues('runningText') || ''} fieldName="runningText" form={form} />
                    <IconInsertButton icon="👍" label="Thumbs Up" insertText={form.getValues('runningText') || ''} fieldName="runningText" form={form} />
                  </div>
                  <FormDescription className="text-xs">
                    Click any icon to insert it at the end of your running text. You can also type emojis directly.
                  </FormDescription>
                </div>

                <Separator />

                <div className="space-y-3">
                  <FormField
                    control={form.control}
                    name="runningText"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Running Text</FormLabel>
                        <FormControl>
                          <Textarea
                            placeholder="🚨 SELAMAT DATANG DI PORTAL RESMI POLRES WONOSOBO | 📞 LAYANAN DARURAT: 110 | 💬 LIVE CHAT 24/7 | 📋 SKCK ONLINE | 🛡️ SPKT TERPADU | 🚗 SIM & LALU LINTAS |"
                            className="resize-none"
                            rows={4}
                            {...field}
                          />
                        </FormControl>
                        <FormDescription>
                          Text that will scroll across the top of the landing page. Use | as separator between different messages.
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                {/* Template Examples */}
                <div className="space-y-2">
                  <FormLabel className="text-sm font-medium">Template Examples</FormLabel>
                  <div className="space-y-2">
                    <TemplateButton 
                      template="🚨 SELAMAT DATANG DI PORTAL RESMI POLRES WONOSOBO | 📞 LAYANAN DARURAT: 110 | 💬 LIVE CHAT 24/7"
                      label="Basic Welcome"
                      form={form}
                      fieldName="runningText"
                    />
                    <TemplateButton 
                      template="📋 SKCK ONLINE | 🛡️ SPKT TERPADU | 🚗 SIM & LALU LINTAS | 👮 LAYANAN KEPOLISIAN | 🏢 KANTOR POLRES WONOSOBO"
                      label="Services Only"
                      form={form}
                      fieldName="runningText"
                    />
                    <TemplateButton 
                      template="⏰ JAM KERJA: SENIN-JUMAT 08:00-16:00 | 📞 HUBUNGI KAMI: 110 | 📍 ALAMAT: JL. BHAYANGKARA NO. 18 WONOSOBO"
                      label="Contact Info"
                      form={form}
                      fieldName="runningText"
                    />
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="hero" className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>Hero Section</CardTitle>
                <CardDescription>
                  Customize the main hero section on your landing page
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <FormField
                    control={form.control}
                    name="heroTitle"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Hero Title</FormLabel>
                        <FormControl>
                          <Input placeholder="Welcome to Our Site" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="heroSubtitle"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Hero Subtitle</FormLabel>
                        <FormControl>
                          <Input placeholder="Amazing services for you" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <FormField
                  control={form.control}
                  name="heroDescription"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Hero Description</FormLabel>
                      <FormControl>
                        <Textarea 
                          placeholder="Describe what makes your service special" 
                          className="resize-none" 
                          {...field} 
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="heroBackgroundImage"
                  render={({ field }) => (
                    <FormItem className="mb-6">
                      <FormLabel>Hero Background Image</FormLabel>
                      <FormControl>
                        <ImageUpload
                          value={field.value}
                          onChange={field.onChange}
                          onRemove={() => field.onChange('')}
                          accept="image/*"
                          maxSize={20}
                          previewSize="large"
                        />
                      </FormControl>
                      <FormDescription>
                        Upload a background image for the hero section. Recommended size: 1920x1080px, max 20MB.
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <Separator />
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <FormField
                    control={form.control}
                    name="heroButtonText"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Primary Button Text</FormLabel>
                        <FormControl>
                          <Input placeholder="Get Started" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="heroButtonLink"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Primary Button Link</FormLabel>
                        <FormControl>
                          <Input placeholder="/services" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="heroSecondaryButtonText"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Secondary Button Text</FormLabel>
                        <FormControl>
                          <Input placeholder="Learn More" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="heroSecondaryButtonLink"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Secondary Button Link</FormLabel>
                        <FormControl>
                          <Input placeholder="/about" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Kapolres Profile Settings */}
          <TabsContent value="kapolres" className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <User className="h-5 w-5" />
                  Profil Kapolres
                </CardTitle>
                <CardDescription>
                  Pengaturan profil Kapolres untuk tanda tangan digital dan dokumen
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <FormField
                    control={form.control}
                    name="kapolresName"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Nama Lengkap Kapolres</FormLabel>
                        <FormControl>
                          <Input placeholder="AKBP. Dr. Budi Purnama, S.I.K., M.H." {...field} />
                        </FormControl>
                        <FormDescription>
                          Nama lengkap dengan gelar akademik dan kepolisian
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="kapolresNRP"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>NRP</FormLabel>
                        <FormControl>
                          <Input placeholder="87050168" {...field} />
                        </FormControl>
                        <FormDescription>
                          Nomor Register Polri
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="kapolresPangkat"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Pangkat</FormLabel>
                        <FormControl>
                          <Input placeholder="AKBP" {...field} />
                        </FormControl>
                        <FormDescription>
                          Pangkat terakhir Kapolres
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <FormField
                  control={form.control}
                  name="kapolresSignature"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Tanda Tangan Digital</FormLabel>
                      <FormControl>
                        <ImageUpload
                          value={field.value}
                          onChange={field.onChange}
                          onRemove={() => field.onChange('')}
                          accept="image/*"
                          maxSize={2}
                          previewSize="small"
                          compact={true}
                        />
                      </FormControl>
                      <FormDescription>
                        Upload tanda tangan Kapolres (format: PNG, JPG, maksimal 2MB)
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </CardContent>
            </Card>
          </TabsContent>

          {/* Request Number Settings */}
          <TabsContent value="numbering" className="space-y-6">
            {/* Format Penomoran Settings */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Type className="h-5 w-5" />
                  Format Penomoran Pengajuan
                </CardTitle>
                <CardDescription>
                  Atur format penomoran untuk setiap kategori layanan. Gunakan placeholder: {'{YYYY}'}, {'{MM}'}, {'{DD}'}, {'{seq:N}'}
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* SKCK Numbering */}
                <div className="space-y-4">
                  <h4 className="text-lg font-semibold text-blue-600">Format SKCK</h4>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <FormField
                      control={form.control}
                      name="skckNumberFormat"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Format Nomor SKCK</FormLabel>
                          <FormControl>
                            <Input 
                              placeholder="contoh: SKCK-{'{YYYY}{MM}{DD}'}-{'{seq:4}'}" 
                              {...field} 
                            />
                          </FormControl>
                          <FormDescription>
                            Format untuk nomor pengajuan SKCK
                          </FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="skckSequence"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Nomor Urut Saat Ini</FormLabel>
                          <FormControl>
                            <Input 
                              type="number" 
                              placeholder="1" 
                              {...field}
                              onChange={(e) => field.onChange(parseInt(e.target.value) || 0)}
                            />
                          </FormControl>
                          <FormDescription>
                            Nomor urut terakhir yang digunakan
                          </FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                </div>

                {/* SPKT Numbering */}
                <div className="space-y-4">
                  <h4 className="text-lg font-semibold text-green-600">Format SPKT</h4>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <FormField
                      control={form.control}
                      name="spktNumberFormat"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Format Nomor SPKT</FormLabel>
                          <FormControl>
                            <Input 
                              placeholder="contoh: SPKT-{'{YYYY}{MM}{DD}'}-{'{seq:4}'}" 
                              {...field} 
                            />
                          </FormControl>
                          <FormDescription>
                            Format untuk nomor pengajuan SPKT
                          </FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="spktSequence"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Nomor Urut Saat Ini</FormLabel>
                          <FormControl>
                            <Input 
                              type="number" 
                              placeholder="1" 
                              {...field}
                              onChange={(e) => field.onChange(parseInt(e.target.value) || 0)}
                            />
                          </FormControl>
                          <FormDescription>
                            Nomor urut terakhir yang digunakan
                          </FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                </div>

                {/* Lalu Lintas Numbering */}
                <div className="space-y-4">
                  <h4 className="text-lg font-semibold text-orange-600">Format Lalu Lintas</h4>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <FormField
                      control={form.control}
                      name="lalinNumberFormat"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Format Nomor Lalu Lintas</FormLabel>
                          <FormControl>
                            <Input 
                              placeholder="contoh: LL-{'{YYYY}{MM}{DD}'}-{'{seq:4}'}" 
                              {...field} 
                            />
                          </FormControl>
                          <FormDescription>
                            Format untuk nomor pengajuan Lalu Lintas
                          </FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="lalinSequence"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Nomor Urut Saat Ini</FormLabel>
                          <FormControl>
                            <Input 
                              type="number" 
                              placeholder="1" 
                              {...field}
                              onChange={(e) => field.onChange(parseInt(e.target.value) || 0)}
                            />
                          </FormControl>
                          <FormDescription>
                            Nomor urut terakhir yang digunakan
                          </FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                </div>

                {/* Guide */}
                <Card className="bg-blue-50 border-blue-200">
                  <CardContent className="pt-6">
                    <h5 className="font-semibold text-blue-800 mb-3">📖 Panduan Placeholder</h5>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                      <div>
                        <p className="font-medium text-blue-700">Tanggal:</p>
                        <ul className="text-blue-600 space-y-1">
                          <li>• <code>{'{YYYY}'}</code> - Tahun 4 digit (2024)</li>
                          <li>• <code>{'{MM}'}</code> - Bulan 2 digit (01-12)</li>
                          <li>• <code>{'{DD}'}</code> - Tanggal 2 digit (01-31)</li>
                        </ul>
                      </div>
                      <div>
                        <p className="font-medium text-blue-700">Nomor Urut:</p>
                        <ul className="text-blue-600 space-y-1">
                          <li>• <code>{'{seq}'}</code> - Nomor urut default (4 digit)</li>
                          <li>• <code>{'{seq:3}'}</code> - Nomor urut 3 digit (001)</li>
                          <li>• <code>{'{seq:6}'}</code> - Nomor urut 6 digit (000001)</li>
                        </ul>
                      </div>
                    </div>
                    <div className="mt-4 p-3 bg-white rounded border border-blue-200">
                      <p className="font-medium text-blue-800 mb-2">💡 Contoh Format:</p>
                      <ul className="text-sm text-blue-700 space-y-1">
                        <li>• <code>SKCK-{'{YYYY}{MM}{DD}'}-{'{seq:4}'}</code> → <code>SKCK-20241014-0001</code></li>
                        <li>• <code>SPKT/{'{YYYY}'}/{'{MM}'}/{'{seq:3}'}</code> → <code>SPKT/2024/10/001</code></li>
                        <li>• <code>LL-{'{seq:6}'}</code> → <code>LL-000001</code></li>
                      </ul>
                    </div>
                  </CardContent>
                </Card>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="seo" className="space-y-6">
            {/* SEO Settings */}
            <Card>
              <CardHeader>
                <CardTitle>SEO Settings</CardTitle>
                <CardDescription>
                  Optimize your website for search engines
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <FormField
                    control={form.control}
                    name="metaTitle"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Meta Title</FormLabel>
                        <FormControl>
                          <Input placeholder="Your Website Title" {...field} />
                        </FormControl>
                        <FormDescription>
                          Recommended length: 50-60 characters
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="ogImage"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>OG Image</FormLabel>
                        <FormControl>
                          <ImageUpload
                            value={field.value}
                            onChange={field.onChange}
                            onRemove={() => field.onChange('')}
                            accept="image/*"
                            maxSize={5}
                            previewSize="medium"
                            compact={true}
                          />
                        </FormControl>
                        <FormDescription>
                          Social media preview image (1200x630px recommended)
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <FormField
                  control={form.control}
                  name="metaDescription"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Meta Description</FormLabel>
                      <FormControl>
                        <Textarea 
                          placeholder="Brief description of your website" 
                          className="resize-none" 
                          {...field} 
                        />
                      </FormControl>
                      <FormDescription>
                        Recommended length: 150-160 characters
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="metaKeywords"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Meta Keywords</FormLabel>
                      <FormControl>
                        <Input placeholder="keyword1, keyword2, keyword3" {...field} />
                      </FormControl>
                      <FormDescription>
                        Comma-separated list of keywords
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </CardContent>
            </Card>

            {/* Contact Settings */}
            <Card>
              <CardHeader>
                <CardTitle>Contact Information</CardTitle>
                <CardDescription>
                  Display contact details on your website
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <FormField
                    control={form.control}
                    name="contactEmail"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Contact Email</FormLabel>
                        <FormControl>
                          <Input type="email" placeholder="contact@example.com" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="contactPhone"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Contact Phone</FormLabel>
                        <FormControl>
                          <Input placeholder="+62 123-456-789" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="contactWhatsApp"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>WhatsApp Number</FormLabel>
                        <FormControl>
                          <Input placeholder="+62 812-3456-7890" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="workingHours"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Working Hours</FormLabel>
                        <FormControl>
                          <Input placeholder="Mon - Fri: 09:00 - 17:00" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <FormField
                  control={form.control}
                  name="address"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Address</FormLabel>
                      <FormControl>
                        <Textarea 
                          placeholder="Enter your address" 
                          className="resize-none" 
                          {...field} 
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>

        {/* Form Actions */}
        <div className="flex justify-end space-x-4">
          <Button
            type="button"
            variant="outline"
            onClick={() => form.reset()}
            disabled={isLoading}
          >
            Reset Changes
          </Button>
          <Button
            type="submit"
            disabled={isLoading}
          >
            {isLoading ? 'Saving...' : 'Save Changes'}
          </Button>
        </div>
      </form>
    </Form>
  )
}

// Helper Components for Icon Insertion
interface IconInsertButtonProps {
  icon: string;
  label: string;
  insertText: string;
  fieldName: string;
  form: any;
}

function IconInsertButton({ icon, label, insertText, fieldName, form }: IconInsertButtonProps) {
  const handleInsert = () => {
    const currentText = form.getValues(fieldName) || '';
    const newText = currentText + ' ' + icon;
    form.setValue(fieldName, newText);
  };

  return (
    <button
      type="button"
      onClick={handleInsert}
      className="flex items-center gap-1 px-2 py-1 text-sm bg-white border border-gray-200 rounded hover:bg-gray-50 transition-colors"
      title={label}
    >
      <span className="text-base">{icon}</span>
    </button>
  );
}

interface TemplateButtonProps {
  template: string;
  label: string;
  form: any;
  fieldName: string;
}

function TemplateButton({ template, label, form, fieldName }: TemplateButtonProps) {
  const handleApplyTemplate = () => {
    form.setValue(fieldName, template);
  };

  return (
    <div className="flex items-center gap-2 p-2 bg-gray-50 rounded-lg border">
      <span className="text-xs text-gray-600 flex-1 truncate">{template}</span>
      <Button
        type="button"
        variant="outline"
        size="sm"
        onClick={handleApplyTemplate}
        className="text-xs h-6"
      >
        {label}
      </Button>
    </div>
  );
}