"use client";

import { useEffect } from "react";
import { habitsDict } from "@/features/habits/dict";
import type { Habit } from "@/features/habits/types";
import {
  formatFrequencyLabel,
  formatTargetSummary,
} from "@/features/habits/utils/habit-helpers";

type HabitInfoSheetProps = {
  open: boolean;
  habit: Habit | null;
  onClose: () => void;
};

type InfoRowProps = {
  label: string;
  value: string;
};

function InfoRow({ label, value }: InfoRowProps) {
  return (
    <div className="space-y-1">
      <p className="text-xs font-medium text-muted-foreground">{label}</p>
      <p className="text-sm leading-6 text-card-foreground">{value}</p>
    </div>
  );
}

export function HabitInfoSheet({ open, habit, onClose }: HabitInfoSheetProps) {
  useEffect(() => {
    if (!open) {
      return;
    }

    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        onClose();
      }
    };

    document.addEventListener("keydown", handleEscape);
    document.body.style.overflow = "hidden";

    return () => {
      document.removeEventListener("keydown", handleEscape);
      document.body.style.overflow = "";
    };
  }, [open, onClose]);

  if (!open || !habit) {
    return null;
  }

  return (
    <div className="fixed inset-0 z-[100] flex items-end justify-center bg-black/40 p-0 sm:items-center sm:p-4">
      <button
        type="button"
        aria-label={habitsDict.cancel}
        className="absolute inset-0"
        onClick={onClose}
      />

      <div
        role="dialog"
        aria-modal="true"
        aria-labelledby="habit-info-title"
        className="relative z-10 w-full max-w-lg overflow-hidden rounded-t-3xl bg-card shadow-soft sm:rounded-3xl"
        onClick={(event) => event.stopPropagation()}
      >
        <div className="px-6 pt-4">
          <div className="mx-auto mb-4 h-1.5 w-12 rounded-full bg-border sm:hidden" />
          <div className="pb-2 text-center sm:text-start">
            <h2
              id="habit-info-title"
              className="text-lg font-bold text-card-foreground"
            >
              {habitsDict.habitInfoTitle}
            </h2>
            <p className="mt-1 truncate text-sm text-muted-foreground">
              {habit.name}
            </p>
          </div>
        </div>

        <div className="space-y-4 px-6 pb-6 pt-2">
          <InfoRow
            label={habitsDict.descriptionLabel}
            value={habit.description?.trim() || habitsDict.noDescription}
          />
          <InfoRow
            label={habitsDict.targetTypeLabel}
            value={formatTargetSummary(habit)}
          />
          <InfoRow
            label={habitsDict.frequencyLabel}
            value={formatFrequencyLabel(habit)}
          />
        </div>
      </div>
    </div>
  );
}
