"use client";

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

interface Task {
  id: number;
  headline: string;
  description: string;
  projectName: string;
  status: number;
  dateToFinish: string;
  editorId: string;
  editorFirstname: string | null;
  editorLastname: string | null;
}

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 1: return 'New';
      case 2: return 'Ready';
      case 3: return 'In Progress';
      case 4: return 'Review';
      case 5: return 'Done';
      default: return 'Unknown';
    }
  };

  const getStatusColor = (status: number): string => {
    switch (status) {
      case 1: return 'bg-blue-500';
      case 2: return 'bg-green-500';
      case 3: return 'bg-yellow-500';
      case 4: return 'bg-purple-500';
      case 5: return 'bg-gray-500';
      default: return 'bg-gray-300';
    }
  };

  const formatDate = (dateStr: string): string => {
    if (!dateStr || dateStr === '0000-00-00 00:00:00') return '';
    try {
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return '';
      return date.toLocaleDateString('fr-FR', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric'
      });
    } catch {
      return '';
    }
  };

  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();
      console.log('Tasks API response:', data);

      if (!data.tasks || !Array.isArray(data.tasks)) {
        console.warn('No tasks found in response:', data);
        setTasks([]);
        return;
      }

      // Sort tasks by status and date
      const sortedTasks = data.tasks
        .filter((task: Task) => 
          task.headline && 
          typeof task.headline === 'string' &&
          task.status !== 5 && // Not done
          task.editorId === '2' // Only tasks assigned to user 2
        )
        .sort((a: Task, b: Task) => {
          // Get valid dates for comparison
          const getValidDate = (task: Task) => {
            if (task.dateToFinish && task.dateToFinish !== '0000-00-00 00:00:00') {
              return new Date(task.dateToFinish).getTime();
            }
            return Number.MAX_SAFE_INTEGER; // Put tasks without due date at the end
          };

          const dateA = getValidDate(a);
          const dateB = getValidDate(b);

          // Sort by date first
          if (dateA !== dateB) {
            return dateA - dateB;
          }

          // If dates are equal, sort by status
          return a.status - b.status;
        });

      console.log('Filtered and sorted tasks:', sortedTasks);
      setTasks(sortedTasks);
      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 bg-white/50 backdrop-blur-sm">
      <CardHeader className="flex flex-row items-center justify-between pb-2">
        <CardTitle className="text-xl font-bold">Flow</CardTitle>
        <Button 
          variant="ghost" 
          size="icon" 
          onClick={() => fetchTasks(true)}
          className="h-8 w-8 p-0 hover:bg-gray-100 rounded-full"
        >
          <RefreshCw className="h-4 w-4" />
        </Button>
      </CardHeader>
      <CardContent className="space-y-4">
        {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-sm text-red-500">{error}</div>
        ) : tasks.length === 0 ? (
          <div className="text-sm text-muted-foreground text-center">No tasks found</div>
        ) : (
          <div className="space-y-3">
            {tasks.map((task) => (
              <div 
                key={task.id}
                className="p-4 rounded-lg border border-gray-100 hover:border-gray-200 transition-all duration-200 bg-white/70"
              >
                <div className="space-y-2.5">
                  <a 
                    href={`https://agilite.slm-lab.net/tickets/showTicket/${task.id}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-blue-600 hover:text-blue-700 font-medium block text-base"
                  >
                    {task.headline}
                  </a>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center text-gray-500">
                      <Folder className="h-4 w-4 mr-1.5 opacity-70" />
                      <span className="text-sm font-medium">{task.projectName}</span>
                    </div>
                    <Badge 
                      variant="secondary" 
                      className="text-xs font-medium bg-gray-100 text-gray-600 hover:bg-gray-200"
                    >
                      Unknown
                    </Badge>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
}