"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";
import TaskDetailActions from "@/components/features/TaskDetailActions";
import InlineEditField from "@/components/features/InlineEditField";

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 || []);
      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 handleInlineUpdate(field: string, value: string) {
    if (!token || !id) return;
    try {
      await updateTask(token, id, { [field]: value });
      loadTask();
    } catch (err) {
      setError(err instanceof Error ? err.message : t("common.error"));
    }
  }

  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 px-4 sm:px-0">
      {/* Action bar - all icon buttons in one compact row */}
      <TaskDetailActions
        taskDone={taskDone}
        deleting={deleting}
        onBack={() => router.push("/tasks")}
        onEdit={() => setEditing(true)}
        onDelete={handleDelete}
        onToggleStatus={() => handleQuickStatus(taskDone ? "pending" : "done")}
        onInvite={() => setShowInvite(true)}
        onCollaborate={() => router.push(`/tasks/${id}/collaborate`)}
        t={t}
      />

      {/* Task detail card with inline editing */}
      <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 flex-1 min-w-0">
            {task.group_icon && (
              <span className="text-2xl flex-shrink-0">{task.group_icon}</span>
            )}
            <InlineEditField
              value={task.title}
              onSave={(val) => handleInlineUpdate("title", val)}
              className={`text-xl font-bold ${taskDone ? "line-through text-muted" : ""}`}
            />
          </div>
          <StatusBadge status={task.status} size="md" />
        </div>

        <div className="mb-4">
          <InlineEditField
            value={task.description || ""}
            onSave={(val) => handleInlineUpdate("description", val)}
            as="textarea"
            multiline
            placeholder={t("tasks.form.descPlaceholder")}
            className="text-muted whitespace-pre-wrap leading-relaxed"
          />
        </div>

        <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>
        </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>
  );
}
