"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;
  dateToFinish: string | null;
  date: string | null;
  projectId: number;
  projectName: string;
  status: number;
  editorId?: string;
  editorFirstname?: string;
  editorLastname?: string;
  authorFirstname: string;
  authorLastname: string;
  milestoneHeadline?: string;
  editTo?: string;
  editFrom?: string;
}

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

interface TaskWithDate extends Task {
  validDate?: Date;
}

export function Flow() {
  const [tasks, setTasks] = useState<TaskWithDate[]>([]);
  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 getValidDate = (task: Task): string | null => {
    if (task.dateToFinish && task.dateToFinish !== '0000-00-00 00:00:00') {
      return task.dateToFinish;
    }
    return null;
  };

  const fetchTasks = async () => {
    setLoading(true);
    try {
      const response = await fetch('/api/leantime/tasks');
      const data = await response.json();
      
      if (!Array.isArray(data)) {
        console.warn('No tasks found in response');
        setTasks([]);
        return;
      }

      // Process tasks with valid dates
      const processedTasks = data.map((task: Task) => {
        const dateStr = getValidDate(task);
        return {
          ...task,
          validDate: dateStr ? new Date(dateStr) : undefined
        };
      });

      // Filter and sort tasks - include status 3 (In Progress)
      const sortedTasks = processedTasks
        .filter((task: TaskWithDate) => task.validDate) // Only keep tasks with valid dates
        .sort((a: TaskWithDate, b: TaskWithDate) => {
          if (!a.validDate || !b.validDate) return 0;
          return a.validDate.getTime() - b.validDate.getTime();
        });

      console.log('Number of tasks found:', sortedTasks.length);
      setTasks(sortedTasks.slice(0, 6));
    } catch (error) {
      console.error('Error fetching tasks');
      setError('Failed to fetch tasks');
    } finally {
      setLoading(false);
    }
  };

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

  // Update the TaskDate component to handle dates better
  const TaskDate = ({ task }: { task: TaskWithDate }) => {
    if (!task.validDate) {
      return (
        <>
          <span className="text-[10px] text-gray-600 font-medium">NO</span>
          <span className="text-sm text-gray-700 font-bold">DATE</span>
        </>
      );
    }

    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const isPastDue = task.validDate < today;

    try {
      const month = task.validDate.toLocaleString('fr-FR', { month: 'short' }).toUpperCase();
      const day = task.validDate.getDate();
      const year = task.validDate.getFullYear();
      
      return (
        <>
          <span className={`text-[10px] font-medium uppercase ${isPastDue ? 'text-red-600' : 'text-blue-600'}`}>
            {month}
          </span>
          <span className={`text-sm font-bold ${isPastDue ? 'text-red-700' : 'text-blue-700'}`}>
            {day}
          </span>
          <span className={`text-[8px] font-medium ${isPastDue ? 'text-red-600' : 'text-blue-600'}`}>
            {year}
          </span>
        </>
      );
    } catch (error) {
      console.error('Error formatting date for task', task.id);
      return (
        <>
          <span className="text-[10px] text-gray-600 font-medium">ERR</span>
          <span className="text-sm text-gray-700 font-bold">DATE</span>
        </>
      );
    }
  };

  return (
    <Card className="transition-transform duration-500 ease-in-out transform hover:scale-105 bg-white/95 backdrop-blur-sm border-0 shadow-lg">
      <CardHeader className="flex flex-row items-center justify-between pb-2 border-b border-gray-100 space-y-0 pt-3 px-3">
        <CardTitle className="text-lg font-semibold text-gray-800">Flow</CardTitle>
        <Button 
          variant="ghost" 
          size="icon" 
          onClick={() => fetchTasks()}
          className="h-6 w-6 p-0 hover:bg-gray-100/50 rounded-full"
        >
          <RefreshCw className="h-3 w-3 text-gray-600" />
        </Button>
      </CardHeader>
      <CardContent className="p-3">
        {loading ? (
          <div className="flex items-center justify-center py-6">
            <div className="h-4 w-4 animate-spin rounded-full border-2 border-blue-500 border-t-transparent" />
          </div>
        ) : error ? (
          <div className="text-xs text-red-500 text-center py-3">{error}</div>
        ) : tasks.length === 0 ? (
          <div className="text-xs text-gray-500 text-center py-6">No tasks with due dates found</div>
        ) : (
          <div className="space-y-2 max-h-[360px] overflow-y-auto pr-2 scrollbar-thin scrollbar-thumb-gray-200 scrollbar-track-transparent">
            {tasks.map((task) => (
              <div 
                key={task.id}
                className="p-2 rounded-lg bg-white shadow-sm hover:shadow-md transition-all duration-200 border border-gray-100"
              >
                <div className="flex gap-2">
                  <div className="flex-shrink-0 w-12 h-12 rounded-lg bg-blue-50 flex flex-col items-center justify-center border border-blue-100">
                    <TaskDate task={task} />
                  </div>
                  <div className="flex-1 min-w-0 space-y-1">
                    <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-sm line-clamp-2"
                    >
                      {task.headline}
                    </a>
                    <div className="flex items-center text-gray-500 text-[10px] bg-gray-50 px-1.5 py-0.5 rounded-md">
                      <Folder className="h-2.5 w-2.5 mr-1 opacity-70" />
                      <span className="truncate">{task.projectName}</span>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
}