"use client";

import { useCallback, useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { X, Upload, FileText, Image as ImageIcon, Music, Video, Trash2 } from "lucide-react";
import { Button } from "@/shared/components/ui/button";
import { FocusTrap } from "@/shared/components/a11y/focus-trap";
import { useFileUpload } from "@/modules/files/hooks/use-file-upload";
import { useLessonPlanContextSafe } from "../providers/lesson-plan-provider";
import type { LessonPlanAttachmentOption } from "../providers/lesson-plan-provider";
import type { RichTextAttachment } from "../types";
import { toast } from "sonner";

interface Props {
  planId: string;
  blockId?: string;
  /** 当前节点已嵌入的附件（用于高亮已选） */
  selectedIds?: string[];
  /** 选择附件后的回调（嵌入到富文本） */
  onSelect: (attachment: RichTextAttachment) => void;
  onClose: () => void;
}

/** V5-5：根据 MIME 类型推断渲染种类（供调用方使用） */
export function inferAttachmentKind(
  mimeType: string | undefined,
): RichTextAttachment["kind"] {
  if (!mimeType) return "file";
  if (mimeType.startsWith("image/")) return "image";
  if (mimeType.startsWith("audio/")) return "audio";
  if (mimeType.startsWith("video/")) return "video";
  return "file";
}

function kindIcon(kind: RichTextAttachment["kind"]) {
  switch (kind) {
    case "image":
      return <ImageIcon className="w-4 h-4" aria-hidden="true" />;
    case "audio":
      return <Music className="w-4 h-4" aria-hidden="true" />;
    case "video":
      return <Video className="w-4 h-4" aria-hidden="true" />;
    default:
      return <FileText className="w-4 h-4" aria-hidden="true" />;
  }
}

/**
 * V5-5：素材库 Picker
 *
 * 功能：
 * 1. 上传新文件（复用 use-file-upload hook，调用 /api/upload）
 * 2. 上传成功后调用 service.createLessonPlanAttachment 落库到 lessonPlanAttachments 表
 * 3. 列出当前课案已上传的所有附件（service.getLessonPlanAttachments）
 * 4. 点击附件 → onSelect 回调，由调用方决定如何嵌入
 *
 * 不直接 import actions，通过 LessonPlanContext 注入的 service 调用。
 */
export function AttachmentPicker({
  planId,
  blockId,
  selectedIds = [],
  onSelect,
  onClose,
}: Props) {
  const t = useTranslations("lessonPreparation");
  const ctx = useLessonPlanContextSafe();
  const service = ctx?.service ?? null;
  const [items, setItems] = useState<LessonPlanAttachmentOption[]>([]);
  const [loading, setLoading] = useState(true);

  // V5-5：复用项目已有 use-file-upload hook
  const { inputRef, handleFiles, tasks } = useFileUpload({
    targetType: "lesson_plan",
    targetId: planId,
    multiple: true,
    onUploaded: async (result) => {
      if (!service) return;
      // 上传成功后创建附件记录
      const res = await service.createLessonPlanAttachment({
        planId,
        blockId,
        fileId: result.id,
        displayName: result.originalName,
        attachmentType: "material",
      });
      if (res.success) {
        toast.success(t("attachment.createSuccess"));
        // 刷新附件列表
        void loadAttachments();
      } else {
        toast.error(res.message ?? t("error.save"));
      }
    },
  });

  // V5-5：加载附件列表
  const loadAttachments = useCallback(async () => {
    if (!service) return;
    setLoading(true);
    try {
      const res = await service.getLessonPlanAttachments(planId);
      if (res.success && res.data) {
        setItems(res.data.items);
      }
    } catch (e) {
      console.error("[AttachmentPicker] load failed", e);
      toast.error(t("attachment.empty"));
    } finally {
      setLoading(false);
    }
  }, [service, planId, t]);

  useEffect(() => {
    void loadAttachments();
  }, [loadAttachments]);

  // V5-5：ESC 关闭
  useEffect(() => {
    function handleEsc(e: KeyboardEvent) {
      if (e.key === "Escape") onClose();
    }
    document.addEventListener("keydown", handleEsc);
    return () => document.removeEventListener("keydown", handleEsc);
  }, [onClose]);

  // V5-5：删除附件
  async function handleDelete(attachmentId: string) {
    if (!service) return;
    try {
      const res = await service.deleteLessonPlanAttachment(attachmentId);
      if (res.success) {
        toast.success(t("attachment.deleteSuccess"));
        void loadAttachments();
      } else {
        toast.error(res.message ?? t("error.save"));
      }
    } catch (e) {
      console.error("[AttachmentPicker] delete failed", e);
      toast.error(t("error.save"));
    }
  }

  // V5-5：选择附件嵌入富文本
  function handleSelect(item: LessonPlanAttachmentOption) {
    const attachment: RichTextAttachment = {
      attachmentId: item.id,
      fileId: item.fileId,
      displayName: item.displayName,
      kind: inferAttachmentKind(item.mimeType),
      url: item.url ?? `/api/files/${item.fileId}`,
      mimeType: item.mimeType,
    };
    onSelect(attachment);
    onClose();
  }

  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("attachment.title")}
        className="bg-surface rounded-lg shadow-xl w-[640px] max-h-[80vh] flex flex-col"
      >
        <FocusTrap className="contents">
          <div className="flex justify-between items-center p-4 border-b">
            <h3 className="font-title-md">{t("attachment.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 overflow-y-auto flex-1 space-y-4">
            {/* 上传区域 */}
            <div className="border-2 border-dashed border-outline-variant rounded p-4 text-center">
              <input
                ref={inputRef}
                type="file"
                multiple
                className="hidden"
                onChange={(e) => handleFiles(e.target.files)}
              />
              <Button
                variant="outline"
                size="sm"
                onClick={() => inputRef.current?.click()}
              >
                <Upload className="w-4 h-4 mr-1" /> {t("attachment.add")}
              </Button>
              {/* 上传任务进度 */}
              {tasks.length > 0 && (
                <div className="mt-3 space-y-1 text-xs text-left">
                  {tasks.map((task) => (
                    <div
                      key={`${task.file.name}-${task.file.size}`}
                      className="flex items-center gap-2"
                    >
                      <span className="flex-1 truncate">{task.file.name}</span>
                      <span
                        className={
                          task.status === "error"
                            ? "text-error"
                            : task.status === "success"
                              ? "text-primary"
                              : "text-on-surface-variant"
                        }
                      >
                        {task.status === "error"
                          ? t("attachment.uploadFailed")
                          : task.status === "success"
                            ? t("attachment.uploadSuccess")
                            : `${task.progress}%`}
                      </span>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* 已上传附件列表 */}
            <div>
              <label className="text-sm font-medium block mb-2">
                {t("attachment.libraryLabel")}
              </label>
              {loading ? (
                <p className="text-sm text-on-surface-variant text-center py-4">
                  {t("version.loading")}
                </p>
              ) : items.length === 0 ? (
                <p className="text-sm text-on-surface-variant text-center py-4">
                  {t("attachment.empty")}
                </p>
              ) : (
                <ul className="space-y-1">
                  {items.map((item) => {
                    const isSelected = selectedIds.includes(item.id);
                    return (
                      <li
                        key={item.id}
                        className={`flex items-center gap-2 border rounded p-2 ${
                          isSelected ? "border-primary bg-primary/5" : "border-outline-variant"
                        }`}
                      >
                        <span className="text-on-surface-variant">
                          {kindIcon(inferAttachmentKind(item.mimeType))}
                        </span>
                        <button
                          className="flex-1 text-left text-sm hover:underline"
                          onClick={() => handleSelect(item)}
                        >
                          {item.displayName}
                        </button>
                        <span className="text-xs text-on-surface-variant">
                          {t(`attachment.type.${item.attachmentType}`)}
                        </span>
                        <button
                          className="text-error hover:bg-error/10 p-1 rounded"
                          onClick={() => void handleDelete(item.id)}
                          aria-label={t("attachment.delete")}
                        >
                          <Trash2 className="w-3 h-3" aria-hidden="true" />
                        </button>
                      </li>
                    );
                  })}
                </ul>
              )}
            </div>
          </div>

          <div className="p-4 border-t flex justify-end">
            <Button variant="outline" onClick={onClose}>
              {t("action.close")}
            </Button>
          </div>
        </FocusTrap>
      </div>
    </div>
  );
}
