import React, { useEffect } from 'react';
import { useStore } from './store/useStore';

// Auth
import LoginPage from './components/auth/LoginPage';

// Layout
import Sidebar from './components/layout/Sidebar';
import { ToastContainer, useToastStore } from './components/layout/Toast';

// Editor
import TableView from './components/editor/TableView';
import PropertyPanel from './components/editor/PropertyPanel';
import { ImportModal } from './components/editor/ImportModal';

// Plans
import PlanListView from './components/plans/PlanListView';
import TaskExecutionView from './components/plans/TaskExecutionView';

// Shared
import DashboardView from './components/shared/DashboardView';
import BugView from './components/shared/BugView';

import { Search, UploadCloud, LogOut } from 'lucide-react';
 
 const App: React.FC = () => {
  const { 
    spaces, currentSpaceId, setCurrentSpaceId, viewMode, setViewMode, 
    fetchSpaces, fetchData, fetchTasks, fetchBugs, testTasks, setSelectedTaskId,
    showImportModal, setShowImportModal, currentUser, setCurrentUser, logout 
  } = useStore();

   const { addToast } = useToastStore();

    useEffect(() => {
      if (currentUser) {
        fetchSpaces();
        fetchTasks();
        fetchBugs();
      }
    }, [currentUser]);
   // Re-fetch data when user manually switches spaces
   useEffect(() => {
     if (currentSpaceId) {
       fetchData();
     }
   }, [currentSpaceId]);

   // Ref to track handled deep links
   const handledRef = React.useRef<string | null>(null);

   // Handle deep linking via URL parameters
   useEffect(() => {
     const params = new URLSearchParams(window.location.search);
     const planId = params.get('plan_id');
     const view = params.get('view');
     
     if (view === 'execution' && planId) {
       if (handledRef.current === planId) return;

       const { testTasks, setSelectedTaskId } = useStore.getState();
       const task = testTasks.find(t => t.planId === planId);
       if (task) {
         setSelectedTaskId(task.id);
         setViewMode('execution');
         handledRef.current = planId;
         
         // Clear URL parameters after successful jump
         const newUrl = window.location.pathname;
         window.history.replaceState({}, '', newUrl);
       } else {
         // If tasks are still loading, don't clear yet, wait for next testTasks update
         setViewMode('execution');
       }
     } else if (view && !handledRef.current) {
       setViewMode(view as any);
       handledRef.current = 'mode-only';
       const newUrl = window.location.pathname;
       window.history.replaceState({}, '', newUrl);
     }
   }, [testTasks]);






   if (!currentUser) {
     return <LoginPage onLogin={(user) => setCurrentUser(user)} />;
   }
 
   return (
     <div className="app-container">
       <ToastContainer />
       {showImportModal && <ImportModal onClose={() => setShowImportModal(false)} />}
       <main className="content-area">
         {/* Main Navigation Sidebar */}
         <Sidebar />
 
         <div className="main-content-wrapper">
           {/* Header is now inside main content wrapper so sidebar can be full height */}
           <header className="main-header glass">
             <div className="header-left">
               <div className="logo" style={{ color: 'var(--primary)', fontWeight: 800, fontSize: '20px', display: 'flex', alignItems: 'center', gap: '8px' }}>
                 <div className="logo-icon" style={{ 
                   width: '32px', height: '32px', 
                   background: 'linear-gradient(135deg, #FF4D4D, #FF8D4D)', 
                   color: 'white', borderRadius: '50%', 
                   display: 'flex', alignItems: 'center', justifyContent: 'center', 
                   fontSize: '18px', fontWeight: 900,
                   boxShadow: '0 4px 10px rgba(255, 77, 77, 0.3)'
                 }}>D</div>
                 <span style={{ letterSpacing: '0.5px' }}>D-Case</span>
               </div>
             </div>

 
              <div className="header-right">
                <div className="user-info-chip">
                  <div className="user-avatar-sm">{currentUser.name.slice(-1)}</div>
                  <span className="user-name-text">{currentUser.name}</span>
                  <button className="logout-btn" onClick={() => { logout(); addToast('已退出登录', 'info'); }} title="退出">
                    <LogOut size={14} />
                  </button>
                </div>

              </div>
           </header>

          <div className="editor-container-wrapper">
            {/* Dynamic Content Area based on Sidebar selection */}
            <section className="editor-container">
              {viewMode === 'table' && <TableView />}
              {viewMode === 'dashboard' && <DashboardView />}
              {viewMode === 'bugs' && <BugView />}
              {viewMode === 'execution' && <TaskExecutionView />}
              {viewMode === 'plans' && <PlanListView />}
            </section>


            {(viewMode === 'table' || viewMode === 'execution') && <PropertyPanel />}


          </div>
        </div>
      </main>








      <style>{`
        .app-container {
          display: flex;
          flex-direction: column;
          height: 100vh;
        }

        .main-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0 24px;
          height: 56px;
          border-bottom: 1px solid var(--border-color);
          background: white;
          z-index: 10;
        }

        .header-left, .header-right {
          display: flex;
          align-items: center;
          gap: 20px;
        }

        .user-info-chip {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 4px 10px 4px 6px;
          background: #F2F3F5;
          border-radius: 20px;
          border: 1px solid #E5E6EB;
        }
        .user-avatar-sm {
          width: 26px; height: 26px;
          background: linear-gradient(135deg, #165DFF, #36ABFF);
          color: white;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 12px;
          font-weight: 600;
        }
        .user-name-text {
          font-size: 13px;
          font-weight: 500;
          color: #1D2129;
        }
        .logout-btn {
          background: none;
          border: none;
          cursor: pointer;
          color: #86909C;
          display: flex;
          align-items: center;
          padding: 2px;
          border-radius: 4px;
          transition: color 0.15s;
        }
        .logout-btn:hover { color: #F53F3F; }

        .logo {
          display: flex;
          align-items: center;
          gap: 10px;
          font-weight: 700;
          font-size: 18px;
          color: var(--primary);
        }

        .logo-icon {
          width: 32px;
          height: 32px;
          background: var(--primary);
          color: white;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 8px;
        }

        .project-switcher {
          margin-left: 32px;
        }
        .proj-select {
          padding: 6px 12px;
          border-radius: 6px;
          border: 1px solid var(--border-color);
          background: #F8F9FA;
          font-weight: 500;
          color: #1D2129;
          outline: none;
        }

        .search-bar {

          display: flex;
          align-items: center;
          gap: 8px;
          background: #F1F3F5;
          padding: 8px 12px;
          border-radius: 8px;
          color: var(--text-secondary);
        }

        .search-bar input {
          border: none;
          background: transparent;
          outline: none;
          font-size: 14px;
          width: 180px;
        }

        .btn-lark {
          background: #E8FFFB;
          color: #00B42A;
          border: 1px solid #AFF0B5;
          padding: 8px 16px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          gap: 8px;
          cursor: pointer;
          font-weight: 500;
          transition: var(--transition-base);
        }

        .btn-lark:active {
          transform: scale(0.96);
          background: #D9F5E8;
        }

        .btn-secondary {
          background: white;
          color: var(--text-primary);
          border: 1px solid var(--border-color);
          padding: 8px 16px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          gap: 8px;
          cursor: pointer;
          font-weight: 500;
          transition: var(--transition-base);
        }
        .btn-secondary:hover {
          background: #F1F3F5;
        }
        .btn-secondary:active {
          transform: scale(0.96);
          background: #E5E6EB;
        }

        .btn-primary {
          background: var(--primary);
          color: white;
          border: none;
          padding: 8px 16px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          gap: 8px;
          cursor: pointer;
          font-weight: 500;
          transition: var(--transition-base);
        }
        .btn-primary:active {
          transform: scale(0.96);
        }

        .user-avatar {
          width: 36px;
          height: 36px;
          background: #FF7D00;
          color: white;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: 600;
          cursor: pointer;
          transition: var(--transition-base);
        }
        .user-avatar:hover {
          box-shadow: 0 0 0 4px rgba(255, 125, 0, 0.2);
        }
        .user-avatar:active {
          transform: scale(0.9);
        }

        .main-content-wrapper {
          flex: 1;
          display: flex;
          flex-direction: column;
          overflow: hidden;
          background: #F8FAFC;
        }

        .editor-container-wrapper {

          flex: 1;
          display: flex;
          position: relative;
          overflow: hidden;
        }

        .editor-container {
          flex: 1;
          position: relative;
          overflow: hidden;
        }

        .content-area {
          flex: 1;
          display: flex;
          overflow: hidden;
        }

        .sidebar {
          width: 240px;
          border-right: 1px solid var(--border-color);
          background: white;
          padding: 20px;
        }

        .section-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          color: var(--text-secondary);
          font-size: 12px;
          text-transform: uppercase;
          letter-spacing: 0.5px;
          margin-bottom: 12px;
        }

        .project-list {
          list-style: none;
        }

        .project-list li {
          padding: 10px 12px;
          border-radius: 8px;
          cursor: pointer;
          font-size: 14px;
          margin-bottom: 4px;
          transition: var(--transition-base);
        }

        .project-list li.active {
          background: #E8F4FF;
          color: var(--primary);
          font-weight: 500;
        }

        .project-list li:hover:not(.active) {
          background: #F1F3F5;
        }

        .editor-container {
          flex: 1;
          background: var(--bg-main);
          position: relative;
        }

        .placeholder-view {
          height: 100%;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          color: var(--text-secondary);
        }
      `}</style>
    </div>
  );
};

export default App;
