/**
 * Settings.tsx
 *
 * @author Descomplicar® Crescimento Digital
 * @link https://descomplicar.pt
 * @copyright 2025 Descomplicar®
 */

import React, { useState, useEffect } from 'react';
import type { CrmSettings } from '../types';

interface SettingsProps {
  crmSettings: CrmSettings;
  onSaveCrmSettings: (settings: CrmSettings) => void;
  isAutoCleanEnabled: boolean;
  setAutoCleanEnabled: (enabled: boolean) => void;
  apiKey: string;
  onSaveApiKey: (key: string) => void;
}

const Settings: React.FC<SettingsProps> = ({ 
  crmSettings, 
  onSaveCrmSettings, 
  isAutoCleanEnabled, 
  setAutoCleanEnabled,
  apiKey,
  onSaveApiKey
}) => {
  const [currentCrmSettings, setCurrentCrmSettings] = useState<CrmSettings>(crmSettings);
  const [currentApiKey, setCurrentApiKey] = useState<string>(apiKey);
  const [showSuccess, setShowSuccess] = useState(false);

  useEffect(() => {
    setCurrentCrmSettings(crmSettings);
  }, [crmSettings]);

  useEffect(() => {
    setCurrentApiKey(apiKey);
  }, [apiKey]);

  const handleCrmChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = e.target;
    setCurrentCrmSettings(prev => ({ 
      ...prev, 
      [name]: type === 'checkbox' ? checked : value 
    }));
  };
  
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSaveCrmSettings(currentCrmSettings);
    onSaveApiKey(currentApiKey);
    setShowSuccess(true);
    setTimeout(() => setShowSuccess(false), 3000);
  };

  return (
    <div className="space-y-8 max-w-3xl mx-auto">
      <div>
        <h2 className="text-2xl font-bold text-slate-800 dark:text-white">Configurações</h2>
        <p className="text-slate-500 dark:text-slate-400">Gerencie as integrações e preferências da aplicação.</p>
      </div>

       <div className="bg-white dark:bg-slate-800 rounded-xl shadow-md border border-slate-200 dark:border-slate-700">
          <div className="p-6">
            <h3 className="text-lg font-semibold text-slate-800 dark:text-white">Limpeza Automática (Backend)</h3>
            <p className="text-slate-500 dark:text-slate-400 text-sm mt-1">
              Ative para que um processo no servidor (Cloud Run) analise seus e-mails a cada 2 horas, mesmo com o navegador fechado.
            </p>
          </div>
          <div className="bg-slate-50 dark:bg-slate-800/50 p-6 border-t border-slate-200 dark:border-slate-700 rounded-b-xl">
             <div className="flex items-center justify-between">
               <span className="font-medium text-slate-700 dark:text-slate-200">
                  {isAutoCleanEnabled ? 'Automação Ativada' : 'Automação Desativada'}
                </span>
               <button
                  onClick={() => setAutoCleanEnabled(!isAutoCleanEnabled)}
                  className={`${
                    isAutoCleanEnabled ? 'bg-sky-500' : 'bg-slate-300 dark:bg-slate-600'
                  } relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-sky-500 focus:ring-offset-2 dark:ring-offset-slate-800`}
                  role="switch"
                  aria-checked={isAutoCleanEnabled}
                >
                  <span
                    className={`${
                      isAutoCleanEnabled ? 'translate-x-5' : 'translate-x-0'
                    } pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out`}
                  />
                </button>
             </div>
              <p className="text-xs text-slate-500 dark:text-slate-400 mt-3">
                <strong>Nota:</strong> Para a automação funcionar, as chaves de API abaixo devem ser configuradas como **variáveis de ambiente** no seu serviço Cloud Run. Consulte o arquivo `README.md`.
              </p>
          </div>
       </div>

      <form onSubmit={handleSubmit}>
         <div className="bg-white dark:bg-slate-800 rounded-xl shadow-md border border-slate-200 dark:border-slate-700 mb-8">
            <div className="p-6 space-y-6">
              <div>
                <h3 className="text-lg font-semibold text-slate-800 dark:text-white">Chave da API do Google Gemini</h3>
                <p className="text-slate-500 dark:text-slate-400 text-sm mt-1">Insira sua chave para habilitar a análise com IA nas verificações manuais.</p>
              </div>
              <div>
                <label htmlFor="apiKey" className="block text-sm font-medium text-slate-700 dark:text-slate-300">
                  Sua Chave API
                </label>
                <input
                  type="password"
                  name="apiKey"
                  id="apiKey"
                  value={currentApiKey}
                  onChange={(e) => setCurrentApiKey(e.target.value)}
                  className="mt-1 block w-full px-3 py-2 bg-white dark:bg-slate-700 border border-slate-300 dark:border-slate-600 rounded-md shadow-sm placeholder-slate-400 focus:outline-none focus:ring-sky-500 focus:border-sky-500 sm:text-sm"
                  placeholder="Cole sua chave da API do Gemini aqui"
                />
              </div>
            </div>
         </div>


        <div className="bg-white dark:bg-slate-800 rounded-xl shadow-md border border-slate-200 dark:border-slate-700">
            <div className="p-6 space-y-6">
              <div>
                <h3 className="text-lg font-semibold text-slate-800 dark:text-white">Integração com Perfex CRM</h3>
                <p className="text-slate-500 dark:text-slate-400 text-sm mt-1">Conecte-se à sua instância do Perfex CRM para automatizar tarefas.</p>
              </div>
              
              <div className="space-y-4">
                <div>
                  <label htmlFor="url" className="block text-sm font-medium text-slate-700 dark:text-slate-300">
                    URL da API do Perfex CRM
                  </label>
                  <input
                    type="url"
                    name="url"
                    id="url"
                    value={currentCrmSettings.url}
                    onChange={handleCrmChange}
                    className="mt-1 block w-full px-3 py-2 bg-white dark:bg-slate-700 border border-slate-300 dark:border-slate-600 rounded-md shadow-sm placeholder-slate-400 focus:outline-none focus:ring-sky-500 focus:border-sky-500 sm:text-sm"
                    placeholder="https://seu-crm.com"
                  />
                </div>

                <div>
                  <label htmlFor="token" className="block text-sm font-medium text-slate-700 dark:text-slate-300">
                    Token da API
                  </label>
                  <input
                    type="password"
                    name="token"
                    id="token"
                    value={currentCrmSettings.token}
                    onChange={handleCrmChange}
                    className="mt-1 block w-full px-3 py-2 bg-white dark:bg-slate-700 border border-slate-300 dark:border-slate-600 rounded-md shadow-sm placeholder-slate-400 focus:outline-none focus:ring-sky-500 focus:border-sky-500 sm:text-sm"
                    placeholder="Seu token de API seguro"
                  />
                </div>

                 <div className="relative flex items-start">
                    <div className="flex h-5 items-center">
                      <input
                        id="autoDeleteTickets"
                        name="autoDeleteTickets"
                        type="checkbox"
                        checked={currentCrmSettings.autoDeleteTickets}
                        onChange={handleCrmChange}
                        className="h-4 w-4 rounded border-slate-300 text-sky-600 focus:ring-sky-500"
                      />
                    </div>
                    <div className="ml-3 text-sm">
                      <label htmlFor="autoDeleteTickets" className="font-medium text-slate-700 dark:text-slate-200">
                        Excluir Tickets de Spam/Notificações
                      </label>
                      <p className="text-slate-500 dark:text-slate-400">Excluir automaticamente tickets do CRM criados por e-mails de spam ou notificações.</p>
                    </div>
                  </div>
              </div>
            </div>
            <div className="bg-slate-50 dark:bg-slate-800/50 p-4 border-t border-slate-200 dark:border-slate-700 rounded-b-xl flex items-center justify-end gap-4">
                {showSuccess && <p className="text-sm text-green-600 dark:text-green-400 animate-pulse">Configurações salvas com sucesso!</p>}
                <button
                    type="submit"
                    className="bg-sky-500 text-white font-semibold py-2 px-5 rounded-lg hover:bg-sky-600 transition-colors"
                >
                    Salvar Todas as Configurações
                </button>
            </div>
        </div>
      </form>
    </div>
  );
};

export default Settings;
