"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { createLessonPlanAction } from "../actions";
import { useRouter } from "next/navigation";
import { Button } from "@/shared/components/ui/button";
import { SYSTEM_TEMPLATES } from "../constants";
import { useLessonPlanTrackerSafe } from "../providers/lesson-plan-provider";

export function TemplatePicker() {
  const t = useTranslations("lessonPreparation");
  const router = useRouter();
  const tracker = useLessonPlanTrackerSafe();
  const [selected, setSelected] = useState<string>("");
  const [title, setTitle] = useState("");
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(formData: FormData) {
    setError(null);
    formData.set("templateId", selected);
    formData.set("title", title);
    const res = await createLessonPlanAction(null, formData);
    if (res.success && res.data) {
      tracker.track("lesson_plan.create", { planId: res.data.planId, templateId: selected });
      router.push(`/teacher/lesson-plans/${res.data.planId}/edit`);
    } else {
      setError(res.message ?? t("error.createFailed"));
    }
  }

  return (
    <form action={handleSubmit} className="max-w-3xl mx-auto p-6 space-y-6">
      <div>
        <label className="font-title-md block mb-2">{t("template.titleLabel")}</label>
        <input
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          required
          className="w-full border border-outline-variant rounded-lg px-3 py-2"
          placeholder={t("template.titlePlaceholder")}
        />
      </div>
      <div>
        <label className="font-title-md block mb-2">{t("template.selectLabel")}</label>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          {SYSTEM_TEMPLATES.map((tpl) => (
            <button
              type="button"
              key={tpl.id}
              onClick={() => setSelected(tpl.id)}
              className={`text-left p-4 border-2 rounded-lg transition-colors ${
                selected === tpl.id
                  ? "border-primary bg-primary/5"
                  : "border-outline-variant hover:border-primary/50"
              }`}
            >
              <div className="font-title-md">{t(`template.names.${tpl.id}`)}</div>
              <div className="text-sm text-on-surface-variant mt-1">
                {tpl.blocks.length === 0
                  ? t("template.blankHint")
                  : t("template.blockCount", { count: tpl.blocks.length })}
              </div>
            </button>
          ))}
        </div>
      </div>
      {error && <p className="text-error text-sm">{error}</p>}
      <Button type="submit" disabled={!selected || !title}>
        {t("action.create")}
      </Button>
    </form>
  );
}
