"use client";

import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { useLessonPlanContextSafe, useLessonPlanTrackerSafe } from "../providers/lesson-plan-provider";
import { Button } from "@/shared/components/ui/button";
import { FocusTrap } from "@/shared/components/a11y/focus-trap";
import { X } from "lucide-react";

interface Props {
  planId: string;
  blockId: string;
  classes: { id: string; name: string }[];
  onClose: () => void;
  onPublished: () => void;
}

export function PublishHomeworkDialog({
  planId,
  blockId,
  classes,
  onClose,
  onPublished,
}: Props) {
  const t = useTranslations("lessonPreparation");
  const ctx = useLessonPlanContextSafe();
  const service = ctx?.service ?? null;
  const tracker = useLessonPlanTrackerSafe();
  const [selectedClasses, setSelectedClasses] = useState<string[]>([]);
  const [availableAt, setAvailableAt] = useState("");
  const [dueAt, setDueAt] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  // P1-1 修复：ESC 键关闭对话框
  useEffect(() => {
    function handleEsc(e: KeyboardEvent) {
      if (e.key === "Escape") onClose();
    }
    document.addEventListener("keydown", handleEsc);
    return () => document.removeEventListener("keydown", handleEsc);
  }, [onClose]);

  async function handlePublish() {
    if (!service) return;
    if (selectedClasses.length === 0) {
      setError(t("publish.selectClass"));
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const res = await service.publishLessonPlanHomework({
        planId,
        blockId,
        classIds: selectedClasses,
        availableAt: availableAt || undefined,
        dueAt: dueAt || undefined,
      });
      if (res.success) {
        tracker.track("lesson_plan.publish", {
          planId,
          blockId,
          classCount: selectedClasses.length,
        });
        onPublished();
        onClose();
      } else {
        setError(res.message ?? t("error.publish"));
      }
    } catch (e) {
      console.error("[PublishHomeworkDialog] publish failed", e);
      setError(t("error.publish"));
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30">
      <div
        role="dialog"
        aria-modal="true"
        aria-label={t("publish.title")}
        className="bg-surface rounded-lg shadow-xl w-96"
      >
        <FocusTrap className="contents">
        <div className="flex justify-between items-center p-4 border-b">
          <h3 className="font-title-md">{t("publish.title")}</h3>
          <button onClick={onClose} aria-label={t("action.close")}>
            <X className="w-4 h-4" aria-hidden="true" />
          </button>
        </div>
        <div className="p-4 space-y-3">
          <div>
            <label className="text-sm font-medium">{t("publish.classLabel")}</label>
            <div className="mt-1 space-y-1 max-h-40 overflow-y-auto">
              {classes.map((c) => (
                <label
                  key={c.id}
                  className="flex items-center gap-2"
                >
                  <input
                    type="checkbox"
                    checked={selectedClasses.includes(c.id)}
                    onChange={() =>
                      setSelectedClasses(
                        selectedClasses.includes(c.id)
                          ? selectedClasses.filter((x) => x !== c.id)
                          : [...selectedClasses, c.id],
                      )
                    }
                  />
                  <span className="text-sm">{c.name}</span>
                </label>
              ))}
            </div>
          </div>
          <div>
            <label className="text-sm font-medium">
              {t("publish.availableAtLabel")}
            </label>
            <input
              type="datetime-local"
              value={availableAt}
              onChange={(e) => setAvailableAt(e.target.value)}
              className="w-full border rounded px-2 py-1 mt-1"
            />
          </div>
          <div>
            <label className="text-sm font-medium">
              {t("publish.dueAtLabel")}
            </label>
            <input
              type="datetime-local"
              value={dueAt}
              onChange={(e) => setDueAt(e.target.value)}
              className="w-full border rounded px-2 py-1 mt-1"
            />
          </div>
          {error && <p className="text-error text-sm">{error}</p>}
        </div>
        <div className="p-4 border-t flex justify-end gap-2">
          <Button variant="outline" onClick={onClose}>
            {t("action.cancel")}
          </Button>
          <Button onClick={handlePublish} disabled={loading}>
            {loading ? t("publish.publishing") : t("publish.publish")}
          </Button>
        </div>
        </FocusTrap>
      </div>
    </div>
  );
}
