"use client"

import { useState, useEffect } from "react"
import { motion } from "framer-motion"
import useTranslate from "@/hooks/useTranslate"
import { router, usePage } from "@inertiajs/react"
import PremiumSettingsCard, { SettingsRow, ToggleCard } from "@/Components/UI/PremiumSettingsCard"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/UI/Select"

export default function BackupSettings({ settings: siteSettings, backups: initialBackups, backupPath }) {
  const t = useTranslate()
  const [isSubmitting, setIsSubmitting] = useState(false)
  
  const [settings, setSettings] = useState({
    autoBackup: siteSettings?.auto_backup_enabled === '1',
    backupFrequency: siteSettings?.backup_frequency || "daily",
    backupRetention: siteSettings?.backup_retention_days || 30,
    includeUploads: siteSettings?.backup_include_uploads === '1',
    includeDatabase: siteSettings?.backup_include_database === '1',
    includeSettings: siteSettings?.backup_include_settings === '1',
    compressionEnabled: siteSettings?.backup_compression === '1',
    encryption: siteSettings?.backup_encryption === '1',
    remoteStorage: siteSettings?.backup_remote_storage === '1',
    storageLocation: siteSettings?.backup_storage_location || "local",
    maintenanceMode: siteSettings?.maintenance_mode === '1',
    scheduledMaintenance: siteSettings?.scheduled_maintenance === '1',
    maintenanceTime: siteSettings?.maintenance_time || "02:00",
    maintenanceDay: siteSettings?.maintenance_day || "sunday",
    autoUpdates: siteSettings?.auto_updates === '1',
    cleanupFrequency: siteSettings?.cleanup_frequency || "weekly",
    logRetention: siteSettings?.log_retention_days || 90,
    cacheCleanup: siteSettings?.cache_cleanup === '1'
  })

  const [backups, setBackups] = useState(initialBackups || [])

  const handleToggle = (key, subKey = null) => {
    if (subKey) {
      setSettings(prev => ({
        ...prev,
        [key]: {
          ...prev[key],
          [subKey]: !prev[key][subKey]
        }
      }))
    } else {
      setSettings(prev => ({ ...prev, [key]: !prev[key] }))
    }
  }

  const handleInputChange = (key, value) => {
    setSettings(prev => ({ ...prev, [key]: value }))
  }

  const handleSave = () => {
    setIsSubmitting(true)
    
    const backupData = {
      auto_backup_enabled: settings.autoBackup ? '1' : '0',
      backup_frequency: settings.backupFrequency,
      backup_retention_days: settings.backupRetention,
      backup_include_uploads: settings.includeUploads ? '1' : '0',
      backup_include_database: settings.includeDatabase ? '1' : '0',
      backup_include_settings: settings.includeSettings ? '1' : '0',
      backup_compression: settings.compressionEnabled ? '1' : '0',
      backup_encryption: settings.encryption ? '1' : '0',
      backup_remote_storage: settings.remoteStorage ? '1' : '0',
      backup_storage_location: settings.storageLocation,
      maintenance_mode: settings.maintenanceMode ? '1' : '0',
      scheduled_maintenance: settings.scheduledMaintenance ? '1' : '0',
      maintenance_time: settings.maintenanceTime,
      maintenance_day: settings.maintenanceDay,
      auto_updates: settings.autoUpdates ? '1' : '0',
      cleanup_frequency: settings.cleanupFrequency,
      log_retention_days: settings.logRetention,
      cache_cleanup: settings.cacheCleanup ? '1' : '0'
    }
    
    router.post(route('user.setting.store'), backupData, {
      preserveScroll: true,
      preserveState: true,
      onFinish: () => setIsSubmitting(false),
      onError: () => setIsSubmitting(false),
    })
  }

  const createBackup = (type = "full") => {
    setIsSubmitting(true)
    router.post(route('user.setting.backup.create'), { type }, {
      preserveScroll: true,
      preserveState: true,
      onFinish: () => setIsSubmitting(false),
      onError: () => setIsSubmitting(false),
    })
  }

  const restoreBackup = (backupPath) => {
    if (confirm(t('Are you sure you want to restore this backup? This action cannot be undone and will overwrite current data.'))) {
      setIsSubmitting(true)
      router.post(route('user.setting.backup.restore'), { backup_path: backupPath }, {
        preserveScroll: true,
        preserveState: true,
        onFinish: () => setIsSubmitting(false),
        onError: () => setIsSubmitting(false),
      })
    }
  }

  const deleteBackup = (backupPath, backupId) => {
    if (confirm(t('Are you sure you want to delete this backup? This action cannot be undone.'))) {
      setIsSubmitting(true)
      router.post(route('user.setting.backup.delete'), { backup_path: backupPath }, {
        preserveScroll: true,
        preserveState: true,
        onSuccess: () => {
          // Remove from local state on success
          setBackups(prev => prev.filter(backup => backup.id !== backupId))
        },
        onFinish: () => setIsSubmitting(false),
        onError: () => setIsSubmitting(false),
      })
    }
  }

  const toggleMaintenanceMode = () => {
    setIsSubmitting(true)
    const newMode = !settings.maintenanceMode
    setSettings(prev => ({ ...prev, maintenanceMode: newMode }))
    
    router.post(route('user.setting.store'), {
      maintenance_mode: newMode ? '1' : '0'
    }, {
      preserveScroll: true,
      preserveState: true,
      onFinish: () => setIsSubmitting(false),
      onError: () => setIsSubmitting(false),
    })
  }

  const runMaintenance = () => {
    setIsSubmitting(true)
    router.post(route('user.setting.maintenance.run'), {}, {
      preserveScroll: true,
      preserveState: true,
      onFinish: () => setIsSubmitting(false),
      onError: () => setIsSubmitting(false),
    })
  }

  return (
    <PremiumSettingsCard
      title={t("Backup & Maintenance")}
      description={t("Configure backup settings and system maintenance tasks")}
      icon={
        <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
          <path d="M4 4a2 2 0 00-2 2v8a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2H4zm0 2h12v8H4V6z" />
          <path d="M6 8h8v2H6V8zM6 11h8v1H6v-1z" />
        </svg>
      }
    >
      <div className="space-y-6">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">{t("Backup & System Maintenance")}</h3>
            <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
              {t("Configure automated backups, maintenance schedules, and system cleanup tasks")}
            </p>
          </div>
          <div className="flex space-x-3">
            <motion.button
              whileHover={{ scale: 1.02 }}
              whileTap={{ scale: 0.98 }}
              onClick={runMaintenance}
              className="px-4 py-2.5 border border-gray-300 dark:border-zinc-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-zinc-800 rounded-lg font-medium transition-colors"
              disabled={isSubmitting}
            >
              {t("Run Maintenance")}
            </motion.button>
            <motion.button
              whileHover={{ scale: 1.02 }}
              whileTap={{ scale: 0.98 }}
              onClick={handleSave}
              className="bg-gradient-to-r from-primary to-secondary hover:from-primary/90 hover:to-secondary/90 text-white px-6 py-2.5 rounded-lg font-medium shadow-sm transition-all duration-200 flex items-center gap-2"
              disabled={isSubmitting}
            >
              {!isSubmitting && (
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                </svg>
              )}
              {isSubmitting ? t("Saving...") : t("Save Settings")}
            </motion.button>
          </div>
        </div>

        {/* Backup Configuration */}
      <PremiumSettingsCard 
        title={t("Backup Configuration")}
        description={t("Configure automatic backup settings")}
        variant="default"
      >
        <div className="space-y-4">
          <ToggleCard
            title={t("Automatic Backups")}
            description={t("Enable scheduled automatic backups")}
            enabled={settings.autoBackup}
            onToggle={() => handleToggle('autoBackup')}
          />

          {settings.autoBackup && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: "auto" }}
              className="space-y-4 pl-6 border-l-2 border-blue-100 dark:border-blue-900"
            >
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t("Backup Frequency")}
                  </label>
                  <Select value={settings.backupFrequency} onValueChange={(value) => handleInputChange('backupFrequency', value)}>
                    <SelectTrigger className="w-full h-9 px-3 py-2 bg-gray-50 dark:bg-zinc-800 border-gray-200 dark:border-zinc-800 text-sm">
                      <SelectValue placeholder={t("Select frequency")} />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="hourly">{t("Hourly")}</SelectItem>
                      <SelectItem value="daily">{t("Daily")}</SelectItem>
                      <SelectItem value="weekly">{t("Weekly")}</SelectItem>
                      <SelectItem value="monthly">{t("Monthly")}</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t("Retention Period (days)")}
                  </label>
                  <input
                    type="number"
                    value={settings.backupRetention}
                    onChange={(e) => handleInputChange('backupRetention', parseInt(e.target.value))}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
                    min="1"
                    max="365"
                  />
                </div>
              </div>

              <div className="space-y-3">
                <h4 className="font-medium text-gray-900 dark:text-white">{t("Backup Content")}</h4>
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                  <ToggleCard
                    title={t("Database")}
                    description={t("Include database data")}
                    enabled={settings.includeDatabase}
                    onToggle={() => handleToggle('includeDatabase')}
                  />
                  <ToggleCard
                    title={t("Files & Uploads")}
                    description={t("Include user uploads and files")}
                    enabled={settings.includeUploads}
                    onToggle={() => handleToggle('includeUploads')}
                  />
                  <ToggleCard
                    title={t("Settings")}
                    description={t("Include system settings")}
                    enabled={settings.includeSettings}
                    onToggle={() => handleToggle('includeSettings')}
                  />
                </div>
              </div>
            </motion.div>
          )}
        </div>
      </PremiumSettingsCard>

      {/* Backup Options */}
      <PremiumSettingsCard 
        title={t("Backup Options")}
        description={t("Advanced backup configuration")}
        variant="gradient"
      >
        <div className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <ToggleCard
              title={t("Compression")}
              description={t("Compress backup files to save space")}
              enabled={settings.compressionEnabled}
              onToggle={() => handleToggle('compressionEnabled')}
            />
            <ToggleCard
              title={t("Encryption")}
              description={t("Encrypt backup files for security")}
              enabled={settings.encryption}
              onToggle={() => handleToggle('encryption')}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              {t("Storage Location")}
            </label>
            <Select value={settings.storageLocation} onValueChange={(value) => handleInputChange('storageLocation', value)}>
              <SelectTrigger className="w-full h-9 px-3 py-2 bg-gray-50 dark:bg-zinc-800 border-gray-200 dark:border-zinc-800 text-sm">
                <SelectValue placeholder={t("Select storage location")} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="local">{t("Local Storage")}</SelectItem>
                <SelectItem value="s3">{t("Amazon S3")}</SelectItem>
                <SelectItem value="ftp">{t("FTP Server")}</SelectItem>
                <SelectItem value="dropbox">{t("Dropbox")}</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
      </PremiumSettingsCard>

      {/* Manual Backup */}
      <PremiumSettingsCard 
        title={t("Manual Backup")}
        description={t("Create backups on demand")}
        variant="bordered"
      >
        <div className="flex flex-wrap gap-3">
          <motion.button
            whileHover={{ scale: 1.02 }}
            whileTap={{ scale: 0.98 }}
            onClick={() => createBackup('full')}
            className="px-4 py-2 bg-blue-500 text-white rounded-lg font-medium hover:bg-blue-600 transition-colors"
          >
            {t("Full Backup")}
          </motion.button>
          <motion.button
            whileHover={{ scale: 1.02 }}
            whileTap={{ scale: 0.98 }}
            onClick={() => createBackup('database')}
            className="px-4 py-2 bg-green-500 text-white rounded-lg font-medium hover:bg-green-600 transition-colors"
          >
            {t("Database Only")}
          </motion.button>
          <motion.button
            whileHover={{ scale: 1.02 }}
            whileTap={{ scale: 0.98 }}
            onClick={() => createBackup('files')}
            className="px-4 py-2 bg-purple-500 text-white rounded-lg font-medium hover:bg-purple-600 transition-colors"
          >
            {t("Files Only")}
          </motion.button>
          <motion.button
            whileHover={{ scale: 1.02 }}
            whileTap={{ scale: 0.98 }}
            onClick={() => createBackup('settings')}
            className="px-4 py-2 bg-orange-500 text-white rounded-lg font-medium hover:bg-orange-600 transition-colors"
          >
            {t("Settings Only")}
          </motion.button>
        </div>
      </PremiumSettingsCard>

      {/* Backup History */}
      <PremiumSettingsCard 
        title={t("Backup History")}
        description={t("Recent backups and restore options")}
        variant="glass"
      >
        {/* Backup Storage Path Display */}
        {backupPath && (
          <div className="mb-4 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
  <div className="flex flex-col sm:flex-row items-start sm:items-center gap-2">
    <svg
      className="w-4 h-4 text-blue-600 dark:text-blue-400"
      fill="none"
      stroke="currentColor"
      viewBox="0 0 24 24"
    >
      <path
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeWidth={2}
        d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2H5a2 2 0 00-2-2z"
      />
    </svg>
    <span className="text-sm font-medium text-blue-800 dark:text-blue-200">
      {t("Storage Location")}:
    </span>
    <code className="text-xs bg-blue-100 dark:bg-blue-900/50 text-blue-900 dark:text-blue-300 px-2 py-1 rounded font-mono break-all">
      {backupPath}
    </code>
  </div>
</div>

        )}

        <div className="overflow-hidden rounded-lg border border-gray-200 dark:border-zinc-800">
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
              <thead className="bg-gray-50 dark:bg-gray-800">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    {t("Backup Name")}
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    {t("Date")}
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    {t("Size")}
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    {t("Type")}
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    {t("Actions")}
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white dark:bg-zinc-900 divide-y divide-gray-200 dark:divide-gray-700">
                {backups && backups.length > 0 ? backups.map((backup) => (
                  <tr key={backup.id}>
                    <td className="px-4 py-3 text-sm text-gray-900 dark:text-gray-300">{backup.name}</td>
                    <td className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400">{backup.date}</td>
                    <td className="px-4 py-3 text-sm text-gray-900 dark:text-gray-300">{backup.size}</td>
                    <td className="px-4 py-3">
                      <span className={`px-2 py-1 text-xs font-semibold rounded-full ${
                        backup.type === 'full' 
                          ? 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400'
                          : backup.type === 'database'
                          ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                          : backup.type === 'files'
                          ? 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400'
                          : 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-400'
                      }`}>
                        {backup.type}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-sm space-x-2">
                      <button
                        onClick={() => restoreBackup(backup.path)}
                        className="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 font-medium"
                        disabled={isSubmitting}
                        title={t("Restore this backup")}
                      >
                        {t("Restore")}
                      </button>
                      <button
                        onClick={() => deleteBackup(backup.path, backup.id)}
                        className="text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 font-medium"
                        disabled={isSubmitting}
                        title={t("Delete this backup")}
                      >
                        {t("Delete")}
                      </button>
                    </td>
                  </tr>
                )) : (
                  <tr>
                    <td colSpan="5" className="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
                      <div className="flex flex-col items-center space-y-3">
                        <svg className="w-12 h-12 text-gray-300 dark:text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2M4 13h2m13-8l-4 4 4 4m-6-4h-2" />
                        </svg>
                        <div className="text-center">
                          <p className="text-sm font-medium text-gray-900 dark:text-gray-300">{t("No backups found")}</p>
                          <p className="text-xs text-gray-500 dark:text-gray-400">{t("Create your first backup using the manual backup options above")}</p>
                        </div>
                      </div>
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      </PremiumSettingsCard>

      {/* Maintenance Settings */}
      <PremiumSettingsCard 
        title={t("System Maintenance")}
        description={t("Configure system maintenance and cleanup tasks")}
        variant="default"
      >
        <div className="space-y-4">
          <div className="flex items-center justify-between flex-wrap gap-4 p-4 bg-yellow-50 dark:bg-yellow-900/20 rounded-lg border border-yellow-200 dark:border-yellow-800">
            <div>
              <h4 className="font-medium text-yellow-800 dark:text-yellow-200">{t("Maintenance Mode")}</h4>
              <p className="text-sm text-yellow-600 dark:text-yellow-400">{settings.maintenanceMode ? t("Site is currently in maintenance mode") : t("Site is operational")}</p>
            </div>
            <button
              onClick={toggleMaintenanceMode}
              className={`px-4 py-2 rounded-lg font-medium transition-colors ${
                settings.maintenanceMode
                  ? 'bg-green-500 hover:bg-green-600 text-white'
                  : 'bg-yellow-500 hover:bg-yellow-600 text-white'
              }`}
            >
              {settings.maintenanceMode ? t("Exit Maintenance") : t("Enter Maintenance")}
            </button>
          </div>

          <ToggleCard
            title={t("Scheduled Maintenance")}
            description={t("Enable automatic scheduled maintenance")}
            enabled={settings.scheduledMaintenance}
            onToggle={() => handleToggle('scheduledMaintenance')}
          />

          {settings.scheduledMaintenance && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: "auto" }}
              className="grid grid-cols-1 md:grid-cols-2 gap-4 pl-6 border-l-2 border-blue-100 dark:border-blue-900"
            >
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  {t("Maintenance Time")}
                </label>
                <input
                  type="time"
                  value={settings.maintenanceTime}
                  onChange={(e) => handleInputChange('maintenanceTime', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  {t("Maintenance Day")}
                </label>
                <Select value={settings.maintenanceDay} onValueChange={(value) => handleInputChange('maintenanceDay', value)}>
                  <SelectTrigger className="w-full h-9 px-3 py-2 bg-gray-50 dark:bg-zinc-800 border-gray-200 dark:border-zinc-800 text-sm">
                    <SelectValue placeholder={t("Select day")} />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="daily">{t("Daily")}</SelectItem>
                    <SelectItem value="sunday">{t("Sunday")}</SelectItem>
                    <SelectItem value="monday">{t("Monday")}</SelectItem>
                    <SelectItem value="tuesday">{t("Tuesday")}</SelectItem>
                    <SelectItem value="wednesday">{t("Wednesday")}</SelectItem>
                    <SelectItem value="thursday">{t("Thursday")}</SelectItem>
                    <SelectItem value="friday">{t("Friday")}</SelectItem>
                    <SelectItem value="saturday">{t("Saturday")}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </motion.div>
          )}

          <div className="space-y-3">
            <h4 className="font-medium text-gray-900 dark:text-white">{t("Cleanup Settings")}</h4>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <ToggleCard
                title={t("Cache Cleanup")}
                description={t("Automatically clear cache files")}
                enabled={settings.cacheCleanup}
                onToggle={() => handleToggle('cacheCleanup')}
              />
              <ToggleCard
                title={t("Auto Updates")}
                description={t("Enable automatic system updates")}
                enabled={settings.autoUpdates}
                onToggle={() => handleToggle('autoUpdates')}
              />
            </div>
          </div>

        </div>
      </PremiumSettingsCard>
      </div>
    </PremiumSettingsCard>
  )
}