"use client";

import { useState, type MouseEvent } from "react";
import { useRouter } from "next/navigation";
import { Divider } from "@/components/divider";
import { DynamicLucideIcon, getIconConfigFromDetails } from "@/components/lucide-icon";
import { tooltipDict } from "@/components/tooltip/dict";
import type { Habit } from "@/features/habits/types";
import { HabitCardMenu } from "@/features/habits/components/habit-card-menu";
import { HabitInfoSheet } from "@/features/habits/components/habit-info-sheet";
import { HabitWeekTracker } from "@/features/habits/components/habit-week-tracker";
import { habitsDict } from "@/features/habits/dict";
import {
  formatFrequencyBadge,
  getFrequencyBadgeClass,
} from "@/features/habits/utils/habit-helpers";
import { toPersianDigits } from "@/lib/to-english-digits";

type HabitCardProps = {
  habit: Habit;
  onEdit: (habit: Habit) => void;
  onDelete: (habit: Habit) => void;
};

function ChainIcon() {
  return (
    <svg
      aria-hidden="true"
      className="size-4 shrink-0"
      fill="none"
      viewBox="0 0 24 24"
      stroke="currentColor"
      strokeWidth={2}
    >
      <path
        strokeLinecap="round"
        strokeLinejoin="round"
        d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"
      />
      <path
        strokeLinecap="round"
        strokeLinejoin="round"
        d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"
      />
    </svg>
  );
}

function InfoIcon() {
  return (
    <svg
      aria-hidden="true"
      className="size-4"
      fill="none"
      viewBox="0 0 24 24"
      stroke="currentColor"
      strokeWidth={1.75}
    >
      <circle cx="12" cy="12" r="9" />
      <path d="M12 10v6" />
      <path d="M12 7h.01" />
    </svg>
  );
}

function BookmarkIcon() {
  return (
    <svg
      aria-hidden="true"
      className="size-5"
      fill="none"
      viewBox="0 0 24 24"
      stroke="currentColor"
      strokeWidth={1.75}
    >
      <path d="M7 4h10a2 2 0 0 1 2 2v14l-7-3.5L5 20V6a2 2 0 0 1 2-2Z" />
    </svg>
  );
}

export function HabitCard({ habit, onEdit, onDelete }: HabitCardProps) {
  const router = useRouter();
  const [infoOpen, setInfoOpen] = useState(false);
  const logsHref = `/panel/habits/${habit.id}/logs`;
  const currentStreak = habit.stats?.currentStreak ?? 0;
  const last7Days = habit.stats?.last7Days ?? [];
  const categoryIcon = getIconConfigFromDetails(habit.category?.details);
  const hasCategoryIcon = Boolean(categoryIcon.iconComponent);

  const navigateToLogs = () => {
    router.push(logsHref);
  };

  const openInfoSheet = (event: MouseEvent<HTMLButtonElement>) => {
    event.stopPropagation();
    setInfoOpen(true);
  };

  return (
    <>
      <article
        role="link"
        tabIndex={0}
        aria-label={`${habit.name} - ${habitsDict.viewLogs}`}
        onClick={navigateToLogs}
        onKeyDown={(event) => {
          if (event.key === "Enter" || event.key === " ") {
            event.preventDefault();
            navigateToLogs();
          }
        }}
        className={`cursor-pointer rounded-[1.75rem] bg-card px-4 py-4 shadow-soft-sm transition-colors hover:bg-card/90 sm:px-5 ${
          !habit.isActive || habit.isArchived ? "opacity-75" : ""
        }`}
      >
        <div className="flex items-start justify-between gap-3">
          <div className="min-w-0 flex-1">
            <div className="flex min-w-0 items-center gap-1.5">
              <button
                type="button"
                aria-label={tooltipDict.infoLabel}
                onClick={openInfoSheet}
                className="inline-flex size-6 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground"
              >
                <InfoIcon />
              </button>
              <h3 className="truncate text-base font-bold text-[#1D2D50] dark:text-card-foreground sm:text-lg">
                {habit.name}
              </h3>
            </div>

            <span
              className={`mt-1.5 inline-flex rounded-full px-2.5 py-0.5 text-[11px] font-semibold ${getFrequencyBadgeClass(habit)}`}
            >
              {formatFrequencyBadge(habit)}
            </span>
          </div>

          <div
            className={
              hasCategoryIcon
                ? "inline-flex size-11 shrink-0 items-center justify-center rounded-2xl shadow-soft-sm ring-1 ring-border"
                : "inline-flex size-11 shrink-0 items-center justify-center rounded-2xl bg-gradient-to-br from-[#2EC4B6] to-[#56CCF2] text-white shadow-soft-sm"
            }
            style={
              hasCategoryIcon && categoryIcon.color
                ? {
                    color: categoryIcon.color,
                    backgroundColor: `${categoryIcon.color}1f`,
                  }
                : undefined
            }
          >
            {hasCategoryIcon ? (
              <DynamicLucideIcon
                iconComponent={categoryIcon.iconComponent}
                name={categoryIcon.icon ?? undefined}
                color={categoryIcon.color ?? undefined}
                size={20}
              />
            ) : (
              <BookmarkIcon />
            )}
          </div>
        </div>

        <HabitWeekTracker days={last7Days} />

        <Divider className="mt-4" />

        <div className="mt-3 flex items-center justify-between gap-3">
          <div
            className="flex items-center gap-1.5 text-sm font-medium text-muted-foreground"
            aria-label={`${habitsDict.currentStreak}: ${currentStreak}`}
          >
            <ChainIcon />
            <span>{toPersianDigits(currentStreak)}</span>
          </div>

          <div onClick={(event) => event.stopPropagation()}>
            <HabitCardMenu
              menuPlacement="top"
              onEdit={() => onEdit(habit)}
              onDelete={() => onDelete(habit)}
            />
          </div>
        </div>
      </article>

      <HabitInfoSheet
        open={infoOpen}
        habit={habit}
        onClose={() => setInfoOpen(false)}
      />
    </>
  );
}
