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

import React, { useState, useEffect } from 'react';
import Header from './components/Header';
import Sidebar from './components/Sidebar';
import Dashboard from './components/Dashboard';
import Accounts from './components/Accounts';
import Settings from './components/Settings';
import type { Account, CrmSettings } from './types';

const App: React.FC = () => {
  const [theme, setTheme] = useState(() => {
    const savedTheme = localStorage.getItem('theme');
    const userPrefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
    return savedTheme || (userPrefersDark ? 'dark' : 'light');
  });

  const [activeView, setActiveView] = useState('dashboard');
  const [accounts, setAccounts] = useState<Account[]>([
    { id: 1, email: 'usuario@gmail.com', provider: 'gmail', avatar: 'https://i.pravatar.cc/40?img=3' }
  ]);
  const [crmSettings, setCrmSettings] = useState<CrmSettings>(() => {
    const savedSettings = localStorage.getItem('crmSettings');
    const defaults = { 
      url: '', 
      token: '', 
      autoDeleteTickets: false,
    };
    return savedSettings ? { ...defaults, ...JSON.parse(savedSettings) } : defaults;
  });

  const [isAutoCleanEnabled, setIsAutoCleanEnabled] = useState<boolean>(() => {
    const savedState = localStorage.getItem('autoCleanEnabled');
    return savedState ? JSON.parse(savedState) : false;
  });

  const [apiKey, setApiKey] = useState<string>(() => localStorage.getItem('geminiApiKey') || '');


  useEffect(() => {
    const root = window.document.documentElement;
    if (theme === 'dark') {
      root.classList.add('dark');
    } else {
      root.classList.remove('dark');
    }
    localStorage.setItem('theme', theme);
  }, [theme]);

  useEffect(() => {
    localStorage.setItem('autoCleanEnabled', JSON.stringify(isAutoCleanEnabled));
  }, [isAutoCleanEnabled]);


  const handleSaveCrmSettings = (settings: CrmSettings) => {
    setCrmSettings(settings);
    localStorage.setItem('crmSettings', JSON.stringify(settings));
  };
  
  const handleSaveApiKey = (key: string) => {
    setApiKey(key);
    localStorage.setItem('geminiApiKey', key);
  };

  const toggleTheme = () => {
    setTheme(prevTheme => (prevTheme === 'light' ? 'dark' : 'light'));
  };

  const addAccount = (account: Omit<Account, 'id' | 'avatar'>) => {
    const newAccount: Account = {
      id: Date.now(),
      ...account,
      avatar: `https://i.pravatar.cc/40?img=${Math.floor(Math.random() * 70)}`
    };
    setAccounts(prev => [...prev, newAccount]);
  };

  const removeAccount = (accountId: number) => {
    setAccounts(prev => prev.filter(acc => acc.id !== accountId));
  };

  return (
    <div className="min-h-screen text-slate-800 dark:text-slate-200">
      <Header theme={theme} toggleTheme={toggleTheme} />
      <div className="flex">
        <Sidebar activeView={activeView} setActiveView={setActiveView} />
        <main className="flex-1 p-4 sm:p-6 lg:p-8 bg-slate-50 dark:bg-slate-900">
          {activeView === 'dashboard' && <Dashboard crmSettings={crmSettings} isAutoCleanEnabled={isAutoCleanEnabled} apiKey={apiKey} />}
          {activeView === 'contas' && <Accounts accounts={accounts} addAccount={addAccount} removeAccount={removeAccount} />}
          {activeView === 'configuracoes' && 
            <Settings 
              crmSettings={crmSettings} 
              onSaveCrmSettings={handleSaveCrmSettings} 
              isAutoCleanEnabled={isAutoCleanEnabled} 
              setAutoCleanEnabled={setIsAutoCleanEnabled}
              apiKey={apiKey}
              onSaveApiKey={handleSaveApiKey}
            />
          }
        </main>
      </div>
    </div>
  );
};

export default App;