"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { Plus, Trash2, Tag } from "lucide-react";
import type { NewTeachingBlockData, NewTeachingPoint } from "../../types";
import { Button } from "@/shared/components/ui/button";
import { KnowledgePointPicker } from "../knowledge-point-picker";
import { LessonPlanErrorBoundary } from "../lesson-plan-error-boundary";

interface Props {
  data: NewTeachingBlockData;
  textbookId?: string;
  chapterId?: string;
  onUpdate: (data: NewTeachingBlockData) => void;
}

export function NewTeachingBlock({ data, textbookId, chapterId, onUpdate }: Props) {
  const t = useTranslations("lessonPreparation");
  const [pickerFor, setPickerFor] = useState<number | null>(null);

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

  function addPoint() {
    onUpdate({
      ...data,
      teachingPoints: [
        ...data.teachingPoints,
        { knowledgePointIds: [], outline: "", boardNotes: "" },
      ],
    });
  }

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

  return (
    <div className="space-y-3">
      <div className="text-xs text-on-surface-variant">
        {t("newTeaching.hint")}
      </div>
      {data.teachingPoints.map((point, idx) => (
        <div key={`teaching-${idx}`} className="border border-outline-variant rounded p-2 space-y-2">
          <div className="flex items-center justify-between">
            <span className="text-xs font-medium">
              {t("newTeaching.pointIndex", { index: idx + 1 })}
            </span>
            <Button
              variant="ghost"
              size="sm"
              className="!p-1 text-error"
              onClick={() => removePoint(idx)}
              aria-label={t("action.delete")}
            >
              <Trash2 className="w-3 h-3" />
            </Button>
          </div>
          <div>
            <label className="text-xs block mb-1">
              {t("newTeaching.outlineLabel")}
            </label>
            <textarea
              value={point.outline}
              onChange={(e) => updatePoint(idx, { outline: e.target.value })}
              className="w-full text-sm border border-outline-variant rounded px-2 py-1 resize-y min-h-[60px]"
              placeholder={t("newTeaching.outlinePlaceholder")}
            />
          </div>
          <div>
            <label className="text-xs block mb-1">
              {t("newTeaching.boardNotesLabel")}
            </label>
            <textarea
              value={point.boardNotes}
              onChange={(e) => updatePoint(idx, { boardNotes: e.target.value })}
              className="w-full text-sm border border-outline-variant rounded px-2 py-1 resize-y min-h-[40px]"
              placeholder={t("newTeaching.boardNotesPlaceholder")}
            />
          </div>
          <div className="flex items-center gap-2 flex-wrap">
            {point.knowledgePointIds.length > 0 && (
              <span className="text-xs text-on-surface-variant">
                {t("knowledgePoint.linked", { count: point.knowledgePointIds.length })}
              </span>
            )}
            <button
              onClick={() => setPickerFor(idx)}
              className="text-xs text-primary hover:underline inline-flex items-center gap-1"
            >
              <Tag className="w-3 h-3" />
              {t("knowledgePoint.annotate")}
            </button>
          </div>
        </div>
      ))}
      <Button variant="outline" size="sm" onClick={addPoint}>
        <Plus className="w-3 h-3 mr-1" />
        {t("newTeaching.addPoint")}
      </Button>
      {pickerFor !== null && (
        <LessonPlanErrorBoundary>
          <KnowledgePointPicker
            textbookId={textbookId}
            chapterId={chapterId}
            selectedIds={data.teachingPoints[pickerFor]?.knowledgePointIds ?? []}
            onChange={(ids) => updatePoint(pickerFor, { knowledgePointIds: ids })}
            onClose={() => setPickerFor(null)}
          />
        </LessonPlanErrorBoundary>
      )}
    </div>
  );
}
