"use client";

import { useMemo, useState } from "react";
import { ConfirmModal } from "@/components/confirm-modal/confirm-modal";
import { HabitLogCard } from "@/features/habits/components/habit-log-card";
import { HabitLogSheet } from "@/features/habits/components/habit-log-sheet";
import { HabitLogsHeader } from "@/features/habits/components/habit-logs-header";
import { habitsDict } from "@/features/habits/dict";
import {
  formatFrequencyLabel,
  formatTargetSummary,
} from "@/features/habits/utils/habit-helpers";
import {
  useCreateHabitLogMutation,
  useDeleteHabitLogMutation,
  useHabit,
  useHabitLogs,
  useUpdateHabitLogMutation,
} from "@/features/habits/hooks/use-habits";
import type {
  CreateHabitLogInput,
  HabitLog,
  UpdateHabitLogInput,
} from "@/features/habits/types";
import { formatLogLocalDate } from "@/features/habits/utils/habit-helpers";

type HabitLogsPageContentProps = {
  habitId: string;
};

export function HabitLogsPageContent({ habitId }: HabitLogsPageContentProps) {
  const [sheetOpen, setSheetOpen] = useState(false);
  const [sheetMode, setSheetMode] = useState<"create" | "edit">("create");
  const [activeLog, setActiveLog] = useState<HabitLog | null>(null);
  const [logToDelete, setLogToDelete] = useState<HabitLog | null>(null);

  const { data: habit, isLoading: isLoadingHabit } = useHabit(habitId);
  const { data: logs = [], isLoading: isLoadingLogs } = useHabitLogs(habitId);
  const createLogMutation = useCreateHabitLogMutation();
  const updateLogMutation = useUpdateHabitLogMutation();
  const deleteLogMutation = useDeleteHabitLogMutation();

  const openCreateSheet = () => {
    setSheetMode("create");
    setActiveLog(null);
    setSheetOpen(true);
  };

  const openEditSheet = (log: HabitLog) => {
    setSheetMode("edit");
    setActiveLog(log);
    setSheetOpen(true);
  };

  const closeSheet = () => {
    setSheetOpen(false);
    setActiveLog(null);
  };

  const handleSubmit = (payload: CreateHabitLogInput | UpdateHabitLogInput) => {
    if (!habit) return;

    if (sheetMode === "create") {
      createLogMutation.mutate(
        { habitId, payload: payload as CreateHabitLogInput },
        { onSuccess: () => closeSheet() },
      );
      return;
    }

    if (!activeLog) return;

    updateLogMutation.mutate(
      {
        habitId,
        logId: activeLog.id,
        payload: payload as UpdateHabitLogInput,
      },
      { onSuccess: () => closeSheet() },
    );
  };

  const handleConfirmDelete = () => {
    if (!logToDelete) return;

    deleteLogMutation.mutate(
      { habitId, logId: logToDelete.id },
      { onSuccess: () => setLogToDelete(null) },
    );
  };

  const deleteDescription = useMemo(() => {
    if (!logToDelete) return "";
    return habitsDict.logDeleteConfirmDescription.replace(
      "{date}",
      formatLogLocalDate(logToDelete.localDate),
    );
  }, [logToDelete]);

  const isLoading = isLoadingHabit || isLoadingLogs;

  return (
    <div className="mx-auto flex w-full max-w-3xl flex-1 flex-col pb-8">
      <HabitLogsHeader habitName={habit?.name} />

      {habit ? (
        <div className="mx-4 mt-2 space-y-1 rounded-[1.75rem] bg-card px-4 py-3 text-sm text-muted-foreground shadow-soft-sm sm:mx-6">
          <p>{formatTargetSummary(habit)}</p>
          <p>{formatFrequencyLabel(habit)}</p>
        </div>
      ) : null}

      <section className="mt-2 px-4 sm:px-6">
        <div className="mb-4 flex items-center justify-between gap-3">
          <p className="text-sm text-muted-foreground">{habitsDict.subtitle}</p>
          {habit ? (
            <button
              type="button"
              onClick={openCreateSheet}
              className="inline-flex h-10 shrink-0 items-center justify-center rounded-2xl bg-primary px-4 text-sm font-semibold text-primary-foreground shadow-soft-sm transition-all hover:brightness-105"
            >
              {habitsDict.logReport}
            </button>
          ) : null}
        </div>

        <div className="space-y-3">
          {isLoading ? (
            <div className="rounded-[1.75rem] bg-card px-5 py-8 text-center text-sm text-muted-foreground shadow-soft-sm">
              در حال بارگذاری...
            </div>
          ) : logs.length === 0 ? (
            <div className="rounded-[1.75rem] bg-card px-5 py-8 text-center text-sm text-muted-foreground shadow-soft-sm">
              {habitsDict.logsEmpty}
            </div>
          ) : (
            logs.map((log) => (
              <HabitLogCard
                key={log.id}
                log={log}
                unit={habit?.unit}
                onEdit={openEditSheet}
                onDelete={setLogToDelete}
              />
            ))
          )}
        </div>
      </section>

      <HabitLogSheet
        open={sheetOpen}
        mode={sheetMode}
        habit={habit ?? null}
        log={activeLog}
        existingLogs={logs}
        isSubmitting={createLogMutation.isPending || updateLogMutation.isPending}
        onClose={closeSheet}
        onSubmit={handleSubmit}
      />

      <ConfirmModal
        open={Boolean(logToDelete)}
        title={habitsDict.logDeleteConfirmTitle}
        description={deleteDescription}
        confirmLabel={habitsDict.delete}
        cancelLabel={habitsDict.cancel}
        isConfirming={deleteLogMutation.isPending}
        onConfirm={handleConfirmDelete}
        onCancel={() => setLogToDelete(null)}
      />
    </div>
  );
}
