import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { SingleTaskView, FiveMinuteStarter } from '@/components/adhd';
import { Task } from '@shared/schema';
import { Focus, ArrowLeft, Timer } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useLocation } from 'wouter';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

export default function SingleTaskPage() {
  const { t } = useTranslation();
  const [, setLocation] = useLocation();
  const queryClient = useQueryClient();
  const [selectedTaskId, setSelectedTaskId] = useState<string | null>(null);
  const [showFiveMinStarter, setShowFiveMinStarter] = useState(false);

  const { data: tasks = [] } = useQuery<Task[]>({
    queryKey: ['/api/tasks'],
  });

  const activeTasks = tasks.filter(t => t.status !== 'done');
  const selectedTask = selectedTaskId ? tasks.find(t => t.id === selectedTaskId) : null;

  const handleTaskComplete = async (taskId: string) => {
    await fetch(`/api/tasks/${taskId}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ status: 'done' }),
    });
    queryClient.invalidateQueries({ queryKey: ['/api/tasks'] });
    setSelectedTaskId(null);
  };

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

  const handleFiveMinComplete = () => {
    setShowFiveMinStarter(false);
    // Continue with the task
  };

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      <div className="flex items-center gap-3 sm:gap-4 mb-6">
        <Button
          variant="ghost"
          size="icon"
          onClick={() => window.history.back()}
          className="shrink-0"
        >
          <ArrowLeft className="h-5 w-5" />
        </Button>
        <div className="flex items-center gap-2 sm:gap-3 min-w-0">
          <div className="p-2 sm:p-3 rounded-xl bg-gradient-to-br from-blue-400 to-indigo-500 text-white shrink-0">
            <Focus className="h-5 w-5 sm:h-6 sm:w-6" />
          </div>
          <div className="min-w-0">
            <h1 className="text-xl sm:text-2xl font-bold">{t('adhd.singleTask.title')}</h1>
            <p className="text-sm sm:text-base text-muted-foreground">{t('adhd.singleTask.description')}</p>
          </div>
        </div>
      </div>

      {!selectedTask ? (
        <div className="bg-gradient-to-br from-blue-50 to-indigo-50 dark:from-blue-950/20 dark:to-indigo-950/20 rounded-2xl p-8 border border-blue-200 dark:border-blue-800">
          <h2 className="text-lg font-semibold mb-4">{t('adhd.singleTask.selectTask', 'Select a task to focus on')}</h2>
          <Select value={selectedTaskId || ''} onValueChange={setSelectedTaskId}>
            <SelectTrigger className="w-full">
              <SelectValue placeholder={t('adhd.singleTask.choosePlaceholder', 'Choose a task...')} />
            </SelectTrigger>
            <SelectContent>
              {activeTasks.map(task => (
                <SelectItem key={task.id} value={task.id}>
                  {task.title}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          <div className="mt-6 flex gap-3">
            <Button
              variant="outline"
              onClick={() => setShowFiveMinStarter(true)}
              className="flex items-center gap-2"
            >
              <Timer className="h-4 w-4" />
              {t('adhd.fiveMin.title')}
            </Button>
          </div>
        </div>
      ) : (
        <SingleTaskView
          onExit={() => setSelectedTaskId(null)}
        />
      )}

      {showFiveMinStarter && selectedTask && (
        <FiveMinuteStarter
          task={selectedTask}
          onComplete={handleFiveMinComplete}
          onClose={() => setShowFiveMinStarter(false)}
        />
      )}
    </div>
  );
}
