import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
import { Button } from "@/components/ui/button";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";

import { Switch, Route, useLocation } from "wouter";

// Components
import TaskCreationModal from './components/TaskCreationModal';
import TaskDetailsModal from './components/TaskDetailsModal';
import TasksWithCalendar from './components/TasksWithCalendar';
import FocusMode from './components/FocusMode';
import CalendarView from './components/CalendarView';
import KanbanBoard from './components/KanbanBoard';
import ProjectTemplate from './components/ProjectTemplate';
import WeekListView from './components/WeekListView';
import Settings from './pages/settings';
import AchievementsPage from './pages/AchievementsPage';
import { Task, Label } from '@shared/schema';
import { useTimer } from './hooks/useTimer';

import { Plus } from 'lucide-react';
import { SidebarProvider, SidebarInset, SidebarTrigger } from "@/components/ui/sidebar"
import { AppSidebar } from "./components/AppSidebar"
import { CommandPalette } from './components/CommandPalette';
import PomodoroOverlay from './components/PomodoroOverlay';
import AuthPage from "@/pages/AuthPage";

import LeaderboardPage from "@/pages/LeaderboardPage";
import SetupWizard from "@/pages/SetupWizard";
import AdminUserManagement from "@/pages/AdminUserManagement";
import AdminSettings from "@/pages/AdminSettings";
import NotFound from "@/pages/not-found";
import { AiChat } from "@/components/AiChat";
import ForgotPasswordPage from "@/pages/ForgotPasswordPage";
import ResetPasswordPage from "@/pages/ResetPasswordPage";

import { useQuery } from "@tanstack/react-query";
import { User } from "@shared/schema";
import { Loader2 } from "lucide-react";

function App() {
  const { t } = useTranslation();
  const [, setLocation] = useLocation();
  const [tasks, setTasks] = useState<Task[]>([]);
  const [labels, setLabels] = useState<Label[]>([]);
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [isTaskDetailsOpen, setIsTaskDetailsOpen] = useState(false);
  const [selectedTask, setSelectedTask] = useState<Task | null>(null);
  const [deleteTaskId, setDeleteTaskId] = useState<string | null>(null);
  const [showPomodoro, setShowPomodoro] = useState(false);
  const [activePomodoroTaskId, setActivePomodoroTaskId] = useState<string | null>(null);

  const { data: user, isLoading: isLoadingUser } = useQuery<User>({
    queryKey: ["/api/user"],
    retry: false,
  });

  const { data: setupStatus } = useQuery<{ isSetup: boolean }>({
    queryKey: ['/api/setup/status'],
  });

  // Fetch tasks and labels
  useEffect(() => {
    if (!user) return;
    const fetchData = async () => {
      try {
        const tasksResponse = await fetch('/api/tasks');
        if (tasksResponse.ok) {
          const serverTasks: Task[] = await tasksResponse.json();
          const normalizedTasks = serverTasks.map(task => ({
            ...task,
            dueDate: task.dueDate ? new Date(task.dueDate) : null
          }));
          setTasks(normalizedTasks);
        }

        const labelsResponse = await fetch('/api/labels');
        if (labelsResponse.ok) {
          const serverLabels: Label[] = await labelsResponse.json();
          setLabels(serverLabels);
        }
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };
    fetchData();
  }, [user]);

  const handleCreateTask = async (newTask: Partial<Task>) => {
    try {
      const response = await fetch('/api/tasks', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title: newTask.title || '',
          description: newTask.description || null,
          status: 'todo',
          priority: newTask.priority || 'medium',
          dueDate: newTask.dueDate || null,
          timeTracked: 0,
          isTracking: false,
          projectId: newTask.projectId || null,
          notes: newTask.notes || null,
          labelId: newTask.labelId || null,
          energyLevel: newTask.energyLevel || 'medium',
          estimatedDuration: newTask.estimatedDuration || null
        })
      });

      if (!response.ok) throw new Error('Failed to create task');

      const createdTask: Task = await response.json();
      const normalizedTask = {
        ...createdTask,
        dueDate: createdTask.dueDate ? new Date(createdTask.dueDate) : null
      };
      setTasks(prev => [...prev, normalizedTask]);
    } catch (error) {
      console.error('Error creating task:', error);
    }
  };

  const handleTaskUpdate = async (taskId: string, updates: Partial<Task>) => {
    try {
      const response = await fetch(`/api/tasks/${taskId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updates)
      });

      if (!response.ok) throw new Error('Failed to update task');

      const updatedTask: Task = await response.json();
      const normalizedTask = {
        ...updatedTask,
        dueDate: updatedTask.dueDate ? new Date(updatedTask.dueDate) : null
      };
      setTasks(prev => prev.map(task => task.id === taskId ? normalizedTask : task));
    } catch (error) {
      console.error('Error updating task:', error);
      setTasks(prev => prev.map(task => task.id === taskId ? { ...task, ...updates } : task));
    }
  };

  const handleCreateFromTemplate = (templateId: string, startDate: Date, projectName: string) => {
    console.log('Creating project from template:', { templateId, startDate, projectName });
  };

  const { startTimer, stopTimer } = useTimer({
    tasks,
    onTaskUpdate: handleTaskUpdate
  });

  const handleStartPomodoro = (taskId: string) => {
    setActivePomodoroTaskId(taskId);
    setShowPomodoro(true);
    startTimer(taskId);
  };

  const handleTaskStatusChange = (taskId: string, newStatus: Task['status']) => {
    handleTaskUpdate(taskId, { status: newStatus });
  };

  const handleTaskDrop = (taskId: string, newDate: Date) => {
    handleTaskUpdate(taskId, { dueDate: newDate });
  };

  const handleTaskClick = (task: Task) => {
    setSelectedTask(task);
    setIsTaskDetailsOpen(true);
  };

  const handleTaskDetailsClose = () => {
    setIsTaskDetailsOpen(false);
    setSelectedTask(null);
  };

  const handleTaskDetailsSave = (updatedTask: Task) => {
    handleTaskUpdate(updatedTask.id, updatedTask);
  };

  const handleTaskDelete = async (taskId: string) => {
    setDeleteTaskId(taskId);
  };

  const confirmTaskDelete = async () => {
    if (!deleteTaskId) return;
    const taskToDelete = tasks.find(task => task.id === deleteTaskId);
    setTasks(prev => prev.filter(task => task.id !== deleteTaskId));

    if (selectedTask?.id === deleteTaskId) {
      handleTaskDetailsClose();
    }
    setDeleteTaskId(null);

    try {
      const response = await fetch(`/api/tasks/${deleteTaskId}`, { method: 'DELETE' });
      if (!response.ok && response.status !== 404) throw new Error('Failed to delete task');
    } catch (error) {
      console.error('Error deleting task:', error);
      if (taskToDelete) setTasks(prev => [...prev, taskToDelete]);
    }
  };

  if (isLoadingUser) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-background">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  // Setup Redirect
  if (setupStatus && !setupStatus.isSetup) {
    return (
      <Switch>
        <Route path="/setup" component={SetupWizard} />
        <Route component={() => <SetupWizard />} />
      </Switch>
    );
  }

  if (!user) {
    return (
      <Switch>
        <Route path="/forgot-password" component={ForgotPasswordPage} />
        <Route path="/reset-password" component={ResetPasswordPage} />
        <Route component={AuthPage} />
      </Switch>
    );
  }

  return (
    <TooltipProvider>
      <SidebarProvider>
        <AppSidebar user={user} />
        <SidebarInset>
          <div className="flex flex-col min-h-screen bg-background">
            {/* Mobile Header trigger */}
            <header className="flex h-16 shrink-0 items-center gap-2 border-b px-4 md:hidden">
              <SidebarTrigger className="-ml-1" />
              <div className="font-semibold">{t('app.title')}</div>
            </header>

            {/* Main Content */}
            <main className="flex-1 p-4 md:p-6 max-w-screen-2xl mx-auto w-full relative">
              <Switch>
                <Route path="/">
                  <FocusMode
                    tasks={tasks}
                    onTaskUpdate={handleTaskUpdate}
                    onTaskEdit={handleTaskClick}
                    onTaskDelete={handleTaskDelete}
                    onStartTimer={startTimer}
                    onStopTimer={stopTimer}
                    onNavigateToTasks={() => setLocation('/tasks')}
                  />
                </Route>
                <Route path="/tasks">
                  <TasksWithCalendar
                    tasks={tasks}
                    onTaskUpdate={handleTaskUpdate}
                    onTaskEdit={handleTaskClick}
                    onTaskDelete={handleTaskDelete}
                    onStartTimer={startTimer}
                    onStopTimer={stopTimer}
                  />
                </Route>
                <Route path="/calendar">
                  <CalendarView
                    tasks={tasks}
                    onTaskDrop={handleTaskDrop}
                    onTaskClick={handleTaskClick}
                    onDateSelect={(date) => console.log('Date selected:', date.toLocaleDateString())}
                    onTaskUpdate={handleTaskUpdate}
                    onTaskEdit={handleTaskClick}
                    onTaskDelete={handleTaskDelete}
                    onStartTimer={startTimer}
                    onStopTimer={stopTimer}
                  />
                </Route>
                <Route path="/kanban">
                  <KanbanBoard
                    tasks={tasks}
                    onTaskStatusChange={handleTaskStatusChange}
                    onTaskUpdate={handleTaskUpdate}
                    onTaskClick={handleTaskClick}
                    onTaskDelete={handleTaskDelete}
                    onStartTimer={startTimer}
                    onStopTimer={stopTimer}
                  />
                </Route>
                <Route path="/weeklist">
                  <WeekListView
                    tasks={tasks}
                    onTaskUpdate={handleTaskUpdate}
                    onTaskEdit={handleTaskClick}
                    onTaskDelete={handleTaskDelete}
                    onStartTimer={startTimer}
                    onStopTimer={stopTimer}
                  />
                </Route>
                <Route path="/templates">
                  <ProjectTemplate
                    onCreateFromTemplate={handleCreateFromTemplate}
                    onCreateTasks={(newTasks) => setTasks(prev => [...prev, ...newTasks])}
                    onNavigateToSettings={() => setLocation('/settings')}
                  />
                </Route>
                <Route path="/achievements">
                  <AchievementsPage user={user} />
                </Route>
                <Route path="/leaderboard">
                  <LeaderboardPage />
                </Route>
                <Route path="/settings">
                  <Settings onNavigateToTemplates={() => setLocation('/templates')} />
                </Route>

                {/* Admin Route */}
                {user.role === 'admin' && (
                  <>
                    <Route path="/admin/users" component={AdminUserManagement} />
                    <Route path="/admin/settings" component={AdminSettings} />
                  </>
                )}

                <Route component={NotFound} />
              </Switch>
            </main>

            {/* Floating Action Button */}
            <div className="fixed bottom-8 right-8 z-[100]">
              <Button
                size="icon"
                className="h-14 w-14 rounded-full shadow-2xl bg-gradient-to-r from-violet-600 to-indigo-600 hover:scale-110 transition-transform duration-200"
                onClick={() => setIsCreateModalOpen(true)}
                data-testid="fab-create-task"
              >
                <Plus className="h-6 w-6 text-white" />
              </Button>
            </div>
          </div>
        </SidebarInset>
      </SidebarProvider>

      <CommandPalette
        onNavigate={(path) => setLocation(path.startsWith('/') ? path : `/${path}`)}
        onCreateTask={() => setIsCreateModalOpen(true)}
      />

      <PomodoroOverlay
        isOpen={showPomodoro}
        onClose={() => setShowPomodoro(false)}
        taskId={activePomodoroTaskId}
        taskTitle={tasks.find(t => t.id === activePomodoroTaskId)?.title || 'Quick Focus'}
        onCompleteTask={(id) => handleTaskUpdate(id, { status: 'done', isTracking: false })}
      />

      <Toaster />
      {user?.aiEnabled && <AiChat />}

      <TaskCreationModal
        isOpen={isCreateModalOpen}
        onClose={() => setIsCreateModalOpen(false)}
        onSave={handleCreateTask}
      />

      <TaskDetailsModal
        isOpen={isTaskDetailsOpen}
        onClose={handleTaskDetailsClose}
        task={selectedTask}
        onSave={handleTaskDetailsSave}
        labels={labels}
      />

      <AlertDialog open={deleteTaskId !== null} onOpenChange={(open) => !open && setDeleteTaskId(null)}>
        <AlertDialogContent data-testid="dialog-delete-confirmation">
          <AlertDialogHeader>
            <AlertDialogTitle>{t('deleteConfirmation.title')}</AlertDialogTitle>
            <AlertDialogDescription>
              {t('deleteConfirmation.description')}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel data-testid="button-cancel-delete">
              {t('deleteConfirmation.cancel')}
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmTaskDelete}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              data-testid="button-confirm-delete"
            >
              {t('deleteConfirmation.confirm')}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </TooltipProvider>
  );
}

export default App;
