"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;
  date: string;
  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 fetchTasks = async () => {
    setLoading(true);
    try {
      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)) {
        console.warn('No tasks found in response', data as unknown);
        setTasks([]);
        return;
      }

      // Debug log to see all tasks and their dates
      data.tasks.forEach((task: Task) => {
        console.log(`Task ${task.id} - ${task.headline} - Full data:`, {
          id: task.id,
          headline: task.headline,
          dateToFinish: task.dateToFinish,
          editTo: task.editTo,
          editFrom: task.editFrom,
          date: task.date,
          status: task.status,
          type: typeof task.dateToFinish
        });
      });

      const getValidDate = (task: Task): Date | undefined => {
        const tryParseDate = (dateStr: string | undefined, fieldName: string): Date | undefined => {
          if (!dateStr) {
            console.log(`${fieldName} for task ${task.id} is empty`);
            return undefined;
          }
          
          if (dateStr === '0000-00-00 00:00:00') {
            console.log(`${fieldName} for task ${task.id} is zero date`);
            return undefined;
          }

          try {
            const date = new Date(dateStr);
            if (isNaN(date.getTime())) {
              console.log(`${fieldName} for task ${task.id} parsed to invalid date:`, dateStr);
              return undefined;
            }
            
            console.log(`Successfully parsed ${fieldName} for task ${task.id}:`, {
              input: dateStr,
              output: date.toISOString(),
              timestamp: date.getTime()
            });
            return date;
          } catch (error) {
            console.error(`Error parsing ${fieldName} for task ${task.id}:`, error);
            return undefined;
          }
        };

        // Try each date field in order of priority
        const dateToFinish = tryParseDate(task.dateToFinish, 'dateToFinish');
        if (dateToFinish) {
          console.log(`Using dateToFinish for task ${task.id}:`, dateToFinish.toISOString());
          return dateToFinish;
        }
        
        const editTo = tryParseDate(task.editTo, 'editTo');
        if (editTo) {
          console.log(`Using editTo for task ${task.id}:`, editTo.toISOString());
          return editTo;
        }
        
        const editFrom = tryParseDate(task.editFrom, 'editFrom');
        if (editFrom) {
          console.log(`Using editFrom for task ${task.id}:`, editFrom.toISOString());
          return editFrom;
        }
        
        const date = tryParseDate(task.date, 'date');
        if (date) {
          console.log(`Using date for task ${task.id}:`, date.toISOString());
          return date;
        }

        console.log(`No valid date found for task ${task.id} - Raw values:`, {
          dateToFinish: task.dateToFinish,
          editTo: task.editTo,
          editFrom: task.editFrom,
          date: task.date
        });
        return undefined;
      };

      // Process and sort tasks
      const processedTasks = data.tasks.map((task: Task): TaskWithDate => {
        const validDate = getValidDate(task);
        console.log(`Final date for task ${task.id}:`, {
          headline: task.headline,
          validDate: validDate?.toISOString() || 'NO DATE',
          rawDateToFinish: task.dateToFinish
        });
        return { ...task, validDate };
      });

      // Sort tasks
      const sortedTasks = processedTasks.sort((a: TaskWithDate, b: TaskWithDate) => {
        if (a.validDate && b.validDate) {
          return a.validDate.getTime() - b.validDate.getTime();
        }
        if (!a.validDate && !b.validDate) {
          return b.id - a.id;
        }
        return a.validDate ? -1 : 1;
      });

      console.log('Final sorted tasks:', sortedTasks.map((t: TaskWithDate) => ({
        id: t.id,
        headline: t.headline,
        validDate: t.validDate?.toISOString(),
        rawDates: {
          dateToFinish: t.dateToFinish,
          editTo: t.editTo,
          editFrom: t.editFrom,
          date: t.date
        }
      })));

      setTasks(sortedTasks);
    } catch (error) {
      console.error('Error fetching tasks:', error);
      setError('Failed to fetch tasks');
    } finally {
      setLoading(false);
    }
  };

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

  // Update the date display component
  const TaskDate = ({ task }: { task: Task & { validDate?: Date } }) => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    if (!task.validDate) {
      return (
        <>
          <span className="text-xs text-gray-600 font-medium">NO</span>
          <span className="text-lg text-gray-700 font-bold">DATE</span>
        </>
      );
    }

    const isPastDue = task.validDate < today;
    const textColorClass = isPastDue ? 'text-red-600' : 'text-blue-600';
    const boldColorClass = isPastDue ? 'text-red-700' : 'text-blue-700';

    return (
      <>
        <span className={`text-xs ${textColorClass} font-medium uppercase`}>
          {task.validDate.toLocaleDateString('fr-FR', { month: 'short' })}
        </span>
        <span className={`text-lg ${boldColorClass} font-bold`}>
          {task.validDate.getDate()}
        </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">
        <CardTitle className="text-xl font-semibold text-gray-800">Flow</CardTitle>
        <Button 
          variant="ghost" 
          size="icon" 
          onClick={() => fetchTasks()}
          className="h-8 w-8 p-0 hover:bg-gray-100/50 rounded-full"
        >
          <RefreshCw className="h-4 w-4 text-gray-600" />
        </Button>
      </CardHeader>
      <CardContent className="p-4">
        {loading ? (
          <div className="flex items-center justify-center py-8">
            <div className="h-5 w-5 animate-spin rounded-full border-2 border-blue-500 border-t-transparent" />
          </div>
        ) : error ? (
          <div className="text-sm text-red-500 text-center py-4">{error}</div>
        ) : tasks.length === 0 ? (
          <div className="text-sm text-gray-500 text-center py-8">No tasks with due dates found</div>
        ) : (
          <div className="space-y-3 max-h-[460px] overflow-y-auto pr-2 scrollbar-thin scrollbar-thumb-gray-200 scrollbar-track-transparent">
            {tasks.map((task) => (
              <div 
                key={task.id}
                className="p-3 rounded-xl bg-white shadow-sm hover:shadow-md transition-all duration-200 border border-gray-100"
              >
                <div className="flex gap-3">
                  <div className="flex-shrink-0 w-14 h-14 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.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 line-clamp-2"
                    >
                      {task.headline}
                    </a>
                    <div className="flex items-center text-gray-500 text-xs bg-gray-50 px-2 py-1 rounded-md">
                      <Folder className="h-3 w-3 mr-1.5 opacity-70" />
                      <span className="truncate">{task.projectName}</span>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
}