"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"

export default function SecuritySettings({ settings: siteSettings }) {
  const t = useTranslate()
  const [isSubmitting, setIsSubmitting] = useState(false)
  
  const [settings, setSettings] = useState({
    twoFactorAuth: siteSettings?.two_factor_auth === '1',
    sessionTimeout: siteSettings?.session_timeout || 30,
    passwordRequirements: {
      minLength: siteSettings?.password_min_length || 8,
      requireUppercase: siteSettings?.password_require_uppercase === '1',
      requireNumbers: siteSettings?.password_require_numbers === '1',
      requireSpecialChars: siteSettings?.password_require_special === '1'
    },
    loginAttempts: siteSettings?.max_login_attempts || 5,
    lockoutDuration: siteSettings?.lockout_duration || 15,
    securityNotifications: siteSettings?.security_notifications === '1',
    ipWhitelist: siteSettings?.ip_whitelist_enabled === '1',
    allowedIPs: siteSettings?.allowed_ips ? JSON.parse(siteSettings.allowed_ips) : [],
    dataRetention: siteSettings?.data_retention_days || 365,
    privacyMode: siteSettings?.privacy_mode === '1',
    analyticsTracking: siteSettings?.analytics_tracking === '1',
    cookieConsent: siteSettings?.cookie_consent === '1',
    gdprCompliance: siteSettings?.gdpr_compliance === '1',
    dataExport: siteSettings?.data_export_enabled === '1',
    accountDeletion: siteSettings?.account_deletion_enabled === '1',
    auditLogs: siteSettings?.audit_logs_enabled === '1',
    encryptData: siteSettings?.data_encryption === '1'
  })

  const [newIP, setNewIP] = useState("")
  const [logs, setLogs] = useState([
    { id: 1, action: "User Login", user: "admin@site.com", ip: "192.168.1.100", time: "2 hours ago", status: "success" },
    { id: 2, action: "Settings Changed", user: "admin@site.com", ip: "192.168.1.100", time: "3 hours ago", status: "success" },
    { id: 3, action: "Failed Login", user: "unknown", ip: "203.0.113.1", time: "5 hours ago", status: "failed" }
  ])

  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 addIPAddress = () => {
    if (newIP && !settings.allowedIPs.includes(newIP)) {
      setSettings(prev => ({
        ...prev,
        allowedIPs: [...prev.allowedIPs, newIP]
      }))
      setNewIP("")
    }
  }

  const removeIPAddress = (ip) => {
    setSettings(prev => ({
      ...prev,
      allowedIPs: prev.allowedIPs.filter(allowedIP => allowedIP !== ip)
    }))
  }

  const handleSave = () => {
    setIsSubmitting(true)
    
    const securityData = {
      two_factor_auth: settings.twoFactorAuth ? '1' : '0',
      session_timeout: settings.sessionTimeout,
      password_min_length: settings.passwordRequirements.minLength,
      password_require_uppercase: settings.passwordRequirements.requireUppercase ? '1' : '0',
      password_require_numbers: settings.passwordRequirements.requireNumbers ? '1' : '0',
      password_require_special: settings.passwordRequirements.requireSpecialChars ? '1' : '0',
      max_login_attempts: settings.loginAttempts,
      lockout_duration: settings.lockoutDuration,
      security_notifications: settings.securityNotifications ? '1' : '0',
      ip_whitelist_enabled: settings.ipWhitelist ? '1' : '0',
      allowed_ips: JSON.stringify(settings.allowedIPs),
      data_retention_days: settings.dataRetention,
      privacy_mode: settings.privacyMode ? '1' : '0',
      analytics_tracking: settings.analyticsTracking ? '1' : '0',
      cookie_consent: settings.cookieConsent ? '1' : '0',
      gdpr_compliance: settings.gdprCompliance ? '1' : '0',
      data_export_enabled: settings.dataExport ? '1' : '0',
      account_deletion_enabled: settings.accountDeletion ? '1' : '0',
      audit_logs_enabled: settings.auditLogs ? '1' : '0',
      data_encryption: settings.encryptData ? '1' : '0'
    }
    
    router.post(route('user.setting.store'), securityData, {
      onFinish: () => setIsSubmitting(false),
      onError: () => setIsSubmitting(false),
    })
  }

  const exportData = () => {
    router.get(route('user.setting.data.export'), {}, {
      onStart: () => setIsSubmitting(true),
      onFinish: () => setIsSubmitting(false),
    })
  }

  return (
    <div className="p-6 space-y-6">

      {/* Authentication Security */}
      <PremiumSettingsCard 
        title={t("Authentication Security")}
        description={t("Configure user authentication and access control")}
        variant="default"
      >
        <div className="space-y-4">
          <ToggleCard
            title={t("Two-Factor Authentication")}
            description={t("Require 2FA for admin accounts")}
            enabled={settings.twoFactorAuth}
            onToggle={() => handleToggle('twoFactorAuth')}
          />

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                {t("Session Timeout (minutes)")}
              </label>
              <input
                type="number"
                value={settings.sessionTimeout}
                onChange={(e) => handleInputChange('sessionTimeout', 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="5"
                max="1440"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                {t("Max Login Attempts")}
              </label>
              <input
                type="number"
                value={settings.loginAttempts}
                onChange={(e) => handleInputChange('loginAttempts', 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="3"
                max="10"
              />
            </div>
          </div>
        </div>
      </PremiumSettingsCard>

      {/* Password Policy */}
      <PremiumSettingsCard 
        title={t("Password Policy")}
        description={t("Set password requirements for user accounts")}
        variant="gradient"
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              {t("Minimum Password Length")}
            </label>
            <input
              type="number"
              value={settings.passwordRequirements.minLength}
              onChange={(e) => handleInputChange('passwordRequirements', {
                ...settings.passwordRequirements,
                minLength: 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="6"
              max="32"
            />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <ToggleCard
              title={t("Require Uppercase Letters")}
              description={t("Password must contain A-Z")}
              enabled={settings.passwordRequirements.requireUppercase}
              onToggle={() => handleToggle('passwordRequirements', 'requireUppercase')}
              />
            <ToggleCard
              title={t("Require Numbers")}
              description={t("Password must contain 0-9")}
              enabled={settings.passwordRequirements.requireNumbers}
              onToggle={() => handleToggle('passwordRequirements', 'requireNumbers')}
              />
          </div>

          <ToggleCard
            title={t("Require Special Characters")}
            description={t("Password must contain symbols (!@#$%^&*)")}
            enabled={settings.passwordRequirements.requireSpecialChars}
            onToggle={() => handleToggle('passwordRequirements', 'requireSpecialChars')}
          />
        </div>
      </PremiumSettingsCard>

      {/* IP Access Control */}
      <PremiumSettingsCard 
        title={t("IP Access Control")}
        description={t("Restrict access by IP address")}
        variant="bordered"
      >
        <div className="space-y-4">
          <ToggleCard
            title={t("Enable IP Whitelist")}
            description={t("Only allow access from specified IP addresses")}
            enabled={settings.ipWhitelist}
            onToggle={() => handleToggle('ipWhitelist')}
          />

          {settings.ipWhitelist && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: "auto" }}
              className="space-y-3 pl-6 border-l-2 border-blue-100 dark:border-blue-900"
            >
              <div className="flex space-x-2">
                <input
                  type="text"
                  value={newIP}
                  onChange={(e) => setNewIP(e.target.value)}
                  placeholder="192.168.1.100"
                  className="flex-1 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"
                />
                <button
                  onClick={addIPAddress}
                  className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
                >
                  {t("Add")}
                </button>
              </div>
              
              <div className="space-y-2">
                {settings.allowedIPs.map((ip, index) => (
                  <div key={index} className="flex items-center justify-between bg-gray-50 dark:bg-gray-800 p-2 rounded-lg">
                    <span className="text-sm text-gray-700 dark:text-gray-300">{ip}</span>
                    <button
                      onClick={() => removeIPAddress(ip)}
                      className="text-red-500 hover:text-red-700 text-sm"
                    >
                      {t("Remove")}
                    </button>
                  </div>
                ))}
              </div>
            </motion.div>
          )}
        </div>
      </PremiumSettingsCard>

      {/* Privacy Settings */}
      <PremiumSettingsCard 
        title={t("Privacy Settings")}
        description={t("Control data collection and privacy options")}
        variant="glass"
      >
        <div className="space-y-4">
          <ToggleCard
            title={t("GDPR Compliance Mode")}
            description={t("Enable GDPR compliance features")}
            enabled={settings.gdprCompliance}
            onToggle={() => handleToggle('gdprCompliance')}
          />
          <ToggleCard
            title={t("Analytics Tracking")}
            description={t("Allow user behavior analytics")}
            enabled={settings.analyticsTracking}
            onToggle={() => handleToggle('analyticsTracking')}
          />
          <ToggleCard
            title={t("Cookie Consent")}
            description={t("Require user consent for cookies")}
            enabled={settings.cookieConsent}
            onToggle={() => handleToggle('cookieConsent')}
          />

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              {t("Data Retention (days)")}
            </label>
            <input
              type="number"
              value={settings.dataRetention}
              onChange={(e) => handleInputChange('dataRetention', 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="30"
              max="3650"
            />
          </div>
        </div>
      </PremiumSettingsCard>

      {/* Data Management */}
      <PremiumSettingsCard 
        title={t("Data Management")}
        description={t("User data export and deletion options")}
        variant="default"
      >
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <h4 className="font-medium text-gray-900 dark:text-white">{t("Data Export")}</h4>
              <p className="text-sm text-gray-500 dark:text-gray-400">{t("Allow users to export their data")}</p>
            </div>
            <button
              onClick={exportData}
              className="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors"
              disabled={isSubmitting}
            >
              {isSubmitting ? t("Exporting...") : t("Export Now")}
            </button>
          </div>

          <ToggleCard
            title={t("Account Deletion")}
            description={t("Allow users to delete their accounts")}
            enabled={settings.accountDeletion}
            onToggle={() => handleToggle('accountDeletion')}
          />

          <ToggleCard
            title={t("Data Encryption")}
            description={t("Encrypt sensitive user data")}
            enabled={settings.encryptData}
            onToggle={() => handleToggle('encryptData')}
          />
        </div>
      </PremiumSettingsCard>

      {/* Security Audit Log */}
      <PremiumSettingsCard 
        title={t("Security Audit Log")}
        description={t("Recent security events and access logs")}
        variant="bordered"
      >
        <div className="space-y-4">
          <ToggleCard
            title={t("Enable Audit Logging")}
            description={t("Log security events and user actions")}
            enabled={settings.auditLogs}
            onToggle={() => handleToggle('auditLogs')}
          />

          {settings.auditLogs && (
            <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("Action")}
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                        {t("User")}
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                        {t("IP Address")}
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                        {t("Time")}
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                        {t("Status")}
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white dark:bg-zinc-900 divide-y divide-gray-200 dark:divide-gray-700">
                    {logs.map((log) => (
                      <tr key={log.id}>
                        <td className="px-4 py-3 text-sm text-gray-900 dark:text-gray-300">{log.action}</td>
                        <td className="px-4 py-3 text-sm text-gray-900 dark:text-gray-300">{log.user}</td>
                        <td className="px-4 py-3 text-sm text-gray-900 dark:text-gray-300">{log.ip}</td>
                        <td className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400">{log.time}</td>
                        <td className="px-4 py-3">
                          <span className={`px-2 py-1 text-xs font-semibold rounded-full ${
                            log.status === 'success' 
                              ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                              : 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400'
                          }`}>
                            {log.status}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      </PremiumSettingsCard>

      {/* Save Settings */}
      <PremiumSettingsCard variant="default">
        <div className="flex justify-end">
          <motion.button
            whileHover={{ scale: 1.02 }}
            whileTap={{ scale: 0.98 }}
            onClick={handleSave}
            className="px-6 py-2 bg-gradient-to-r from-blue-500 to-purple-600 text-white rounded-lg font-medium hover:shadow-lg transition-all"
            disabled={isSubmitting}
          >
            {isSubmitting ? t("Saving...") : t("Save Security Settings")}
          </motion.button>
        </div>
      </PremiumSettingsCard>
    </div>
  )
}