import React, { useState, useEffect } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Database, CheckCircle, BarChart2, LogOut, User, FlaskConical } from 'lucide-react';
import { ImportView } from './components/ImportView';
import { ReviewView } from './components/ReviewView';
import { DashboardView } from './components/DashboardView';
import { LabView } from './components/LabView';
import { LoginPage } from './components/LoginPage';
import { LanguageSwitch } from './components/common/LanguageSwitch';
import { authApi } from './services/api';

type TabId = 'import' | 'review' | 'dashboard' | 'lab';

interface Tab {
  id: TabId;
  icon: React.ElementType;
  labelKey: string;
  badge?: number;
}

const MainLayout: React.FC<{ onLogout: () => void }> = ({ onLogout }) => {
  const { t } = useTranslation();
  const [activeTab, setActiveTab] = useState<TabId>('import');
  const [reviewCount, setReviewCount] = useState(0);
  const [userEmail, setUserEmail] = useState('');

  useEffect(() => {
    authApi.me().then(user => {
      setUserEmail(user.email);
    }).catch(() => { });
  }, []);

  const tabs: Tab[] = [
    { id: 'import', icon: Database, labelKey: 'nav.import' },
    { id: 'review', icon: CheckCircle, labelKey: 'nav.review', badge: reviewCount },
    { id: 'dashboard', icon: BarChart2, labelKey: 'nav.dashboard' },
    { id: 'lab', icon: FlaskConical, labelKey: 'nav.lab' },
  ];

  const handleEtlComplete = () => {
    setReviewCount(2);
    setActiveTab('review');
  };

  const handleReviewComplete = () => {
    setReviewCount(0);
    setActiveTab('dashboard');
  };

  const handleLogout = () => {
    localStorage.removeItem('token');
    onLogout();
  };

  return (
    <div className="min-h-screen bg-slate-50 font-sans text-slate-800">
      <header className="bg-white border-b border-slate-200 sticky top-0 z-10">
        <div className="max-w-7xl mx-auto px-4 h-16 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-indigo-600 rounded-lg flex items-center justify-center text-white font-bold">
              S
            </div>
            <div>
              <span className="font-bold text-lg text-slate-800 block leading-tight">
                {t('common.appName')}
              </span>
              <span className="text-[10px] text-slate-500 font-medium">
                {t('common.appSubtitle')}
              </span>
            </div>
          </div>

          <div className="flex gap-1 bg-slate-100 p-1 rounded-lg">
            {tabs.map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`
                  flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-all
                  ${activeTab === tab.id
                    ? 'bg-white text-indigo-600 shadow-sm'
                    : 'text-slate-500 hover:text-slate-700 hover:bg-slate-200/50'}
                `}
              >
                <tab.icon size={16} />
                {t(tab.labelKey)}
                {tab.badge !== undefined && tab.badge > 0 && (
                  <span className="bg-rose-500 text-white text-[10px] px-1.5 py-0.5 rounded-full">
                    {tab.badge}
                  </span>
                )}
              </button>
            ))}
          </div>

          <div className="flex items-center gap-4">
            <div className="flex items-center gap-2 text-sm text-emerald-600 bg-emerald-50 px-3 py-1 rounded-full border border-emerald-100">
              <div className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></div>
              {t('common.systemRunning')}
            </div>

            <LanguageSwitch />

            <div className="flex items-center gap-2 text-sm text-slate-600">
              <User size={16} />
              <span className="hidden sm:inline">{userEmail}</span>
            </div>

            <button
              onClick={handleLogout}
              className="flex items-center gap-2 px-3 py-2 text-sm text-slate-600 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
              title={t('nav.logout')}
            >
              <LogOut size={16} />
              <span className="hidden sm:inline">{t('nav.logout')}</span>
            </button>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-4 py-8">
        {activeTab === 'import' && (
          <ImportView onEtlComplete={handleEtlComplete} />
        )}

        {activeTab === 'review' && (
          <ReviewView onReviewComplete={handleReviewComplete} />
        )}

        {activeTab === 'dashboard' && (
          <DashboardView />
        )}

        {activeTab === 'lab' && (
          <LabView />
        )}
      </main>
    </div>
  );
};

function App() {
  const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null);

  useEffect(() => {
    const token = localStorage.getItem('token');
    if (token) {
      authApi.me()
        .then(() => setIsAuthenticated(true))
        .catch(() => {
          localStorage.removeItem('token');
          setIsAuthenticated(false);
        });
    } else {
      setIsAuthenticated(false);
    }
  }, []);

  const handleLogin = () => {
    setIsAuthenticated(true);
  };

  const handleLogout = () => {
    setIsAuthenticated(false);
  };

  if (isAuthenticated === null) {
    return (
      <div className="min-h-screen bg-slate-50 flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-4 border-indigo-600 border-t-transparent"></div>
      </div>
    );
  }

  return (
    <Routes>
      <Route
        path="/login"
        element={
          isAuthenticated ? (
            <Navigate to="/" replace />
          ) : (
            <LoginPage onLogin={handleLogin} />
          )
        }
      />
      <Route
        path="/*"
        element={
          isAuthenticated ? (
            <MainLayout onLogout={handleLogout} />
          ) : (
            <Navigate to="/login" replace />
          )
        }
      />
    </Routes>
  );
}

export default App;
