"use client";

import { useState } from "react";
import { Lock, X } from "lucide-react";
import { DescriptionInfoButton } from "@/components/description-info-button";
import { ItemDescriptionSheet } from "@/components/item-description-sheet";
import { habitsDict } from "@/features/habits/dict";
import type { HabitDayReport } from "@/features/habits/types";
import {
  formatTargetSummary,
  getCategoryLabel,
  isQuantitativeHabit,
} from "@/features/habits/utils/habit-helpers";
import type { ScheduledHabitForDay } from "@/features/tasks/utils/habit-calendar-helpers";
import { isHabitDayCompleted } from "@/features/tasks/utils/habit-calendar-helpers";
import { tasksDict } from "@/features/tasks/dict";
import { toast } from "@/lib/toast";

type TaskHabitCardProps = {
  item: ScheduledHabitForDay;
  dayReport?: HabitDayReport;
  isFutureDay?: boolean;
  onLog?: (item: ScheduledHabitForDay) => void;
  onToggle?: (item: ScheduledHabitForDay) => void;
  isLogPending?: boolean;
};

function getStatusLabel(status: HabitDayReport["status"]) {
  if (status === "NOT_SCHEDULED") {
    return "";
  }

  return habitsDict.logStatuses[status as keyof typeof habitsDict.logStatuses] ?? "";
}

export function TaskHabitCard({
  item,
  dayReport: dayReportOverride,
  isFutureDay = false,
  onLog,
  onToggle,
  isLogPending = false,
}: TaskHabitCardProps) {
  const [descriptionOpen, setDescriptionOpen] = useState(false);
  const { habit } = item;
  const habitDescription = habit.description?.trim() ?? "";
  const dayReport = dayReportOverride ?? item.dayReport;
  const completed = isHabitDayCompleted(dayReport);
  const skipped = dayReport.status === "SKIPPED";
  const isBooleanHabit = !isQuantitativeHabit(habit);
  const statusLabel = getStatusLabel(dayReport.status);
  const subtitle = [formatTargetSummary(habit), getCategoryLabel(habit.category)]
    .filter(Boolean)
    .join(" · ");
  const showFutureLogIcon = isFutureDay && !completed && !skipped;

  const handleLogClick = () => {
    if (isFutureDay) {
      toast.warning(habitsDict.logFutureDateNotAllowed);
      return;
    }

    if (isBooleanHabit && onToggle) {
      onToggle(item);
      return;
    }

    onLog?.(item);
  };

  return (
    <article className="flex items-center gap-3 rounded-[1.75rem] bg-card px-4 py-4 shadow-soft-sm sm:gap-4 sm:px-5">
      <button
        type="button"
        aria-label={tasksDict.logHabit}
        disabled={isLogPending && !isBooleanHabit}
        onClick={handleLogClick}
        className={`inline-flex size-10 shrink-0 items-center justify-center rounded-full border-2 transition-all ${
          completed
            ? "border-transparent bg-gradient-to-br from-[#2EC4B6] to-[#56CCF2] text-white shadow-soft-sm"
            : skipped
              ? "border-destructive/60 bg-destructive/10 text-destructive shadow-soft-sm"
              : showFutureLogIcon
                ? "border-muted-foreground/30 bg-muted/40 text-muted-foreground"
                : "border-[#1D2D50] bg-transparent text-transparent dark:border-foreground"
        }`}
      >
        {completed ? (
          <svg
            aria-hidden="true"
            className="size-5"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={2.5}
          >
            <path d="M6 12l4 4 8-8" />
          </svg>
        ) : skipped ? (
          <X aria-hidden className="size-5" strokeWidth={2.5} />
        ) : showFutureLogIcon ? (
          <Lock aria-hidden className="size-5" strokeWidth={2} />
        ) : null}
      </button>

      <div className="flex min-w-0 flex-1 items-start gap-1 sm:gap-2">
        <button
          type="button"
          onClick={handleLogClick}
          className="min-w-0 flex-1 text-start"
        >
          <span className="mb-1 inline-block max-w-full truncate rounded-full bg-[#2EC4B6]/15 px-2.5 py-1 text-[11px] font-semibold text-[#2EC4B6] sm:text-xs">
            {habitsDict.title}
          </span>
          <h3
            className={`truncate text-base font-bold text-[#1D2D50] dark:text-card-foreground sm:text-lg ${
              completed ? "line-through opacity-60" : ""
            }`}
          >
            {habit.name}
          </h3>
          <p className="mt-1 truncate text-sm text-muted-foreground">{subtitle}</p>
        </button>

        {habitDescription ? (
          <DescriptionInfoButton onClick={() => setDescriptionOpen(true)} />
        ) : null}
      </div>

      {habitDescription ? (
        <ItemDescriptionSheet
          open={descriptionOpen}
          title={habit.name}
          description={habitDescription}
          onClose={() => setDescriptionOpen(false)}
        />
      ) : null}
    </article>
  );
}
