"use client";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { RefreshCw, Share2 } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { getTaskStatusColor, getTaskStatusLabel } from "@/lib/utils/status-utils";
import { useTasks, Task } from "@/hooks/use-tasks";

interface FlowProps {
  limit?: number;
  showRefresh?: boolean;
  showHeader?: boolean;
  cardClassName?: string;
}

export function Duties({
  limit = 5,
  showRefresh = true,
  showHeader = true,
  cardClassName = "transition-transform duration-500 ease-in-out transform hover:scale-105 bg-white/95 backdrop-blur-sm border-0 shadow-lg"
}: FlowProps) {
  const { tasks, loading, error, refresh } = useTasks({ 
    limit,
    includeDone: false,
    sortField: 'dateToFinish',
    sortDirection: 'asc'
  });
  
  // TaskDate component
  const TaskDate = ({ task }: { task: Task }) => {
    const dateStr = task.dateToFinish || task.dueDate;
    if (!dateStr) {
      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) {
      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>
      );
    }
  };

  const renderContent = () => {
    if (loading) {
      return (
        <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>
      );
    }
    
    if (error) {
      return (
        <div className="text-xs text-red-500 text-center py-3">{error}</div>
      );
    }
    
    if (tasks.length === 0) {
      return (
        <div className="text-xs text-gray-500 text-center py-6">No tasks with due dates found</div>
      );
    }
    
    return (
      <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-14 h-14 rounded-md flex items-center justify-center">
                <TaskDate task={task} />
              </div>
              
              <div className="flex-1 min-w-0 space-y-1">
                <div className="flex items-start justify-between gap-2">
                  <p className="text-sm font-medium text-gray-800 line-clamp-2 flex-1">
                    {task.headline}
                  </p>
                  <div className={`px-2 py-1 rounded-full w-3 h-3 ${getTaskStatusColor(task.status)}`} 
                        title={getTaskStatusLabel(task.status)} />
                </div>
                
                <div className="flex items-center gap-1">
                  <Badge variant="outline" className="text-[10px] bg-gray-50">
                    {task.projectName}
                  </Badge>
                  
                  {task.milestoneHeadline && (
                    <Badge variant="outline" className="text-[10px] bg-blue-50">
                      {task.milestoneHeadline}
                    </Badge>
                  )}
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
    );
  };

  if (!showHeader) {
    return renderContent();
  }

  return (
    <Card className={cardClassName}>
      <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" />
          Tasks
        </CardTitle>
        {showRefresh && (
          <Button 
            variant="ghost" 
            size="icon" 
            onClick={refresh}
            className="h-7 w-7 p-0 hover:bg-gray-100/50 rounded-full"
            disabled={loading}
          >
            <RefreshCw className={`h-3.5 w-3.5 text-gray-600 ${loading ? 'animate-spin' : ''}`} />
          </Button>
        )}
      </CardHeader>
      <CardContent className="p-3">
        {renderContent()}
      </CardContent>
    </Card>
  );
}