"use client";

import { useState } from "react";
import { Plus, Circle, CheckCircle2, Trash2 } from "lucide-react";
import { cn } from "@/lib/utils";
import type { Task } from "@/types";

interface SubtaskListProps {
  subtasks: Task[];
  onAdd: (title: string) => Promise<void>;
  onToggle: (id: string, currentStatus: string) => Promise<void>;
  onDelete: (id: string) => Promise<void>;
  editable?: boolean;
}

export function SubtaskList({
  subtasks,
  onAdd,
  onToggle,
  onDelete,
  editable = true,
}: SubtaskListProps) {
  const [adding, setAdding] = useState(false);
  const [newTitle, setNewTitle] = useState("");
  const [submitting, setSubmitting] = useState(false);

  async function handleAdd() {
    if (!editable) return;
    if (!newTitle.trim() || submitting) return;
    setSubmitting(true);
    await onAdd(newTitle.trim());
    setNewTitle("");
    setSubmitting(false);
  }

  const doneCount = subtasks.filter((s) => s.status === "done").length;

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <span className="text-xs font-medium text-muted-foreground">
          Subtasks
          {subtasks.length > 0 && (
            <span className="ml-1.5">
              {doneCount}/{subtasks.length}
            </span>
          )}
        </span>
      </div>

      {/* Progress bar */}
      {subtasks.length > 0 && (
        <div className="h-1 rounded-full bg-muted overflow-hidden">
          <div
            className="h-full rounded-full bg-primary transition-all duration-300"
            style={{
              width: `${(doneCount / subtasks.length) * 100}%`,
            }}
          />
        </div>
      )}

      {/* Subtask items */}
      <div className="space-y-0.5">
        {subtasks.map((subtask) => (
          <div
            key={subtask.id}
            className="group flex items-center gap-2 rounded-md px-1 py-1 -mx-1 hover:bg-accent/50 transition-colors"
          >
            <button
              type="button"
              onClick={() => onToggle(subtask.id, subtask.status)}
              disabled={!editable}
              className="shrink-0 cursor-pointer text-muted-foreground hover:text-foreground transition-colors"
            >
              {subtask.status === "done" ? (
                <CheckCircle2 className="h-4 w-4 text-primary" />
              ) : (
                <Circle className="h-4 w-4" />
              )}
            </button>
            <span
              className={cn(
                "flex-1 text-sm",
                subtask.status === "done" &&
                  "line-through text-muted-foreground"
              )}
            >
              {subtask.title}
            </span>
            <button
              type="button"
              onClick={() => onDelete(subtask.id)}
              disabled={!editable}
              className="opacity-0 group-hover:opacity-100 p-0.5 text-muted-foreground hover:text-destructive transition-all cursor-pointer"
            >
              <Trash2 className="h-3.5 w-3.5" />
            </button>
          </div>
        ))}
      </div>

      {/* Add subtask */}
      {adding && editable ? (
        <div className="flex items-center gap-2">
          <Circle className="h-4 w-4 text-muted-foreground shrink-0" />
          <input
            value={newTitle}
            onChange={(e) => setNewTitle(e.target.value)}
            placeholder="Subtask title"
            className="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
            onKeyDown={(e) => {
              if (e.key === "Enter") handleAdd();
              if (e.key === "Escape") {
                setAdding(false);
                setNewTitle("");
              }
            }}
            autoFocus
          />
        </div>
      ) : editable ? (
        <button
          type="button"
          onClick={() => setAdding(true)}
          className="flex items-center gap-2 text-xs text-muted-foreground hover:text-foreground transition-colors cursor-pointer py-1"
        >
          <Plus className="h-3.5 w-3.5" />
          Add subtask
        </button>
      ) : (
        <p className="py-1 text-xs text-muted-foreground">
          You can view subtasks, but only editors can change them.
        </p>
      )}
    </div>
  );
}
