"use client";

import { useTranslations } from "next-intl";
import { Plus, Trash2 } from "lucide-react";
import type { ReflectionBlockData, ReflectionItem } from "../../types";
import { isReflectionAspect } from "../../lib/type-guards";
import { Button } from "@/shared/components/ui/button";

interface Props {
  data: ReflectionBlockData;
  onUpdate: (data: ReflectionBlockData) => void;
}

const ASPECTS: ReflectionItem["aspect"][] = ["effectiveness", "problems", "improvements"];

export function ReflectionBlock({ data, onUpdate }: Props) {
  const t = useTranslations("lessonPreparation");

  function updateItem(index: number, patch: Partial<ReflectionItem>) {
    const next = data.reflection.map((it, i) =>
      i === index ? { ...it, ...patch } : it,
    );
    onUpdate({ ...data, reflection: next });
  }

  function addItem() {
    onUpdate({
      ...data,
      reflection: [...data.reflection, { aspect: "effectiveness", text: "" }],
    });
  }

  function removeItem(index: number) {
    onUpdate({
      ...data,
      reflection: data.reflection.filter((_, i) => i !== index),
    });
  }

  return (
    <div className="space-y-2">
      <div className="text-xs text-on-surface-variant">
        {t("reflection.hint")}
      </div>
      {data.reflection.map((item, idx) => (
        <div key={`reflection-${idx}`} className="flex items-start gap-2">
          <select
            value={item.aspect}
            onChange={(e) => {
              const value = e.target.value;
              if (isReflectionAspect(value)) {
                updateItem(idx, { aspect: value });
              }
            }}
            className="text-xs border border-outline-variant rounded px-1 py-1 bg-surface"
          >
            {ASPECTS.map((a) => (
              <option key={a} value={a}>
                {t(`reflection.aspect.${a}`)}
              </option>
            ))}
          </select>
          <textarea
            value={item.text}
            onChange={(e) => updateItem(idx, { text: e.target.value })}
            className="flex-1 text-sm border border-outline-variant rounded px-2 py-1 resize-y min-h-[60px]"
            placeholder={t("reflection.textPlaceholder")}
          />
          <Button
            variant="ghost"
            size="sm"
            className="!p-1 text-error"
            onClick={() => removeItem(idx)}
            aria-label={t("action.delete")}
          >
            <Trash2 className="w-3 h-3" />
          </Button>
        </div>
      ))}
      <Button variant="outline" size="sm" onClick={addItem}>
        <Plus className="w-3 h-3 mr-1" />
        {t("reflection.addItem")}
      </Button>
    </div>
  );
}
