"use client";

import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { RefreshCw, Calendar, CheckCircle2, Clock } from "lucide-react";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";

interface Task {
  id: string;
  headline: string;
  description: string;
  status: string;
  dueDate: string;
  priority: number;
}

export function Flow() {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [refreshing, setRefreshing] = useState(false);
  const router = useRouter();
  const { data: session } = useSession();

  const fetchTasks = async (isRefresh = false) => {
    try {
      if (isRefresh) {
        setRefreshing(true);
      }
      const response = await fetch('/api/leantime/tasks', {
        cache: 'no-store',
        next: { revalidate: 0 },
      });
      
      if (response.status === 401) {
        setError('Session expired. Please sign in again.');
        return;
      }

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to fetch tasks');
      }

      const data = await response.json();
      setTasks(data.tasks);
      setError(null);
    } catch (err) {
      console.error('Error fetching tasks:', err);
      const errorMessage = err instanceof Error ? err.message : 'Failed to fetch tasks';
      setError(errorMessage);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    if (session) {
      fetchTasks();
      // Set up polling every 5 minutes
      const interval = setInterval(() => fetchTasks(), 300000);
      return () => clearInterval(interval);
    }
  }, [session]);

  const getPriorityColor = (priority: number) => {
    switch (priority) {
      case 1:
        return 'text-red-500';
      case 2:
        return 'text-yellow-500';
      case 3:
        return 'text-green-500';
      default:
        return 'text-gray-500';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status.toLowerCase()) {
      case 'done':
        return <CheckCircle2 className="h-4 w-4 text-green-500" />;
      case 'in progress':
        return <Clock className="h-4 w-4 text-yellow-500" />;
      default:
        return <Calendar className="h-4 w-4 text-blue-500" />;
    }
  };

  return (
    <Card 
      className="transition-transform duration-500 ease-in-out transform hover:scale-105 cursor-pointer bg-white/50 backdrop-blur-sm h-full" 
      onClick={() => router.push('/flow')}
    >
      <CardHeader className="flex flex-row items-center justify-between pb-2">
        <CardTitle className="text-lg font-semibold">My Tasks</CardTitle>
        <Button 
          variant="ghost" 
          size="icon"
          onClick={(e) => {
            e.stopPropagation();
            fetchTasks(true);
          }}
          disabled={refreshing}
          className={refreshing ? 'animate-spin' : ''}
        >
          <RefreshCw className="h-4 w-4" />
        </Button>
      </CardHeader>
      <CardContent className="p-4">
        {loading && <p className="text-center text-muted-foreground">Loading tasks...</p>}
        {error && (
          <div className="text-center">
            <p className="text-red-500">Error: {error}</p>
            <Button 
              variant="outline" 
              onClick={(e) => {
                e.stopPropagation();
                fetchTasks(true);
              }}
              className="mt-2"
            >
              Try Again
            </Button>
          </div>
        )}
        {!loading && !error && (
          <div className="space-y-2 max-h-[300px] overflow-y-auto">
            {tasks.length === 0 ? (
              <p className="text-center text-muted-foreground">No tasks found</p>
            ) : (
              tasks.map((task) => (
                <div 
                  key={task.id} 
                  className="flex items-start space-x-2 hover:bg-gray-50 p-2 rounded-lg transition-colors"
                >
                  <div className="flex-shrink-0">
                    {getStatusIcon(task.status)}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-baseline justify-between">
                      <p className="text-sm font-medium truncate">{task.headline}</p>
                      <span className={`text-xs ${getPriorityColor(task.priority)}`}>
                        {task.priority === 1 ? 'High' : task.priority === 2 ? 'Medium' : 'Low'}
                      </span>
                    </div>
                    <p className="text-xs text-gray-600 line-clamp-2">{task.description}</p>
                    {task.dueDate && (
                      <p className="text-xs text-gray-500 mt-1">
                        Due: {new Date(task.dueDate).toLocaleDateString()}
                      </p>
                    )}
                  </div>
                </div>
              ))
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
} 