import React, { useState, useEffect } from "react";
import "./Task.css";

const Task = ({
  title,
  subtitle,
  initialDone = false,
  children,
  onStatusChange,
  order,
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [done, setDone] = useState(initialDone);

  // Fermer la tâche quand elle est complétée
  useEffect(() => {
    if (done) {
      setIsOpen(false);
    }
  }, [done]);

  const handleCircleClick = (e) => {
    e.stopPropagation();
    const newStatus = !done;
    setDone(newStatus);
    if (onStatusChange) {
      onStatusChange(newStatus);
    }
  };

  const handleTitleClick = () => {
    if (!done) {
      setIsOpen(!isOpen);
    }
  };

  return (
    <div className="task-wrapper" data-order={order}>
      <div className={`task-container ${done ? "completed" : ""}`}>
        <div className="task-header">
          <div
            className={`task-checkbox ${done ? "done" : ""}`}
            onClick={handleCircleClick}
            title={done ? "Mark as incomplete" : "Mark as complete"}
          >
            {done && (
              <svg
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 24 24"
                width="16"
                height="16"
                fill="#fff"
              >
                <path d="M20.285 2l-11.285 11.567-5.286-5.011-3.714 3.716 9 8.728 15-15.285z" />
              </svg>
            )}
          </div>
          <div className="task-title" onClick={handleTitleClick}>
            <div className="task-title-content">
              <span className="task-title-text">{title}</span>
              {subtitle && <span className="task-subtitle">{subtitle}</span>}
            </div>
            <div className="task-actions">
              <span className={`task-status ${done ? "completed" : ""}`}>
                {done ? "Completed" : "Click to follow steps"}
              </span>
              <svg
                className="task-arrow"
                xmlns="http://www.w3.org/2000/svg"
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
                style={{
                  transform: isOpen ? "rotate(180deg)" : "rotate(0deg)",
                }}
              >
                <path d="M6 9l6 6 6-6" />
              </svg>
            </div>
          </div>
        </div>
        {isOpen && <div className="task-content">{children}</div>}
      </div>
    </div>
  );
};

export default Task;
