"use client";

import { useEffect, useState, useCallback, useMemo } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/lib/auth";
import { getTasks, getGroups, createTask, updateTask, Task, Group } from "@/lib/api";
import { useTranslation } from "@/lib/i18n";
import TaskCard from "@/components/TaskCard";
import GroupSelector from "@/components/GroupSelector";
import TaskModal from "@/components/TaskModal";
import { useSwipeable } from "react-swipeable";

type StatusFilter = "all" | "pending" | "in_progress" | "done" | "cancelled";

export default function TasksPage() {
  const { token } = useAuth();
  const { t } = useTranslation();
  const router = useRouter();
  const [tasks, setTasks] = useState<Task[]>([]);
  const [groups, setGroups] = useState<Group[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedGroup, setSelectedGroup] = useState<string | null>(null);
  const [statusFilter, setStatusFilter] = useState<StatusFilter>("all");
  const [showForm, setShowForm] = useState(false);
  const [swipeDirection, setSwipeDirection] = useState<"left" | "right" | null>(null);
  const [swipeOverlay, setSwipeOverlay] = useState<{ name: string; icon: string | null } | null>(null);

  // Build group order: [null (all), group1.id, group2.id, ...]
  const groupOrder = useMemo(() => {
    return [null, ...groups.map((g) => g.id)];
  }, [groups]);

  const currentGroupIndex = useMemo(() => {
    return groupOrder.indexOf(selectedGroup);
  }, [groupOrder, selectedGroup]);

  const loadData = useCallback(async () => {
    if (!token) return;
    setLoading(true);
    try {
      const params: Record<string, string> = {};
      if (selectedGroup) params.group_id = selectedGroup;
      if (statusFilter !== "all") params.status = statusFilter;

      const [tasksRes, groupsRes] = await Promise.all([
        getTasks(token, Object.keys(params).length > 0 ? params : undefined),
        getGroups(token),
      ]);
      setTasks(tasksRes.data || []);
      setGroups(groupsRes.data || []);
    } catch (err) {
      console.error("Load error:", err);
    } finally {
      setLoading(false);
    }
  }, [token, selectedGroup, statusFilter]);

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

  // Navigate to next/previous group via swipe
  const navigateGroup = useCallback(
    (direction: "left" | "right") => {
      if (groupOrder.length <= 1) return;
      const newIndex =
        direction === "left"
          ? (currentGroupIndex + 1) % groupOrder.length
          : (currentGroupIndex - 1 + groupOrder.length) % groupOrder.length;
      const newGroupId = groupOrder[newIndex];

      if (newGroupId === null) {
        setSwipeOverlay({ name: t("tasks.all"), icon: null });
      } else {
        const group = groups.find((g) => g.id === newGroupId);
        setSwipeOverlay({ name: group?.name || "", icon: group?.icon || null });
      }
      setSwipeDirection(direction);
      setSelectedGroup(newGroupId);

      setTimeout(() => {
        setSwipeOverlay(null);
        setSwipeDirection(null);
      }, 600);
    },
    [groupOrder, currentGroupIndex, groups, t]
  );

  // Swipe handlers for cycling groups
  const swipeHandlers = useSwipeable({
    onSwipedLeft: () => navigateGroup("left"),
    onSwipedRight: () => navigateGroup("right"),
    trackMouse: false,
    trackTouch: true,
    preventScrollOnSwipe: false,
    delta: 50,
    swipeDuration: 500,
  });

  async function handleCreateTask(data: Partial<Task>) {
    if (!token) return;
    await createTask(token, data);
    setShowForm(false);
    loadData();
  }

  async function handleCompleteTask(taskId: string) {
    if (!token) return;
    try {
      await updateTask(token, taskId, { status: "done" });
      loadData();
    } catch (err) {
      console.error("Complete error:", err);
    }
  }

  const statusOptions: { value: StatusFilter; label: string }[] = [
    { value: "all", label: t("tasks.all") },
    { value: "pending", label: t("tasks.status.pending") },
    { value: "in_progress", label: t("tasks.status.in_progress") },
    { value: "done", label: t("tasks.status.done") },
    { value: "cancelled", label: t("tasks.status.cancelled") },
  ];

  if (!token) return null;

  return (
    <div className="space-y-2 pb-24 sm:pb-8 px-4 sm:px-0">
      {/* Group dropdown + Status pills — single compact row */}
      <div className="flex items-center gap-3 flex-nowrap">
        <div className="flex-shrink-0">
          <GroupSelector
            groups={groups}
            selected={selectedGroup}
            onSelect={setSelectedGroup}
          />
        </div>
        <div className="flex gap-1 overflow-x-auto scrollbar-hide flex-1 min-w-0">
          {statusOptions.map((opt) => (
            <button
              key={opt.value}
              onClick={() => setStatusFilter(opt.value)}
              className={`flex-shrink-0 px-2.5 py-1 rounded-full text-[11px] font-medium transition-all ${
                statusFilter === opt.value
                  ? "bg-gray-800 text-white dark:bg-white dark:text-gray-900"
                  : "bg-gray-100 dark:bg-gray-800 text-gray-500 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-700"
              }`}
            >
              {opt.label}
            </button>
          ))}
        </div>
      </div>

      {/* Swipeable task list area */}
      <div {...swipeHandlers} className="relative min-h-[200px]">
        {/* Swipe overlay */}
        {swipeOverlay && (
          <div className="absolute inset-0 z-30 flex items-center justify-center pointer-events-none">
            <div
              className={`bg-black/70 dark:bg-white/20 backdrop-blur-md text-white px-6 py-3 rounded-2xl flex items-center gap-3 shadow-2xl ${
                swipeDirection === "left" ? "animate-slideOverlayLeft" : "animate-slideOverlayRight"
              }`}
            >
              {swipeOverlay.icon && (
                <span className="text-2xl">{swipeOverlay.icon}</span>
              )}
              <span className="text-lg font-semibold">{swipeOverlay.name}</span>
            </div>
          </div>
        )}

        {/* Task list */}
        <div
          className={`transition-all duration-300 ease-out ${
            swipeDirection === "left"
              ? "animate-slideContentLeft"
              : swipeDirection === "right"
              ? "animate-slideContentRight"
              : ""
          }`}
        >
          {loading ? (
            <div className="flex justify-center py-8">
              <div className="animate-spin rounded-full h-7 w-7 border-b-2 border-blue-600" />
            </div>
          ) : tasks.length === 0 ? (
            <div className="text-center py-12">
              <div className="text-4xl mb-3 opacity-50">&#9744;</div>
              <p className="text-muted text-base font-medium">{t("tasks.noTasks")}</p>
              <p className="text-muted text-sm mt-1">
                {t("tasks.createFirst")}
              </p>
            </div>
          ) : (
            <div className="space-y-1">
              {tasks.map((task) => (
                <TaskCard
                  key={task.id}
                  task={task}
                  onComplete={handleCompleteTask}
                />
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Floating action button */}
      <button
        onClick={() => setShowForm(true)}
        className="fixed bottom-20 sm:bottom-6 right-4 sm:right-6 w-14 h-14 bg-blue-600 hover:bg-blue-700 active:bg-blue-800 text-white rounded-full shadow-lg hover:shadow-xl active:shadow-md transition-all duration-200 flex items-center justify-center z-40 hover:scale-105 active:scale-95"
        aria-label={t("tasks.add")}
      >
        <svg
          className="w-7 h-7"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
          strokeWidth={2.5}
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            d="M12 4v16m8-8H4"
          />
        </svg>
      </button>

      {/* Add task modal */}
      {showForm && (
        <TaskModal
          groups={groups}
          onSubmit={handleCreateTask}
          onClose={() => setShowForm(false)}
        />
      )}
    </div>
  );
}
