"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,
} from "@/lib/api";
import TaskForm from "@/components/TaskForm";
import StatusBadge from "@/components/StatusBadge";

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

export default function TaskDetailPage() {
  const { token } = 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 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] = await Promise.all([
        getTask(token, id),
        getGroups(token),
      ]);
      setTask(taskData);
      setGroups(groupsData.data || []);
    } 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-6">
      {/* Back button */}
      <button
        onClick={() => router.push("/tasks")}
        className="text-sm text-muted hover:text-foreground flex items-center gap-1"
      >
        <svg
          className="w-4 h-4"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M15 19l-7-7 7-7"
          />
        </svg>
        {t("common.back")}
      </button>

      {/* 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>

      {/* Quick status buttons */}
      <div className="flex gap-2 flex-wrap">
        {!taskDone && (
          <button
            onClick={() => handleQuickStatus("done")}
            className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg text-sm font-medium transition-colors"
          >
            {t("tasks.markDone")}
          </button>
        )}
        {task.status === "pending" && (
          <button
            onClick={() => handleQuickStatus("in_progress")}
            className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors"
          >
            {t("tasks.start")}
          </button>
        )}
        {taskDone && (
          <button
            onClick={() => handleQuickStatus("pending")}
            className="px-4 py-2 bg-yellow-600 hover:bg-yellow-700 text-white rounded-lg text-sm font-medium transition-colors"
          >
            {t("tasks.reopen")}
          </button>
        )}
      </div>

      {/* Action buttons */}
      <div className="flex gap-3">
        <button
          onClick={() => setEditing(true)}
          className="flex-1 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors font-medium"
        >
          {t("tasks.edit")}
        </button>
        <button
          onClick={handleDelete}
          disabled={deleting}
          className="px-6 py-2.5 border border-red-300 dark:border-red-800 text-red-600 dark:text-red-400 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors font-medium disabled:opacity-50"
        >
          {deleting ? t("tasks.deleting") : t("tasks.delete")}
        </button>
      </div>
    </div>
  );
}
