"use client";

import { useMemo, useState } from "react";
import { ConfirmModal } from "@/components/confirm-modal/confirm-modal";
import { useHabits } from "@/features/habits/hooks/use-habits";
import { GoalCard } from "@/features/goals/components/goal-card";
import { GoalSheet } from "@/features/goals/components/goal-sheet";
import { GoalsFab } from "@/features/goals/components/goals-fab";
import { GoalsHeader } from "@/features/goals/components/goals-header";
import { goalsDict } from "@/features/goals/dict";
import {
  useDeleteGoalMutation,
  useGoals,
  useSaveGoalMutation,
} from "@/features/goals/hooks/use-goals";
import type { Goal, GoalFormValues, GoalStatus } from "@/features/goals/types";
import { useTasks } from "@/features/tasks/hooks/use-tasks";

type GoalListFilter = "active" | "completed";

function isCompletedGoal(status: GoalStatus) {
  return status === "COMPLETED";
}

export function GoalsPageContent() {
  const [sheetOpen, setSheetOpen] = useState(false);
  const [sheetMode, setSheetMode] = useState<"create" | "edit">("create");
  const [activeGoal, setActiveGoal] = useState<Goal | null>(null);
  const [goalToDelete, setGoalToDelete] = useState<Goal | null>(null);
  const [listFilter, setListFilter] = useState<GoalListFilter>("active");

  const { data: goals = [], isLoading } = useGoals();
  const { data: habits = [] } = useHabits();
  const { data: tasks = [] } = useTasks();
  const saveGoalMutation = useSaveGoalMutation();
  const deleteGoalMutation = useDeleteGoalMutation();

  const visibleHabits = useMemo(
    () => habits.filter((habit) => !habit.isArchived && habit.isActive),
    [habits],
  );

  const filteredGoals = useMemo(() => {
    return goals.filter((goal) =>
      listFilter === "completed"
        ? isCompletedGoal(goal.status)
        : !isCompletedGoal(goal.status),
    );
  }, [goals, listFilter]);

  const emptyMessage =
    goals.length === 0
      ? goalsDict.empty
      : listFilter === "completed"
        ? goalsDict.filterCompletedEmpty
        : goalsDict.filterActiveEmpty;

  const openCreateSheet = () => {
    setSheetMode("create");
    setActiveGoal(null);
    setSheetOpen(true);
  };

  const openEditSheet = (goal: Goal) => {
    setSheetMode("edit");
    setActiveGoal(goal);
    setSheetOpen(true);
  };

  const closeSheet = () => {
    setSheetOpen(false);
    setActiveGoal(null);
  };

  const handleSubmit = (values: GoalFormValues) => {
    saveGoalMutation.mutate(
      {
        mode: sheetMode,
        goalId: activeGoal?.id,
        values,
        existingSourceIds: activeGoal?.sources.map((source) => source.id) ?? [],
      },
      { onSuccess: () => closeSheet() },
    );
  };

  const handleDeleteRequest = (goal: Goal) => {
    setGoalToDelete(goal);
  };

  const handleConfirmDelete = () => {
    if (!goalToDelete) return;

    deleteGoalMutation.mutate(goalToDelete.id, {
      onSuccess: () => {
        setGoalToDelete(null);
        if (activeGoal?.id === goalToDelete.id) closeSheet();
      },
    });
  };

  const deleteDescription = useMemo(() => {
    if (!goalToDelete) return "";
    return goalsDict.deleteConfirmDescription.replace("{title}", goalToDelete.title);
  }, [goalToDelete]);

  return (
    <div className="mx-auto flex w-full max-w-3xl flex-1 flex-col pb-8">
      <GoalsHeader />

      <section className="mt-2 px-4 sm:px-6">
        <div className="mb-4 flex gap-2">
          <button
            type="button"
            onClick={() => setListFilter("active")}
            className={`inline-flex h-10 flex-1 items-center justify-center rounded-2xl px-4 text-sm font-semibold transition-colors ${
              listFilter === "active"
                ? "bg-primary text-primary-foreground shadow-soft-sm"
                : "bg-input text-foreground ring-1 ring-border hover:bg-muted"
            }`}
          >
            {goalsDict.filterActive}
          </button>
          <button
            type="button"
            onClick={() => setListFilter("completed")}
            className={`inline-flex h-10 flex-1 items-center justify-center rounded-2xl px-4 text-sm font-semibold transition-colors ${
              listFilter === "completed"
                ? "bg-primary text-primary-foreground shadow-soft-sm"
                : "bg-input text-foreground ring-1 ring-border hover:bg-muted"
            }`}
          >
            {goalsDict.filterCompleted}
          </button>
        </div>

        <div className="space-y-3 pb-12">
          {isLoading ? (
            <div className="rounded-[1.75rem] bg-card px-5 py-8 text-center text-sm text-muted-foreground shadow-soft-sm">
              در حال بارگذاری...
            </div>
          ) : filteredGoals.length === 0 ? (
            <div className="rounded-[1.75rem] bg-card px-5 py-8 text-center text-sm text-muted-foreground shadow-soft-sm">
              {emptyMessage}
            </div>
          ) : (
            filteredGoals.map((goal) => (
              <GoalCard
                key={goal.id}
                goal={goal}
                habits={visibleHabits}
                tasks={tasks}
                onEdit={openEditSheet}
                onDelete={handleDeleteRequest}
              />
            ))
          )}
        </div>
      </section>

      <GoalsFab onClick={openCreateSheet} />

      <GoalSheet
        open={sheetOpen}
        mode={sheetMode}
        goal={activeGoal}
        habits={visibleHabits}
        tasks={tasks}
        isSubmitting={saveGoalMutation.isPending}
        isDeleting={deleteGoalMutation.isPending}
        onClose={closeSheet}
        onSubmit={handleSubmit}
        onDelete={
          sheetMode === "edit" && activeGoal
            ? () => handleDeleteRequest(activeGoal)
            : undefined
        }
      />

      <ConfirmModal
        open={Boolean(goalToDelete)}
        title={goalsDict.deleteConfirmTitle}
        description={deleteDescription}
        confirmLabel={goalsDict.delete}
        cancelLabel={goalsDict.cancel}
        isConfirming={deleteGoalMutation.isPending}
        onConfirm={handleConfirmDelete}
        onCancel={() => setGoalToDelete(null)}
      />
    </div>
  );
}
