"use client";

import { useEffect, useState, useCallback } from "react";
import { useRouter, useParams } from "next/navigation";
import { useAuth } from "@/lib/auth";
import { useTranslation } from "@/lib/i18n";
import {
  getTask,
  getGroups,
  updateTask,
  deleteTask,
  Task,
  Group,
  Subtask,
  getSubtasks,
  searchUsers,
} from "@/lib/api";
import TaskForm from "@/components/TaskForm";
import InviteModal from "@/components/InviteModal";
import StatusBadge from "@/components/StatusBadge";

function isDone(status: string): boolean {
  return status === "done" || status === "completed";
}

export default function TaskDetailPage() {
  const { token, user } = useAuth();
  const { t, locale } = useTranslation();
  const router = useRouter();
  const params = useParams();
  const id = params.id as string;
  const [task, setTask] = useState<Task | null>(null);
  const [groups, setGroups] = useState<Group[]>([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [error, setError] = useState("");
  const [subtasks, setSubtasks] = useState<Subtask[]>([]);
  const [assigneeNames, setAssigneeNames] = useState<Record<string, string>>({});
  const [showInvite, setShowInvite] = useState(false);

  const dateLocale = locale === "ua" ? "uk-UA" : locale === "cs" ? "cs-CZ" : locale === "he" ? "he-IL" : "ru-RU";

  function formatDate(dateStr: string | null | undefined): string {
    if (!dateStr) return t("tasks.noDue");
    try {
      const d = new Date(dateStr);
      if (isNaN(d.getTime())) return t("tasks.noDue");
      return d.toLocaleDateString(dateLocale, {
        day: "numeric",
        month: "numeric",
        year: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      });
    } catch {
      return t("tasks.noDue");
    }
  }

  const loadTask = useCallback(async () => {
    if (!token || !id) return;
    setLoading(true);
    try {
      const [taskData, groupsData, subtasksData] = await Promise.all([
        getTask(token, id),
        getGroups(token),
        getSubtasks(token, id).catch(() => ({ data: [] })),
      ]);
      setTask(taskData);
      setGroups(groupsData.data || []);
      setSubtasks(subtasksData.data || []);
      // Load assignee names
      const assigned: string[] = taskData.assigned_to || [];
      if (assigned.length > 0) {
        try {
          const res = await searchUsers(token, "");
          const nameMap: Record<string, string> = {};
          (res.data || []).forEach((u: { id: string; name: string }) => {
            if (assigned.includes(u.id)) nameMap[u.id] = u.name;
          });
          setAssigneeNames(nameMap);
        } catch { /* ignore */ }
      }
    } catch (err) {
      setError(
        err instanceof Error ? err.message : t("tasks.loadError")
      );
    } finally {
      setLoading(false);
    }
  }, [token, id, t]);

  useEffect(() => {
    if (!token) {
      router.replace("/login");
      return;
    }
    loadTask();
  }, [token, router, loadTask]);

  async function handleUpdate(data: Partial<Task>) {
    if (!token || !id) return;
    await updateTask(token, id, data);
    setEditing(false);
    loadTask();
  }

  async function handleDelete() {
    if (!token || !id) return;
    if (!confirm(t("tasks.confirmDelete"))) return;
    setDeleting(true);
    try {
      await deleteTask(token, id);
      router.push("/tasks");
    } catch (err) {
      setError(
        err instanceof Error ? err.message : t("common.error")
      );
      setDeleting(false);
    }
  }

  async function handleQuickStatus(newStatus: Task["status"]) {
    if (!token || !id) return;
    try {
      await updateTask(token, id, { status: newStatus });
      loadTask();
    } catch (err) {
      setError(
        err instanceof Error ? err.message : t("common.error")
      );
    }
  }

  if (!token) return null;

  if (loading) {
    return (
      <div className="flex justify-center py-12">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600" />
      </div>
    );
  }

  if (error || !task) {
    return (
      <div className="text-center py-12">
        <p className="text-red-500">{error || t("tasks.notFound")}</p>
        <button
          onClick={() => router.push("/tasks")}
          className="mt-4 text-blue-600 hover:underline"
        >
          {t("tasks.backToTasks")}
        </button>
      </div>
    );
  }

  if (editing) {
    return (
      <div className="max-w-lg mx-auto">
        <h1 className="text-xl font-bold mb-4">{t("tasks.editTask")}</h1>
        <TaskForm
          groups={groups}
          initial={task}
          onSubmit={handleUpdate}
          onCancel={() => setEditing(false)}
          submitLabel={t("tasks.saveChanges")}
        />
      </div>
    );
  }

  const PRIORITY_LABELS: Record<string, { dot: string }> = {
    low: { dot: "\ud83d\udfe2" },
    medium: { dot: "\ud83d\udfe1" },
    high: { dot: "\ud83d\udfe0" },
    urgent: { dot: "\ud83d\udd34" },
  };

  const pri = PRIORITY_LABELS[task.priority] || PRIORITY_LABELS.medium;
  const taskDone = isDone(task.status);

  return (
    <div className="max-w-lg mx-auto space-y-4">
      {/* Action bar - all buttons in one compact row */}
      <div className="flex items-center gap-2 flex-wrap">
        <button
          onClick={() => router.push("/tasks")}
          className="inline-flex items-center gap-1.5 px-3 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors"
        >
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
          </svg>
          {t("common.back")}
        </button>

        <div className="flex-1" />

        {!taskDone && (
          <button
            onClick={() => handleQuickStatus("done")}
            className="inline-flex items-center gap-1.5 px-3 py-2 text-sm font-medium bg-green-600 hover:bg-green-700 text-white rounded-lg transition-colors"
          >
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
            </svg>
            {t("tasks.markDone")}
          </button>
        )}

        {taskDone && (
          <button
            onClick={() => handleQuickStatus("pending")}
            className="inline-flex items-center gap-1.5 px-3 py-2 text-sm font-medium bg-yellow-600 hover:bg-yellow-700 text-white rounded-lg transition-colors"
          >
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
            {t("tasks.reopen")}
          </button>
        )}

        <button
          onClick={() => setEditing(true)}
          className="inline-flex items-center gap-1.5 px-3 py-2 text-sm font-medium border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-800 rounded-lg transition-colors"
        >
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
          </svg>
          {t("tasks.edit")}
        </button>

        <button
          onClick={handleDelete}
          disabled={deleting}
          className="inline-flex items-center gap-1.5 px-3 py-2 text-sm font-medium border border-red-300 dark:border-red-800 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors disabled:opacity-50"
        >
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
          </svg>
          {deleting ? t("tasks.deleting") : t("tasks.delete")}
        </button>
      </div>

      {/* Task detail card */}
      <div className="bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-2xl p-6">
        <div className="flex items-start justify-between gap-4 mb-4">
          <div className="flex items-start gap-3">
            {task.group_icon && (
              <span className="text-2xl">{task.group_icon}</span>
            )}
            <h1
              className={`text-xl font-bold ${
                taskDone ? "line-through text-muted" : ""
              }`}
            >
              {task.title}
            </h1>
          </div>
          <StatusBadge status={task.status} size="md" />
        </div>

        {task.description && (
          <p className="text-muted mb-4 whitespace-pre-wrap leading-relaxed">
            {task.description}
          </p>
        )}

        <div className="grid grid-cols-2 gap-3 text-sm">
          <div>
            <span className="text-muted">{t("tasks.form.priority")}:</span>
            <span className="ml-2 font-medium">
              {pri.dot} {t(`tasks.priority.${task.priority}`)}
            </span>
          </div>
          {task.group_name && (
            <div>
              <span className="text-muted">{t("tasks.form.group")}:</span>
              <span
                className="ml-2 inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium text-white"
                style={{
                  backgroundColor: task.group_color || "#6b7280",
                }}
              >
                {task.group_icon && (
                  <span className="mr-1">{task.group_icon}</span>
                )}
                {task.group_name}
              </span>
            </div>
          )}
          <div>
            <span className="text-muted">{t("tasks.form.dueDate")}:</span>
            <span className="ml-2">
              {formatDate(task.due_at)}
            </span>
          </div>
          <div>
            <span className="text-muted">{t("tasks.created")}:</span>
            <span className="ml-2">
              {formatDate(task.created_at)}
            </span>
          </div>
          {task.completed_at && (
            <div>
              <span className="text-muted">{t("tasks.completed")}:</span>
              <span className="ml-2">
                {formatDate(task.completed_at)}
              </span>
            </div>
          )}
        </div>
      </div>

      {/* Collaboration summary */}
      <div className="bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-2xl p-6">
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-sm font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">
            {t("collab.collaboration")}
          </h2>
          <button
            onClick={() => router.push(`/tasks/${id}/collaborate`)}
            className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors"
          >
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
            </svg>
            {t("collab.collaboration")}
          </button>
          <button
            onClick={() => setShowInvite(true)}
            className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
          >
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
            </svg>
            Pozvat
          </button>
        </div>

        {/* Assigned users */}
        {task.assigned_to && task.assigned_to.length > 0 && (
          <div className="flex items-center gap-2 mb-3">
            <span className="text-sm text-gray-500">{t("collab.assignees")}:</span>
            <div className="flex -space-x-2">
              {task.assigned_to.slice(0, 5).map((uid: string) => {
                const name = assigneeNames[uid] || uid.slice(0, 4);
                const initials = name.split(" ").map((n: string) => n[0]).join("").toUpperCase().slice(0, 2);
                const colors = ["bg-blue-500", "bg-green-500", "bg-purple-500", "bg-orange-500", "bg-pink-500"];
                const color = colors[name.charCodeAt(0) % colors.length];
                return (
                  <div
                    key={uid}
                    title={assigneeNames[uid] || uid}
                    className={`w-8 h-8 rounded-full ${color} text-white flex items-center justify-center text-xs font-medium border-2 border-white dark:border-gray-900`}
                  >
                    {initials}
                  </div>
                );
              })}
              {task.assigned_to.length > 5 && (
                <div className="w-8 h-8 rounded-full bg-gray-400 text-white flex items-center justify-center text-xs font-medium border-2 border-white dark:border-gray-900">
                  +{task.assigned_to.length - 5}
                </div>
              )}
            </div>
          </div>
        )}

        {/* Subtask progress */}
        {subtasks.length > 0 && (() => {
          const done = subtasks.filter(s => s.status === "done" || s.status === "completed").length;
          const total = subtasks.length;
          const pct = Math.round((done / total) * 100);
          return (
            <div>
              <div className="flex items-center justify-between text-sm mb-1">
                <span className="text-gray-500">{t("collab.subtasks")}</span>
                <span className="font-medium">{done}/{total} {t("collab.subtasksDone")}</span>
              </div>
              <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                <div
                  className="bg-green-500 h-2 rounded-full transition-all duration-300"
                  style={{ width: `${pct}%` }}
                />
              </div>
            </div>
          );
        })()}

        {(!task.assigned_to || task.assigned_to.length === 0) && subtasks.length === 0 && (
          <p className="text-sm text-gray-400">{t("collab.noAssignees")}</p>
        )}
      </div>

      {/* Invite Modal */}
      {showInvite && token && user && (
        <InviteModal
          taskId={id}
          token={token}
          userId={user.id}
          onClose={() => setShowInvite(false)}
        />
      )}
    </div>
  );
}
