"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { useLessonPlanEditor } from "../../hooks/use-lesson-plan-editor";
import { Button } from "@/shared/components/ui/button";
import { Plus, Trash2 } from "lucide-react";
import { createId } from "@paralleldrive/cuid2";
import type {
  TextStudyBlockData,
  TextStudyAnnotation,
} from "../../types";

interface Props {
  blockId: string;
  data: TextStudyBlockData;
}

export function TextStudyBlock({ blockId, data }: Props) {
  const t = useTranslations("lessonPreparation");
  const { updateNode } = useLessonPlanEditor();
  const [selection, setSelection] = useState<{
    start: number;
    end: number;
  } | null>(null);

  function update(patch: Partial<TextStudyBlockData>) {
    updateNode(blockId, { data: { ...data, ...patch } });
  }

  function handleTextSelect(e: React.MouseEvent<HTMLTextAreaElement>) {
    const textarea = e.currentTarget;
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    if (end > start) setSelection({ start, end });
  }

  function addAnnotation() {
    if (!selection) {
      toast.error(t("textStudy.selectFirst"));
      return;
    }
    const ann: TextStudyAnnotation = {
      id: createId(),
      anchor: selection,
      nodeType: "language_feature",
      title: t("textStudy.annotationTitle"),
      note: "",
      color: "yellow",
    };
    update({ annotations: [...data.annotations, ann] });
    setSelection(null);
  }

  function removeAnnotation(id: string) {
    update({
      annotations: data.annotations.filter((a) => a.id !== id),
    });
  }

  return (
    <div className="space-y-3">
      <div>
        <label className="text-sm font-medium">{t("textStudy.sourceTextLabel")}</label>
        <textarea
          value={data.sourceText}
          onChange={(e) => update({ sourceText: e.target.value })}
          onMouseUp={handleTextSelect}
          className="w-full border rounded p-2 mt-1 min-h-[120px] font-serif leading-loose"
          placeholder={t("textStudy.sourceTextPlaceholder")}
        />
      </div>
      <Button
        variant="outline"
        size="sm"
        onClick={addAnnotation}
        disabled={!selection}
      >
        <Plus className="w-3 h-3 mr-1" aria-hidden="true" />
        {t("textStudy.addAnnotation")}
      </Button>
      {data.annotations.length > 0 && (
        <div className="space-y-2">
          {data.annotations.map((ann) => (
            <div
              key={ann.id}
              className="border-l-4 border-secondary-container pl-3 py-1"
            >
              <div className="flex justify-between items-center">
                <input
                  value={ann.title}
                  onChange={(e) =>
                    update({
                      annotations: data.annotations.map((a) =>
                        a.id === ann.id
                          ? { ...a, title: e.target.value }
                          : a,
                      ),
                    })
                  }
                  className="font-medium text-sm bg-transparent flex-1"
                />
                <button onClick={() => removeAnnotation(ann.id)} aria-label={t("action.delete")}>
                  <Trash2 className="w-3 h-3 text-error" aria-hidden="true" />
                </button>
              </div>
              <textarea
                value={ann.note}
                onChange={(e) =>
                  update({
                    annotations: data.annotations.map((a) =>
                      a.id === ann.id
                        ? { ...a, note: e.target.value }
                        : a,
                    ),
                  })
                }
                className="w-full text-sm border rounded p-1 mt-1 min-h-[40px]"
                placeholder={t("textStudy.annotationNotePlaceholder")}
              />
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
