"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";

interface Task {
  id: string;
  headline: string;
  projectName: string;
  projectId: number;
  status: number;
  type: string;
  dateToFinish: string | null;
}

interface ProjectSummary {
  name: string;
  tasks: {
    status: number;
    count: number;
  }[];
}

export function Flow() {
  const [projects, setProjects] = useState<ProjectSummary[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  const getStatusLabel = (status: number): string => {
    switch (status) {
      case 1:
        return 'NEW';
      case 2:
        return 'INPROGRESS';
      case 3:
        return 'DONE';
      default:
        return 'UNKNOWN';
    }
  };

  const fetchTasks = async (isRefresh = false) => {
    try {
      if (isRefresh) setRefreshing(true);
      
      const response = await fetch('/api/leantime/tasks');
      if (!response.ok) throw new Error('Failed to fetch tasks');

      const data = await response.json();
      if (!data.tasks || !Array.isArray(data.tasks)) {
        setProjects([]);
        return;
      }

      // Group tasks by project and count statuses
      const projectMap = new Map<string, Map<number, number>>();
      
      data.tasks.forEach((task: Task) => {
        if (!projectMap.has(task.projectName)) {
          projectMap.set(task.projectName, new Map());
        }
        const statusMap = projectMap.get(task.projectName)!;
        statusMap.set(task.status, (statusMap.get(task.status) || 0) + 1);
      });

      // Convert to array format
      const projectSummaries: ProjectSummary[] = Array.from(projectMap.entries())
        .map(([name, statusMap]) => ({
          name,
          tasks: Array.from(statusMap.entries()).map(([status, count]) => ({
            status,
            count
          }))
        }));

      setProjects(projectSummaries);
      setError(null);
    } catch (err) {
      console.error('Error fetching tasks:', err);
      setError('Failed to fetch tasks');
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    fetchTasks();
  }, []);

  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}
          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>
        ) : projects.length === 0 ? (
          <div className="text-center text-sm text-gray-500">No tasks found</div>
        ) : (
          <div className="space-y-6">
            {projects.map((project) => (
              <div key={project.name} className="space-y-2">
                <h3 className="text-xl font-medium">{project.name}</h3>
                <div className="space-y-2">
                  {project.tasks.map(({ status, count }) => (
                    <div key={status} className="flex items-center justify-between p-2 rounded-lg bg-white shadow-sm">
                      <span className="text-lg font-medium">{count}</span>
                      <span className={`px-3 py-1 rounded-full text-sm font-medium ${
                        status === 3 ? 'bg-green-100 text-green-800' :
                        status === 2 ? 'bg-yellow-100 text-yellow-800' :
                        'bg-gray-100 text-gray-800'
                      }`}>
                        {getStatusLabel(status)}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
}