"use client";

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

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

const TYPES: HomeworkAssignment["type"][] = ["exercise", "reading", "writing"];

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

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

  function addItem() {
    onUpdate({
      ...data,
      assignments: [...data.assignments, { type: "exercise", description: "" }],
    });
  }

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

  return (
    <div className="space-y-2">
      <div className="text-xs text-on-surface-variant">
        {t("homework.hint")}
      </div>
      {data.assignments.map((item, idx) => (
        <div key={`homework-${idx}`} className="flex items-start gap-2">
          <select
            value={item.type}
            onChange={(e) => {
              const value = e.target.value;
              if (isHomeworkType(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(`homework.type.${tp}`)}
              </option>
            ))}
          </select>
          <input
            type="text"
            value={item.refId ?? ""}
            onChange={(e) => updateItem(idx, { refId: e.target.value || undefined })}
            className="w-32 text-sm border border-outline-variant rounded px-2 py-1"
            placeholder={t("homework.refIdPlaceholder")}
          />
          <input
            type="text"
            value={item.description}
            onChange={(e) => updateItem(idx, { description: e.target.value })}
            className="flex-1 text-sm border border-outline-variant rounded px-2 py-1"
            placeholder={t("homework.descriptionPlaceholder")}
          />
          <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("homework.addItem")}
      </Button>
    </div>
  );
}
