import { useState, type ChangeEvent, type DragEvent } from "react";
import { useNavigate } from "react-router";
import {
  AlertCircle,
  BookOpen,
  CheckCircle2,
  FileText,
  Loader2,
  Megaphone,
  Monitor,
  Sparkles,
  Wand2,
} from "lucide-react";
import { Progress } from "../components/ui/progress";
import { useCreateProject } from "../../hooks/useProjects";
import { projectsApi } from "../../lib/api/projects";
import { aspectRatioOptions, projectStyleOptions, resolutionOptions } from "../../lib/projectStyles";

type SubmitStage = "idle" | "creating" | "uploading" | "redirecting";
type CreationMode = "agent" | "manual";

const MAX_SCRIPT_SIZE = 20 * 1024 * 1024;
const SCRIPT_EXTENSIONS = [".txt", ".doc", ".docx", ".pdf", ".md"];

const submitStageMeta: Record<
  Exclude<SubmitStage, "idle">,
  { title: string; description: string; progress: number }
> = {
  creating: {
    title: "正在创建项目",
    description: "项目基础信息正在写入，请稍候。",
    progress: 28,
  },
  uploading: {
    title: "正在上传剧本",
    description: "剧本文件上传完成后，会进入大纲生成页面继续处理。",
    progress: 72,
  },
  redirecting: {
    title: "准备进入剧本大纲",
    description: "马上跳转到剧本大纲页面，可以继续解析已上传剧本，或手动输入内容。",
    progress: 96,
  },
};

function getProjectNameFromFile(file: File | null) {
  return file ? file.name.replace(/\.[^/.]+$/, "") : "新短剧项目";
}

function formatFileSize(size: number) {
  if (size >= 1024 * 1024) return `${(size / 1024 / 1024).toFixed(1)} MB`;
  return `${(size / 1024).toFixed(1)} KB`;
}

export function NewProject() {
  const navigate = useNavigate();
  const [mode, setMode] = useState<CreationMode>("agent");
  const [scriptFile, setScriptFile] = useState<File | null>(null);
  const [aspectRatio, setAspectRatio] = useState(aspectRatioOptions[0].value);
  const [resolution, setResolution] = useState(resolutionOptions[0].value);
  const [style, setStyle] = useState(projectStyleOptions[0].value);
  const [submitStage, setSubmitStage] = useState<SubmitStage>("idle");
  const [submitError, setSubmitError] = useState<string | null>(null);
  const createProject = useCreateProject();

  const isSubmitting = submitStage !== "idle";
  const hasUpload = !!scriptFile;

  const validateAndSetScript = (file: File) => {
    const lowerName = file.name.toLowerCase();
    const hasValidExtension = SCRIPT_EXTENSIONS.some((ext) => lowerName.endsWith(ext));

    if (!hasValidExtension) {
      setSubmitError("请上传 doc、docx、txt、pdf 或 md 格式的剧本文件");
      return;
    }

    if (file.size > MAX_SCRIPT_SIZE) {
      setSubmitError("剧本文件大小不能超过 20M");
      return;
    }

    setSubmitError(null);
    setScriptFile(file);
  };

  const handleScriptChange = (e: ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files?.[0] || isSubmitting || mode !== "agent") return;
    validateAndSetScript(e.target.files[0]);
  };

  const handleDrop = (e: DragEvent<HTMLLabelElement>) => {
    e.preventDefault();
    if (isSubmitting || mode !== "agent") return;
    const file = e.dataTransfer.files?.[0];
    if (file) validateAndSetScript(file);
  };

  const handleSubmit = async () => {
    if (isSubmitting) return;

    if (mode === "agent" && !scriptFile) {
      setSubmitError("Agent模式需要先上传剧本文件");
      return;
    }

    const name = getProjectNameFromFile(scriptFile);

    try {
      setSubmitError(null);
      setSubmitStage("creating");

      const project = await createProject.mutateAsync({
        name,
        style,
        aspectRatio,
        resolution,
      });

      if (scriptFile) {
        setSubmitStage("uploading");
        await projectsApi.uploadAsset(project.id, scriptFile, "script");
      }

      setSubmitStage("redirecting");

      navigate(`/project/${project.id}/outline`, {
        state: {
          fromNewProject: true,
          projectName: name,
          aspectRatio,
          resolution,
          style,
          mode,
        },
      });
    } catch (error) {
      setSubmitStage("idle");
      setSubmitError((error as Error)?.message ?? "创建项目失败，请重试");
    }
  };

  const activeSubmitMeta = submitStage === "idle" ? null : submitStageMeta[submitStage];

  return (
    <div className="relative min-h-full overflow-auto bg-[#f8f9fa] text-[#15131f]">
      {activeSubmitMeta && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-white/80 p-6 backdrop-blur-sm">
          <div className="w-full max-w-md rounded-2xl border border-[#e6eaed] bg-white p-6 shadow-2xl">
            <div className="mb-5 flex h-14 w-14 items-center justify-center rounded-2xl bg-[#8064f1]">
              <Loader2 className="h-7 w-7 animate-spin text-white" />
            </div>
            <h2 className="mb-2 text-xl font-semibold text-[#15131f]">{activeSubmitMeta.title}</h2>
            <p className="mb-5 text-sm leading-relaxed text-[#7a748c]">
              {activeSubmitMeta.description}
            </p>
            <Progress value={activeSubmitMeta.progress} className="mb-4 h-2.5" />
            <div className="space-y-2 text-sm">
              <div className="flex items-center justify-between text-[#262238]">
                <span>创建项目</span>
                <span>{submitStage === "creating" ? "进行中" : "已完成"}</span>
              </div>
              <div className="flex items-center justify-between text-[#262238]">
                <span>上传剧本</span>
                <span>
                  {!hasUpload
                    ? "已跳过"
                    : submitStage === "uploading"
                      ? "进行中"
                      : submitStage === "redirecting"
                        ? "已完成"
                        : "等待中"}
                </span>
              </div>
              <div className="flex items-center justify-between text-[#262238]">
                <span>进入大纲页</span>
                <span>{submitStage === "redirecting" ? "进行中" : "等待中"}</span>
              </div>
            </div>
            <p className="mt-4 text-xs text-[#7a748c]">处理过程中按钮已锁定，避免重复创建项目。</p>
          </div>
        </div>
      )}

      <div className="flex min-h-full flex-col">
        <div className="flex h-12 items-center justify-center gap-2 border-b border-[#e6eaed] bg-[#f3eefe] px-6 text-sm text-[#262238]">
          <Megaphone className="h-4 w-4 text-[#5337c7]" />
          <span>
            公告：视频生成在使用视频素材作为输入时，积分计算逻辑已更新。针对不同的视频输出时长，现设有最低积分消耗限制，详情请参见
          </span>
          <span className="font-medium text-[#5337c7]">视频生成计费说明。</span>
        </div>

        <main className="mx-auto flex w-full max-w-[1280px] flex-1 flex-col items-center px-8 pb-10 pt-14">
          <h1 className="text-center text-[40px] font-semibold leading-tight tracking-normal text-black">
            翻开剧本，创作<span className="text-[#5337c7]">精品短剧</span>
          </h1>

          {submitError && (
            <div className="mt-8 flex w-full max-w-[1000px] items-start gap-3 rounded-xl border border-red-200 bg-red-50 p-4">
              <AlertCircle className="mt-0.5 h-5 w-5 flex-shrink-0 text-red-500" />
              <p className="text-sm text-red-700">{submitError}</p>
            </div>
          )}

          <section className="dramix-panel mt-12 w-full max-w-[1000px] rounded-2xl p-4">
            <label
              onDrop={handleDrop}
              onDragOver={(e) => e.preventDefault()}
              className={`flex min-h-[228px] items-center justify-center rounded-xl border border-dashed border-[#d6cfea] bg-[#fbfaff] transition-colors ${
                mode === "agent" && !isSubmitting
                  ? "cursor-pointer hover:border-[#a58bff] hover:bg-[#f7f3ff]"
                  : "cursor-default"
              }`}
            >
              {mode === "agent" && (
                <input
                  type="file"
                  accept=".txt,.doc,.docx,.pdf,.md"
                  onChange={handleScriptChange}
                  disabled={isSubmitting}
                  className="hidden"
                />
              )}

              {mode === "agent" ? (
                scriptFile ? (
                  <div className="flex flex-col items-center text-center">
                    <div className="mb-4 flex h-16 w-16 items-center justify-center rounded-2xl border border-[#e6eaed] bg-white shadow-sm">
                      <FileText className="h-8 w-8 text-[#5337c7]" />
                    </div>
                    <div className="text-sm font-medium text-[#15131f]">{scriptFile.name}</div>
                    <div className="mt-1 text-xs text-[#7a748c]">{formatFileSize(scriptFile.size)}</div>
                    <button
                      type="button"
                      onClick={(e) => {
                        e.preventDefault();
                        if (!isSubmitting) setScriptFile(null);
                      }}
                      disabled={isSubmitting}
                      className="mt-4 rounded-lg border border-[#e6eaed] bg-white px-3 py-1.5 text-xs text-[#5337c7] transition-colors hover:bg-[#f7f3ff] disabled:cursor-not-allowed disabled:opacity-60"
                    >
                      重新上传
                    </button>
                  </div>
                ) : (
                  <div className="flex flex-col items-center text-center">
                    <div className="mb-6 flex items-center justify-center">
                      <div className="-mr-2 rotate-[-14deg] rounded-lg border border-[#e6eaed] bg-white p-2 text-[#a9a0bb] shadow-sm">
                        <FileText className="h-5 w-5" />
                      </div>
                      <div className="z-10 rounded-xl border border-[#e6eaed] bg-white p-3 text-[#5b546e] shadow-md">
                        <BookOpen className="h-6 w-6" />
                      </div>
                      <div className="-ml-2 rotate-[14deg] rounded-lg border border-[#e6eaed] bg-white p-2 text-[#a9a0bb] shadow-sm">
                        <FileText className="h-5 w-5" />
                      </div>
                    </div>
                    <div className="text-sm text-[#7a748c]">
                      点击或拖拽剧本至此，支持 doc、docx、txt、pdf 和 md 格式，文件大小不超过 20M
                    </div>
                  </div>
                )
              ) : (
                <div className="flex flex-col items-center text-center">
                  <div className="mb-5 flex h-16 w-16 items-center justify-center rounded-2xl border border-[#e6eaed] bg-white shadow-sm">
                    <Wand2 className="h-8 w-8 text-[#5337c7]" />
                  </div>
                  <div className="text-sm font-medium text-[#15131f]">人工模式将在下一页手动输入剧本和大纲</div>
                  <div className="mt-2 text-sm text-[#7a748c]">这里不需要填写项目名称，也不需要上传图片。</div>
                </div>
              )}
            </label>

            <div className="mt-4 flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
              <div className="inline-flex w-fit rounded-lg border border-[#e6eaed] bg-white p-0.5">
                <button
                  type="button"
                  onClick={() => {
                    setMode("agent");
                    setSubmitError(null);
                  }}
                  disabled={isSubmitting}
                  className={`h-9 rounded-md px-4 text-sm transition-colors ${
                    mode === "agent"
                      ? "bg-[#f3eefe] text-[#5337c7]"
                      : "text-[#15131f] hover:bg-[#f7f5fb]"
                  } disabled:cursor-not-allowed disabled:opacity-60`}
                >
                  Agent模式
                </button>
                <button
                  type="button"
                  onClick={() => {
                    setMode("manual");
                    setSubmitError(null);
                  }}
                  disabled={isSubmitting}
                  className={`h-9 rounded-md px-4 text-sm transition-colors ${
                    mode === "manual"
                      ? "bg-[#f3eefe] text-[#5337c7]"
                      : "text-[#15131f] hover:bg-[#f7f5fb]"
                  } disabled:cursor-not-allowed disabled:opacity-60`}
                >
                  人工模式
                </button>
              </div>

              <div className="flex flex-wrap items-center gap-3">
                <label className="relative">
                  <Monitor className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[#5b546e]" />
                  <select
                    value={aspectRatio}
                    onChange={(e) => setAspectRatio(e.target.value)}
                    disabled={isSubmitting}
                    className="h-10 min-w-[126px] appearance-none rounded-lg border border-[#e6eaed] bg-white py-0 pl-9 pr-8 text-sm text-[#15131f] outline-none transition-colors focus:border-[#8064f1] disabled:cursor-not-allowed disabled:opacity-60"
                  >
                    {aspectRatioOptions.map((option) => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </label>

                <select
                  value={resolution}
                  onChange={(e) => setResolution(e.target.value)}
                  disabled={isSubmitting}
                  className="h-10 min-w-[112px] rounded-lg border border-[#e6eaed] bg-white px-3 text-sm text-[#15131f] outline-none transition-colors focus:border-[#8064f1] disabled:cursor-not-allowed disabled:opacity-60"
                >
                  {resolutionOptions.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </select>

                <select
                  value={style}
                  onChange={(e) => setStyle(e.target.value)}
                  disabled={isSubmitting}
                  className="h-10 min-w-[150px] rounded-lg border border-[#e6eaed] bg-white px-3 text-sm text-[#15131f] outline-none transition-colors focus:border-[#8064f1] disabled:cursor-not-allowed disabled:opacity-60"
                >
                  {projectStyleOptions.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </select>
              </div>
            </div>
          </section>

          <button
            type="button"
            onClick={handleSubmit}
            disabled={isSubmitting}
            className="dramix-primary mt-16 flex h-[52px] min-w-[250px] items-center justify-center gap-2 rounded-xl px-8 text-sm font-medium transition-all hover:-translate-y-0.5 disabled:cursor-not-allowed disabled:translate-y-0 disabled:opacity-60"
          >
            {isSubmitting ? <Loader2 className="h-5 w-5 animate-spin" /> : <Sparkles className="h-5 w-5" />}
            <span>{isSubmitting ? activeSubmitMeta?.title ?? "处理中..." : "创建短剧项目"}</span>
          </button>

          <div className="mt-8 flex items-center gap-2 text-sm text-[#8d86a2]">
            <CheckCircle2 className="h-4 w-4" />
            <span>平台内容均由人工智能模型生成，不代表平台立场</span>
          </div>
        </main>
      </div>
    </div>
  );
}
