"use client";

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

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

const TYPES: KeyPointItem["type"][] = ["key", "difficult"];

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

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

  function addItem() {
    onUpdate({
      ...data,
      keyPoints: [...data.keyPoints, { type: "key", text: "" }],
    });
  }

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

  return (
    <div className="space-y-2">
      <div className="text-xs text-on-surface-variant">
        {t("keyPoint.hint")}
      </div>
      {data.keyPoints.map((item, idx) => (
        <div key={`key-point-${idx}`} className="flex items-start gap-2">
          <select
            value={item.type}
            onChange={(e) => {
              const value = e.target.value;
              if (isKeyPointType(value)) {
                updateItem(idx, { type: value });
              }
            }}
            className="text-xs border border-outline-variant rounded px-1 py-1 bg-surface"
          >
            {TYPES.map((tp) => (
              <option key={tp} value={tp}>
                {t(`keyPoint.type.${tp}`)}
              </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-[40px]"
            placeholder={t("keyPoint.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("keyPoint.addItem")}
      </Button>
    </div>
  );
}
