import { useState } from 'react';
import { TodoWithStats, CompleteTodoRequest } from '../../../api/controller/todo';
import Button from '@greatness/components/src/Button';

interface TodoCardProps {
  todo: TodoWithStats;
  onComplete: (id: string, data: CompleteTodoRequest) => void;
  onEdit: (todo: TodoWithStats) => void;
  onDelete: (id: string) => void;
  isLoading?: boolean;
}

export default function TodoCard({ todo, onComplete, onEdit, onDelete, isLoading = false }: TodoCardProps) {
  const [showCompleteForm, setShowCompleteForm] = useState(false);
  const [completionDescription, setCompletionDescription] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleComplete = async () => {
    if (todo.completedToday) return;
    
    setIsSubmitting(true);
    try {
      await onComplete(todo.id, { description: completionDescription });
      setShowCompleteForm(false);
      setCompletionDescription('');
    } catch (error) {
      console.error('Failed to complete todo:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const getStreakColor = (streak: number) => {
    if (streak === 0) return 'text-gray-500';
    if (streak < 7) return 'text-yellow-600';
    if (streak < 30) return 'text-orange-600';
    return 'text-green-600';
  };

  const getStreakIcon = (streak: number) => {
    if (streak === 0) return '⚪';
    if (streak < 7) return '🔥';
    if (streak < 30) return '🚀';
    return '⭐';
  };

  return (
    <div 
      className="relative p-4 rounded-lg border-2 shadow-sm transition-all hover:shadow-md"
      style={{ 
        borderColor: todo.color,
        backgroundColor: todo.completedToday ? `${todo.color}10` : 'var(--color-greyOpacity'
      }}
    >
      {/* Color indicator */}
      <div 
        className="absolute top-0 left-0 w-full h-1 rounded-t-lg"
        style={{ backgroundColor: todo.color }}
      />

      <div className="flex justify-between items-start mb-3">
        <div className="flex-1">
          <h3 className="font-semibold text-gray-900 mb-1">{todo.title}</h3>
          {todo.description && (
            <p className="text-sm text-gray-600 mb-2">{todo.description}</p>
          )}
        </div>
        
        <div className="flex gap-2 ml-4">
          <button
            onClick={() => onEdit(todo)}
            className="text-gray-400 hover:text-gray-600 p-1"
            title="Edit todo"
          >
            ✏️
          </button>
          <button
            onClick={() => onDelete(todo.id)}
            className="text-gray-400 hover:text-red-600 p-1"
            title="Delete todo"
          >
            🗑️
          </button>
        </div>
      </div>

      {/* Stats */}
      <div className="flex justify-between items-center mb-3 text-sm">
        <div className="flex gap-4">
          <span className={`font-medium ${getStreakColor(todo.currentStreak)}`}>
            {getStreakIcon(todo.currentStreak)} {todo.currentStreak} day streak
          </span>
          <span className="text-gray-500">
            Best: {todo.longestStreak} days
          </span>
          <span className="text-gray-500">
            Total: {todo.totalCompletions}
          </span>
        </div>
        
        {todo.lastCompletedAt && (
          <span className="text-xs text-gray-400">
            Last: {new Date(todo.lastCompletedAt).toLocaleDateString()}
          </span>
        )}
      </div>

      {/* Completion section */}
      {todo.completedToday ? (
        <div className="flex items-center gap-2 p-2 bg-green-50 rounded border border-green-200">
          <span className="text-green-600">✅</span>
          <span className="text-green-800 font-medium">Completed today!</span>
        </div>
      ) : showCompleteForm ? (
        <div className="space-y-3 p-3 bg-greyOpacity rounded border">
          <textarea
            value={completionDescription}
            onChange={(e) => setCompletionDescription(e.target.value)}
            placeholder="How did you complete this today? (optional)"
            className="w-full p-2 border rounded-md resize-none h-20 text-sm"
          />
          <div className="flex gap-2">
            <Button
              onClick={handleComplete}
              isDisabled={isSubmitting}
              className="flex-1 bg-green-600 hover:bg-green-700 text-white py-2 px-4 rounded-md text-sm"
              label={isSubmitting ? 'Completing...' : 'Mark Complete'}
            >
            </Button>
            <Button
              onClick={() => {
                setShowCompleteForm(false);
                setCompletionDescription('');
              }}
              className="px-4 py-2 border border-gray-300 rounded-md text-sm hover:bg-gray-50"
              label="Cancel"
            >
            </Button>
          </div>
        </div>
      ) : (
        <Button
          onClick={() => setShowCompleteForm(true)}
          isDisabled={isLoading}
          className="w-full py-2 px-4 border-2 rounded-md text-sm font-medium transition-colors"
          style={{ 
            borderColor: todo.color,
            color: todo.color,
            backgroundColor: 'var(--color-greyOpacity)'
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.backgroundColor = todo.color;
            e.currentTarget.style.color = 'white';
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.backgroundColor = 'var(--color-greyOpacity)';
            e.currentTarget.style.color = todo.color;
          }}
          label="Complete Today"
        >
        </Button>
      )}
    </div>
  );
}

