"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;
  date: string;
  editFrom: string;
  editTo: string;
  authorFirstname?: string;
  authorLastname?: string;
  tags?: string;
}

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

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 getStatusLabel = (status: number): string => {
    switch (status) {
      case 3:
        return 'NEW';
      case 1:
      case 4:
        return 'INPROGRESS';
      case 2:
      case 5:
        return 'DONE';
      default:
        return 'UNKNOWN';
    }
  };

  const getStatusColor = (status: number): string => {
    const statusLabel = getStatusLabel(status);
    switch (statusLabel) {
      case 'DONE':
        return 'bg-green-100 text-green-800';
      case 'INPROGRESS':
        return 'bg-yellow-100 text-yellow-800';
      case 'NEW':
        return 'bg-gray-100 text-gray-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  const getDateToSort = (task: Task): number => {
    // Try different date fields in order of preference
    const dates = [
      task.date,
      task.dateToFinish,
      task.editFrom,
      task.editTo
    ].filter(date => date && date !== '0000-00-00 00:00:00');
    
    return dates.length > 0 ? new Date(dates[0]).getTime() : 0;
  };

  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)) {
        setTasks([]);
        return;
      }

      // Sort tasks by date (oldest first)
      const sortedTasks = data.tasks.sort((a: Task, b: Task) => {
        return getDateToSort(a) - getDateToSort(b);
      });

      // Limit to 6 tasks
      setTasks(sortedTasks.slice(0, 6));
      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>
        ) : tasks.length === 0 ? (
          <div className="text-center text-sm text-gray-500">No tasks found</div>
        ) : (
          <div className="space-y-3">
            {tasks.map((task) => (
              <div key={task.id} className="flex items-start space-x-2 p-2 rounded-lg bg-white/50 backdrop-blur-sm shadow-sm hover:bg-white/60 transition-colors">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center justify-between gap-2">
                    <h3 className="text-sm font-medium truncate" title={task.headline}>
                      {task.headline}
                    </h3>
                    <span className={`px-2 py-1 rounded-full text-xs font-medium whitespace-nowrap ${getStatusColor(task.status)}`}>
                      {getStatusLabel(task.status)}
                    </span>
                  </div>
                  <div className="flex items-center justify-between mt-1">
                    <p className="text-xs text-gray-500 truncate">
                      {task.projectName}
                    </p>
                    {task.tags && (
                      <p className="text-xs text-blue-500 truncate">
                        {task.tags}
                      </p>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
}