"use client";

import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { RefreshCw } from "lucide-react";
import { formatDate } from "@/lib/utils";

interface Task {
  id: string;
  headline: string;
  projectName: string;
  status: string;
  dueDate: string | null;
  details?: string;
  milestone?: string;
}

export function Flow() {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [retryTimeout, setRetryTimeout] = useState<NodeJS.Timeout | null>(null);

  const fetchTasks = async (isRefresh = false) => {
    try {
      if (isRefresh) {
        setRefreshing(true);
      }
      const response = await fetch('/api/leantime/status-labels');
      
      if (response.status === 429) {
        const retryAfter = parseInt(response.headers.get('retry-after') || '60');
        const timeout = setTimeout(() => fetchTasks(), retryAfter * 1000);
        setRetryTimeout(timeout);
        setError(`Rate limit exceeded. Retrying in ${retryAfter} seconds...`);
        return;
      }

      if (!response.ok) {
        throw new Error('Failed to fetch tasks');
      }

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

  useEffect(() => {
    fetchTasks();
    return () => {
      if (retryTimeout) {
        clearTimeout(retryTimeout);
      }
    };
  }, []);

  const getStatusColor = (status: string) => {
    switch (status.toLowerCase()) {
      case 'new':
        return 'text-blue-600';
      case 'blocked':
        return 'text-red-600';
      case 'in progress':
      case 'inprogress':
        return 'text-orange-600';
      case 'done':
      case 'archived':
        return 'text-green-600';
      case 'waiting for approval':
        return 'text-yellow-600';
      default:
        return 'text-gray-600';
    }
  };

  // Group tasks by project
  const groupedTasks = tasks.reduce((acc, task) => {
    if (!acc[task.projectName]) {
      acc[task.projectName] = [];
    }
    acc[task.projectName].push(task);
    return acc;
  }, {} as Record<string, Task[]>);

  return (
    <Card className="transition-transform duration-500 ease-in-out transform hover:scale-105">
      <CardHeader className="flex flex-row items-center justify-between pb-2">
        <CardTitle className="text-lg font-medium">Flow</CardTitle>
        <Button
          variant="ghost"
          size="icon"
          onClick={() => fetchTasks(true)}
          disabled={refreshing || !!retryTimeout}
          className={refreshing ? 'animate-spin' : ''}
        >
          <RefreshCw className="h-4 w-4" />
        </Button>
      </CardHeader>
      <CardContent>
        {loading ? (
          <div className="flex items-center justify-center py-4">
            <div className="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent" />
          </div>
        ) : error ? (
          <div className="text-center text-sm text-red-500">{error}</div>
        ) : Object.keys(groupedTasks).length === 0 ? (
          <div className="text-center text-sm text-gray-500">No tasks found</div>
        ) : (
          <div className="space-y-6">
            {Object.entries(groupedTasks).map(([projectName, projectTasks]) => (
              <div key={projectName} className="space-y-2">
                <h3 className="font-medium text-sm">{projectName}</h3>
                <div className="space-y-2">
                  {projectTasks.map((task) => (
                    <div key={task.id} className="flex justify-between items-start text-sm border-b border-gray-100 pb-2">
                      <div className="flex-1">
                        <div className="font-medium">{task.headline}</div>
                        {task.milestone && (
                          <div className="text-xs text-gray-500 mt-1">
                            {task.milestone}
                          </div>
                        )}
                        {task.dueDate && (
                          <div className="text-xs text-gray-500 mt-1">
                            {formatDate(task.dueDate)}
                          </div>
                        )}
                      </div>
                      <div className={`ml-4 ${getStatusColor(task.status)}`}>
                        {task.status.toUpperCase()}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
}