"use client";
import React, { useState } from "react";
import { Task } from "./TaskList";
import { useI18n } from "@/lib/i18n";

interface KanbanViewProps {
  tasks: Task[];
  selectedTaskId: string | null;
  onSelectTask: (task: Task) => void;
  onToggleTask: (id: string, completed: boolean) => void;
  onAddTask: (title: string, priority?: number) => void;
}

export function KanbanView({
  tasks,
  selectedTaskId,
  onSelectTask,
  onToggleTask,
  onAddTask,
}: KanbanViewProps) {
  const { t } = useI18n();
  const [newTodoTitle, setNewTodoTitle] = useState("");
  const [newProgTitle, setNewProgTitle] = useState("");

  const PRIORITY_COLORS = ["", "var(--priority-low)", "var(--priority-medium)", "var(--priority-high)"];

  // Group tasks into 3 columns
  const todoTasks = tasks.filter((task) => !task.completed && task.priority < 2 && !task.parentId);
  const inProgressTasks = tasks.filter((task) => !task.completed && task.priority >= 2 && !task.parentId);
  const doneTasks = tasks.filter((task) => task.completed && !task.parentId);

  const renderCard = (task: Task) => {
    const isSelected = selectedTaskId === task.id;
    const subtaskCount = task.children?.length || 0;
    const completedSubtasks = task.children?.filter((s) => s.completed).length || 0;

    return (
      <div
        key={task.id}
        className={`kanban-card${isSelected ? " selected" : ""}`}
        onClick={() => onSelectTask(task)}
      >
        <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
          <button
            type="button"
            className={`task-check-btn${task.completed ? " checked" : ""}`}
            style={{ width: 17, height: 17, marginTop: 2, flexShrink: 0 }}
            onClick={(e) => {
              e.stopPropagation();
              onToggleTask(task.id, !task.completed);
            }}
            aria-label="Toggle task completion"
          />

          <div style={{ flex: 1, minWidth: 0 }}>
            <div
              style={{
                fontSize: 13.5,
                fontWeight: 600,
                color: task.completed ? "var(--text-tertiary)" : "var(--text-primary)",
                textDecoration: task.completed ? "line-through" : "none",
                wordBreak: "break-word",
                lineHeight: 1.4,
              }}
            >
              {task.title}
            </div>

            {/* Badges row: Priority, Due Date, Subtask progress */}
            <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 8, flexWrap: "wrap" }}>
              {task.priority > 0 && (
                <span
                  style={{
                    fontSize: 10,
                    fontWeight: 700,
                    padding: "2px 6px",
                    borderRadius: "var(--radius-sm)",
                    background: `${PRIORITY_COLORS[task.priority]}15`,
                    color: PRIORITY_COLORS[task.priority],
                    display: "inline-flex",
                    alignItems: "center",
                    gap: 3,
                  }}
                >
                  🚩 P{task.priority}
                </span>
              )}

              {task.dueDate && (
                <span
                  style={{
                    fontSize: 10,
                    fontWeight: 500,
                    padding: "2px 6px",
                    borderRadius: "var(--radius-sm)",
                    background: "var(--bg-hover)",
                    color: "var(--text-secondary)",
                  }}
                >
                  📅 {new Date(task.dueDate).toLocaleDateString(undefined, { month: "short", day: "numeric" })}
                </span>
              )}

              {subtaskCount > 0 && (
                <span
                  style={{
                    fontSize: 10,
                    fontWeight: 600,
                    padding: "2px 6px",
                    borderRadius: "var(--radius-sm)",
                    background: "var(--bg-hover)",
                    color: "var(--text-tertiary)",
                  }}
                >
                  ☑️ {completedSubtasks}/{subtaskCount}
                </span>
              )}

              {task.note && (
                <span style={{ fontSize: 10, color: "var(--text-tertiary)" }} title="Has note">
                  📝
                </span>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="kanban-container">
      {/* Column 1: To Do */}
      <div className="kanban-column">
        <div className="kanban-column-header">
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--text-tertiary)" }} />
            <span style={{ fontSize: 13, fontWeight: 700, color: "var(--text-primary)" }}>{t("todoCol")}</span>
          </div>
          <span style={{ fontSize: 11, fontWeight: 700, color: "var(--text-tertiary)", background: "var(--bg-hover)", padding: "2px 8px", borderRadius: "var(--radius-full)" }}>
            {todoTasks.length}
          </span>
        </div>

        <div className="kanban-column-body">
          {todoTasks.map(renderCard)}

          {/* Quick inline add in To Do */}
          <div style={{ display: "flex", gap: 6, marginTop: 4 }}>
            <input
              className="form-input"
              placeholder={t("addTaskPlaceholder")}
              style={{ fontSize: 12, padding: "6px 10px", flex: 1 }}
              value={newTodoTitle}
              onChange={(e) => setNewTodoTitle(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter" && newTodoTitle.trim()) {
                  e.preventDefault();
                  onAddTask(newTodoTitle.trim(), 0);
                  setNewTodoTitle("");
                }
              }}
            />
          </div>
        </div>
      </div>

      {/* Column 2: In Progress / High Priority */}
      <div className="kanban-column">
        <div className="kanban-column-header">
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--accent)" }} />
            <span style={{ fontSize: 13, fontWeight: 700, color: "var(--text-primary)" }}>{t("inProgressCol")}</span>
          </div>
          <span style={{ fontSize: 11, fontWeight: 700, color: "var(--accent)", background: "var(--accent-light)", padding: "2px 8px", borderRadius: "var(--radius-full)" }}>
            {inProgressTasks.length}
          </span>
        </div>

        <div className="kanban-column-body">
          {inProgressTasks.map(renderCard)}

          {/* Quick inline add in In Progress */}
          <div style={{ display: "flex", gap: 6, marginTop: 4 }}>
            <input
              className="form-input"
              placeholder={t("addTaskPlaceholder")}
              style={{ fontSize: 12, padding: "6px 10px", flex: 1 }}
              value={newProgTitle}
              onChange={(e) => setNewProgTitle(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter" && newProgTitle.trim()) {
                  e.preventDefault();
                  onAddTask(newProgTitle.trim(), 2);
                  setNewProgTitle("");
                }
              }}
            />
          </div>
        </div>
      </div>

      {/* Column 3: Done */}
      <div className="kanban-column">
        <div className="kanban-column-header">
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--success)" }} />
            <span style={{ fontSize: 13, fontWeight: 700, color: "var(--text-primary)" }}>{t("doneCol")}</span>
          </div>
          <span style={{ fontSize: 11, fontWeight: 700, color: "var(--success)", background: "rgba(16, 185, 129, 0.12)", padding: "2px 8px", borderRadius: "var(--radius-full)" }}>
            {doneTasks.length}
          </span>
        </div>

        <div className="kanban-column-body">
          {doneTasks.map(renderCard)}
        </div>
      </div>
    </div>
  );
}
