import { useState } from 'react';
import type { Task } from '../types';
import { useLanguage } from '../i18n/LanguageContext';
import './TodaysTasks.css';

interface TodaysTasksProps {
  tasks: Task[];
  onComplete: (taskId: number) => void;
}

export default function TodaysTasks({ tasks, onComplete }: TodaysTasksProps) {
  const { t } = useLanguage();
  const essentialTasks = tasks.filter(task => task.priority === 'ESSENTIAL');
  const whenIHaveTimeTasks = tasks.filter(task => task.priority === 'WHEN_I_HAVE_TIME');
  const [showWhenIHaveTime, setShowWhenIHaveTime] = useState(false);

  return (
    <div className="todays-tasks">

      <section className="task-section">
        <h2 className="section-title">{t.needToDo} 
          <span className="count-badge">{essentialTasks.length}</span></h2>
        {essentialTasks.length === 0 ? (
          <p className="no-tasks">{t.nothingEssential}</p>
        ) : (
          <div className="task-grid">
            {essentialTasks.map(task => (
              <TaskCard
                key={task.id}
                task={task}
                onComplete={onComplete}
              />
            ))}
          </div>
        )}
      </section>

      <section className="task-section">
        <h2
          className="section-title section-title--clickable"
          onClick={() => setShowWhenIHaveTime(!showWhenIHaveTime)}
        >
          {t.whenIHaveTime}
          <span className="count-badge">{whenIHaveTimeTasks.length}</span>
          <span className="toggle-icon">{showWhenIHaveTime ? '▾' : '▸'}</span>
        </h2>
        {showWhenIHaveTime && (
          whenIHaveTimeTasks.length === 0 ? (
            <p className="no-tasks">{t.nothingHere}</p>
          ) : (
            <div className="task-grid">
              {whenIHaveTimeTasks.map(task => (
                <TaskCard
                  key={task.id}
                  task={task}
                  onComplete={onComplete}
                />
              ))}
            </div>
          )
        )}
      </section>
    </div>
  );
}

interface TaskCardProps {
  task: Task;
  onComplete: (taskId: number) => void;
}

function TaskCard({ task, onComplete }: TaskCardProps) {
  const { t } = useLanguage();
  const [tooltipVisible, setTooltipVisible] = useState(false);

  return (
    <div className="task-card">
      <span
        className="task-card-name"
        onClick={() => setTooltipVisible(v => !v)}
        onMouseEnter={() => setTooltipVisible(true)}
        onMouseLeave={() => setTooltipVisible(false)}
      >
        {task.name}
        {tooltipVisible && <span className="name-tooltip">{task.name}</span>}
      </span>
      <div className="task-card-actions">
        <button
          className="action-btn"
          onClick={() => onComplete(task.id)}
          title={t.markCompleted}
        >
          ✓
        </button>
      </div>
    </div>
  );
}
