"use client";

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

interface Task {
  id: number;
  headline: string;
  description: string;
  dateToFinish: string | null;
  projectId: number;
  projectName: string;
  status: number;
  editorId?: string;
  editorFirstname?: string;
  editorLastname?: string;
  authorFirstname: string;
  authorLastname: string;
  milestoneHeadline?: string;
  editTo?: string;
  editFrom?: string;
  type?: string;
  dependingTicketId?: number | null;
}

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

interface TaskWithDate extends Task {
  validDate?: Date;
}

export function Duties() {
  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 'Blocked';
      case 3: return 'In Progress';
      case 4: return 'Waiting for Approval';
      case 5: return 'Done';
      default: return 'Unknown';
    }
  };

  const getStatusColor = (status: number): string => {
    switch (status) {
      case 1: return 'bg-blue-500';   // New - blue
      case 2: return 'bg-red-500';    // Blocked - red
      case 3: return 'bg-yellow-500'; // In Progress - yellow
      case 4: return 'bg-purple-500'; // Waiting for Approval - purple
      case 5: return 'bg-gray-500';   // Done - gray
      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);
    setError(null);
    try {
      const response = await fetch('/api/leantime/tasks');
      if (!response.ok) {
        throw new Error('Failed to fetch tasks');
      }
      const data = await response.json();
      
      console.log('Raw API response:', data);
      
      if (!Array.isArray(data)) {
        console.warn('No tasks found in response', data as unknown);
        setTasks([]);
        return;
      }

      // Filter out tasks with status Done (5) and sort by dateToFinish
      const sortedTasks = data
        .filter((task: Task) => {
          // Filter out any task (main or subtask) that has status Done (5)
          const isNotDone = task.status !== 5;
          if (!isNotDone) {
            console.log(`Filtering out Done task ${task.id} (type: ${task.type || 'main'}, status: ${task.status})`);
          } else {
            console.log(`Keeping task ${task.id}: status=${task.status} (${getStatusLabel(task.status)}), type=${task.type || 'main'}`);
          }
          return isNotDone;
        })
        .sort((a: Task, b: Task) => {
          // First sort by dateToFinish (oldest first)
          const dateA = getValidDate(a);
          const dateB = getValidDate(b);
          
          // If both dates are valid, compare them
          if (dateA && dateB) {
            const timeA = new Date(dateA).getTime();
            const timeB = new Date(dateB).getTime();
            if (timeA !== timeB) {
              return timeA - timeB;
            }
          }
          
          // If only one date is valid, put the task with a date first
          if (dateA) return -1;
          if (dateB) return 1;
          
          // If dates are equal or neither has a date, sort by status (4 before others)
          if (a.status === 4 && b.status !== 4) return -1;
          if (b.status === 4 && a.status !== 4) return 1;
          
          // If status is also equal, maintain original order
          return 0;
        });

      console.log('Sorted and filtered tasks:', sortedTasks.map(t => ({
        id: t.id,
        date: t.dateToFinish,
        status: t.status,
        type: t.type || 'main'
      })));
      setTasks(sortedTasks.slice(0, 7));
    } catch (error) {
      console.error('Error fetching tasks:', error);
      setError(error instanceof Error ? error.message : 'Failed to fetch tasks');
    } finally {
      setLoading(false);
    }
  };

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

  // Update the TaskDate component to handle dates better
  const TaskDate = ({ task }: { task: TaskWithDate }) => {
    const dateStr = task.dateToFinish;
    if (!dateStr || dateStr === '0000-00-00 00:00:00') {
      return (
        <div className="flex flex-col items-center">
          <span className="text-[10px] text-gray-600 font-medium">NO</span>
          <span className="text-sm text-gray-700 font-bold">DATE</span>
        </div>
      );
    }

    try {
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) {
        throw new Error('Invalid date');
      }

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

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

  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-lg font-semibold text-gray-800 flex items-center gap-2">
          <Share2 className="h-5 w-5 text-gray-600" />
          Devoirs
        </CardTitle>
        <Button 
          variant="ghost" 
          size="icon" 
          onClick={() => fetchTasks()}
          className="h-7 w-7 p-0 hover:bg-gray-100/50 rounded-full"
        >
          <RefreshCw className="h-3.5 w-3.5 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-[400px] overflow-y-auto pr-1 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>
  );
}