"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 EmailSettings({ settings: siteSettings }) {
  const t = useTranslate()
  const [isSubmitting, setIsSubmitting] = useState(false)
  
  const [settings, setSettings] = useState({
    smtpEnabled: siteSettings?.mail_gateway === 'smtp',
    smtpHost: siteSettings?.smtp_host || "smtp.gmail.com",
    smtpPort: siteSettings?.smtp_port || "587",
    smtpUsername: siteSettings?.smtp_username || "",
    smtpPassword: siteSettings?.smtp_password || "",
    encryption: siteSettings?.smtp_encryption || "tls",
    fromAddress: siteSettings?.mail_from_address || "",
    fromName: siteSettings?.mail_from_name || "",
    testEmail: "",
    testMode: false,
    passwordReset: true,
    accountVerification: true,
    notifications: true,
    templates: {
      passwordReset: true,
      welcome: true,
      verification: true,
      notifications: true
    }
  })

  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 emailData = {
      mail_gateway: settings.smtpEnabled ? 'smtp' : 'php',
      smtp_host: settings.smtpHost,
      smtp_port: settings.smtpPort,
      smtp_username: settings.smtpUsername,
      smtp_password: settings.smtpPassword,
      smtp_encryption: settings.encryption,
      mail_from_address: settings.fromAddress,
      mail_from_name: settings.fromName,
      mail_password_reset: settings.passwordReset ? '1' : '0',
      mail_account_verification: settings.accountVerification ? '1' : '0',
      mail_notifications: settings.notifications ? '1' : '0',
      mail_template_password_reset: settings.templates.passwordReset ? '1' : '0',
      mail_template_welcome: settings.templates.welcome ? '1' : '0',
      mail_template_verification: settings.templates.verification ? '1' : '0',
      mail_template_notifications: settings.templates.notifications ? '1' : '0',
      mail_test_mode: settings.testMode ? '1' : '0'
    }
    
    router.post(route('user.setting.store'), emailData, {
      onFinish: () => setIsSubmitting(false),
      onError: () => setIsSubmitting(false),
    })
  }

  const handleTestEmail = () => {
    if (!settings.testEmail) {
      alert(t('Please enter a test email address'))
      return
    }
    
    setIsSubmitting(true)
    
    router.post(route('user.setting.test-email'), {
      smtp_host: settings.smtpHost,
      smtp_port: settings.smtpPort,
      smtp_username: settings.smtpUsername,
      smtp_password: settings.smtpPassword,
      smtp_encryption: settings.encryption,
      mail_from_address: settings.fromAddress,
      mail_from_name: settings.fromName,
      test_email: settings.testEmail
    }, {
      onFinish: () => setIsSubmitting(false),
      onError: () => setIsSubmitting(false),
    })
  }

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

      {/* SMTP Configuration */}
      <PremiumSettingsCard 
        title={t("SMTP Server Settings")}
        description={t("Configure your email server settings")}
        variant="default"
      >
        <div className="space-y-4">
          <ToggleCard
            title={t("Enable SMTP")}
            description={t("Use custom SMTP server for sending emails")}
            enabled={settings.smtpEnabled}
            onToggle={() => handleToggle('smtpEnabled')}
          />

          {settings.smtpEnabled && (
            <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-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t("SMTP Host")}
                  </label>
                  <input
                    type="text"
                    value={settings.smtpHost}
                    onChange={(e) => handleInputChange('smtpHost', 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"
                    placeholder="smtp.gmail.com"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t("SMTP Port")}
                  </label>
                  <select
                    value={settings.smtpPort}
                    onChange={(e) => handleInputChange('smtpPort', 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"
                  >
                    <option value="587">587 (TLS)</option>
                    <option value="465">465 (SSL)</option>
                    <option value="25">25 (No encryption)</option>
                  </select>
                </div>
              </div>

              <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("Username")}
                  </label>
                  <input
                    type="email"
                    value={settings.smtpUsername}
                    onChange={(e) => handleInputChange('smtpUsername', 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"
                    placeholder="your-email@example.com"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t("Password")}
                  </label>
                  <input
                    type="password"
                    value={settings.smtpPassword}
                    onChange={(e) => handleInputChange('smtpPassword', 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"
                    placeholder="••••••••"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  {t("Encryption")}
                </label>
                <select
                  value={settings.encryption}
                  onChange={(e) => handleInputChange('encryption', 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"
                >
                  <option value="tls">TLS</option>
                  <option value="ssl">SSL</option>
                  <option value="none">None</option>
                </select>
              </div>
            </motion.div>
          )}
        </div>
      </PremiumSettingsCard>

      {/* Email Identity */}
      <PremiumSettingsCard 
        title={t("Email Identity")}
        description={t("Configure sender information")}
        variant="gradient"
      >
        <div className="space-y-4">
          <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("From Email")}
              </label>
              <input
                type="email"
                value={settings.fromAddress}
                onChange={(e) => handleInputChange('fromAddress', 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"
                placeholder="noreply@yoursite.com"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                {t("From Name")}
              </label>
              <input
                type="text"
                value={settings.fromName}
                onChange={(e) => handleInputChange('fromName', 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"
                placeholder="Your Site Name"
              />
            </div>
          </div>
        </div>
      </PremiumSettingsCard>

      {/* Email Types */}
      <PremiumSettingsCard 
        title={t("Email Types")}
        description={t("Configure which emails to send")}
        variant="bordered"
      >
        <div className="space-y-4">
          <ToggleCard
            title={t("Password Reset Emails")}
            description={t("Send emails when users request password reset")}
            enabled={settings.passwordReset}
            onToggle={() => handleToggle('passwordReset')}
          />
          <ToggleCard
            title={t("Account Verification")}
            description={t("Send verification emails for new accounts")}
            enabled={settings.accountVerification}
            onToggle={() => handleToggle('accountVerification')}
          />
          <ToggleCard
            title={t("System Notifications")}
            description={t("Send system and admin notifications")}
            enabled={settings.notifications}
            onToggle={() => handleToggle('notifications')}
          />
        </div>
      </PremiumSettingsCard>

      {/* Email Templates */}
      <PremiumSettingsCard 
        title={t("Email Templates")}
        description={t("Manage email template settings")}
        variant="glass"
      >
        <div className="space-y-4">
          <ToggleCard
            title={t("Password Reset Template")}
            description={t("Custom password reset email template")}
            enabled={settings.templates.passwordReset}
            onToggle={() => handleToggle('templates', 'passwordReset')}
          />
          <ToggleCard
            title={t("Welcome Email Template")}
            description={t("Send welcome email to new users")}
            enabled={settings.templates.welcome}
            onToggle={() => handleToggle('templates', 'welcome')}
          />
          <ToggleCard
            title={t("Verification Template")}
            description={t("Email verification template")}
            enabled={settings.templates.verification}
            onToggle={() => handleToggle('templates', 'verification')}
          />
          <ToggleCard
            title={t("Notification Template")}
            description={t("System notification template")}
            enabled={settings.templates.notifications}
            onToggle={() => handleToggle('templates', 'notifications')}
          />
        </div>
      </PremiumSettingsCard>

      {/* Test & Save */}
      <PremiumSettingsCard 
        title={t("Test Email Configuration")}
        description={t("Send a test email to verify your SMTP settings")}
        variant="default"
      >
        <div className="space-y-4">
          {/* Test Email Input */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              {t("Test Email Address")}
            </label>
            <input
              type="email"
              value={settings.testEmail}
              onChange={(e) => handleInputChange('testEmail', 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"
              placeholder={t("Enter email address to send test email")}
            />
          </div>

          {/* Test Mode Toggle */}
          <ToggleCard
            title={t("Test Mode")}
            description={t("Test emails without actually sending them")}
            enabled={settings.testMode}
            onToggle={() => handleToggle('testMode')}
          />

          {/* Action Buttons */}
          <div className="flex justify-between items-center pt-4 border-t border-gray-200 dark:border-zinc-800">
            <div className="text-sm text-gray-500 dark:text-gray-400">
              {t("Make sure to save settings before testing")}
            </div>
            <div className="flex space-x-3">
              <motion.button
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
                onClick={handleTestEmail}
                className="px-4 py-2 text-blue-600 bg-blue-50 hover:bg-blue-100 dark:bg-blue-900/30 dark:text-blue-400 dark:hover:bg-blue-900/50 rounded-lg font-medium transition-colors"
                disabled={isSubmitting || !settings.testEmail}
              >
                {isSubmitting ? t("Sending Test...") : t("Send Test Email")}
              </motion.button>
              <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 Settings")}
              </motion.button>
            </div>
          </div>
        </div>
      </PremiumSettingsCard>
    </div>
  )
}