import { useEffect, useState, useRef } from "react";
import { Link, useNavigate } from "react-router";
import {
  Plus, Film, Search, Calendar,
  Filter, Loader2, Pencil, Trash2, X, Check, Upload, Sparkles, MoreHorizontal,
} from "lucide-react";
import { useProjects, useUpdateProject, useDeleteProject } from "../../hooks/useProjects";
import { useTeamMembers } from "../../hooks/useTeam";
import { projectsApi } from "../../lib/api/projects";
import { useQueryClient } from "@tanstack/react-query";
import type { ProjectDTO } from "../../lib/api/projects";
import {
  aspectRatioOptions,
  projectStyleOptions,
  resolutionOptions,
} from "../../lib/projectStyles";

function ProjectCover({ url, name, className = "" }: { url?: string; name: string; className?: string }) {
  if (url) {
    return <img src={url} alt={name} className={`w-full h-full object-cover ${className}`} />;
  }
  return (
    <div className={`flex h-full w-full items-center justify-center bg-[linear-gradient(135deg,#e5fff2_0%,#b9d8ff_52%,#61d7ee_100%)] ${className}`}>
      <div className="relative text-white">
        <Film className="h-8 w-8 stroke-[2.2]" />
        <Sparkles className="absolute -right-2 bottom-0 h-4 w-4 fill-white stroke-white" />
      </div>
    </div>
  );
}

// ── Edit Modal ───────────────────────────────────────────────────────────────
function EditModal({
  project,
  onClose,
}: {
  project: ProjectDTO;
  onClose: () => void;
}) {
  const qc = useQueryClient();
  const updateProject = useUpdateProject(project.id);
  const [name, setName] = useState(project.name);
  const [style, setStyle] = useState(project.style ?? "");
  const [aspectRatio, setAspectRatio] = useState(project.aspectRatio ?? "");
  const [resolution, setResolution] = useState(project.resolution ?? "");
  const [coverFile, setCoverFile] = useState<File | null>(null);
  const [coverPreview, setCoverPreview] = useState<string>(project.coverUrl ?? "");
  const [saving, setSaving] = useState(false);
  const fileRef = useRef<HTMLInputElement>(null);

  const handleCoverChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setCoverFile(file);
    setCoverPreview(URL.createObjectURL(file));
  };

  const handleSave = async () => {
    if (!name.trim()) return;
    setSaving(true);
    try {
      await updateProject.mutateAsync({
        name: name.trim(),
        style: style || undefined,
        aspectRatio: aspectRatio || undefined,
        resolution: resolution || undefined,
      });
      if (coverFile) {
        await projectsApi.uploadAsset(project.id, coverFile, "cover");
        qc.invalidateQueries({ queryKey: ["projects"] });
        qc.invalidateQueries({ queryKey: ["projects", project.id] });
      }
      onClose();
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
      <div className="bg-card border border-border rounded-2xl shadow-xl w-full max-w-md mx-4 overflow-hidden">
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-border">
          <h3 className="text-base font-semibold text-foreground">编辑项目</h3>
          <button onClick={onClose} className="p-1 rounded-lg hover:bg-muted transition">
            <X className="w-4 h-4 text-muted-foreground" />
          </button>
        </div>

        <div className="px-6 py-5 space-y-5">
          {/* Cover image */}
          <div>
            <label className="block text-xs text-muted-foreground mb-2">项目封面</label>
            <div className="flex items-center gap-4">
              {/* Preview */}
              <div
                className="w-24 h-16 rounded-lg overflow-hidden border border-border flex-shrink-0 cursor-pointer"
                onClick={() => fileRef.current?.click()}
              >
                <ProjectCover url={coverPreview || undefined} name={name || project.name} className="group-hover:scale-105 transition" />
              </div>
              <div className="flex-1">
                <button
                  onClick={() => fileRef.current?.click()}
                  className="flex items-center gap-2 px-3 py-2 rounded-lg border border-border text-xs text-foreground hover:bg-muted transition w-full justify-center"
                >
                  <Upload className="w-3.5 h-3.5" />
                  {coverPreview ? "更换封面图" : "上传封面图"}
                </button>
                <p className="text-[11px] text-muted-foreground mt-1.5 text-center">
                  支持 JPG、PNG，建议 16:9
                </p>
              </div>
            </div>
            <input
              ref={fileRef}
              type="file"
              accept="image/*"
              className="hidden"
              onChange={handleCoverChange}
            />
          </div>

          {/* Project name */}
          <div>
            <label className="block text-xs text-muted-foreground mb-2">项目名称</label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              className="w-full px-3 py-2.5 rounded-lg border border-border bg-background text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/20"
              placeholder="请输入项目名称"
              maxLength={200}
            />
          </div>

          <div className="grid grid-cols-3 gap-3">
            <div>
              <label className="block text-xs text-muted-foreground mb-2">视觉风格</label>
              <select
                value={style}
                onChange={(e) => setStyle(e.target.value)}
                className="w-full px-3 py-2.5 rounded-lg border border-border bg-background text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/20"
              >
                <option value="">未设置</option>
                {projectStyleOptions.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-xs text-muted-foreground mb-2">画幅比例</label>
              <select
                value={aspectRatio}
                onChange={(e) => setAspectRatio(e.target.value)}
                className="w-full px-3 py-2.5 rounded-lg border border-border bg-background text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/20"
              >
                <option value="">未设置</option>
                {aspectRatioOptions.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label} {option.helper ?? ""}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-xs text-muted-foreground mb-2">清晰度</label>
              <select
                value={resolution}
                onChange={(e) => setResolution(e.target.value)}
                className="w-full px-3 py-2.5 rounded-lg border border-border bg-background text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/20"
              >
                <option value="">未设置</option>
                {resolutionOptions.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label} {option.helper ?? ""}
                  </option>
                ))}
              </select>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-border">
          <button
            onClick={onClose}
            className="px-4 py-2 rounded-lg border border-border text-sm text-foreground hover:bg-muted transition"
          >
            取消
          </button>
          <button
            onClick={handleSave}
            disabled={saving || !name.trim()}
            className="flex items-center gap-2 px-4 py-2 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white text-sm disabled:opacity-50 hover:shadow-md transition"
          >
            {saving ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Check className="w-3.5 h-3.5" />}
            保存
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Delete Confirm ────────────────────────────────────────────────────────────
function DeleteConfirm({
  project,
  onClose,
}: {
  project: ProjectDTO;
  onClose: () => void;
}) {
  const deleteProject = useDeleteProject();
  const navigate = useNavigate();

  const handleDelete = async () => {
    await deleteProject.mutateAsync(project.id);
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
      <div className="bg-card border border-border rounded-2xl shadow-xl w-full max-w-sm mx-4 p-6">
        <div className="w-12 h-12 rounded-full bg-red-100 flex items-center justify-center mx-auto mb-4">
          <Trash2 className="w-6 h-6 text-red-500" />
        </div>
        <h3 className="text-base font-semibold text-foreground text-center mb-2">删除项目</h3>
        <p className="text-sm text-muted-foreground text-center mb-6">
          确定删除「{project.name}」？此操作无法撤销，项目数据将被软删除。
        </p>
        <div className="flex gap-3">
          <button
            onClick={onClose}
            className="flex-1 px-4 py-2.5 rounded-lg border border-border text-sm text-foreground hover:bg-muted transition"
          >
            取消
          </button>
          <button
            onClick={handleDelete}
            disabled={deleteProject.isPending}
            className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg bg-red-500 text-white text-sm hover:bg-red-600 transition disabled:opacity-50"
          >
            {deleteProject.isPending ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Trash2 className="w-3.5 h-3.5" />}
            删除
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Dashboard ─────────────────────────────────────────────────────────────────
export function Dashboard() {
  const [searchTerm, setSearchTerm] = useState("");
  const [dateRange, setDateRange] = useState({ start: "", end: "" });
  const [selectedMembers, setSelectedMembers] = useState<string[]>([]);
  const [showMemberFilter, setShowMemberFilter] = useState(false);
  const [editingProject, setEditingProject] = useState<ProjectDTO | null>(null);
  const [deletingProject, setDeletingProject] = useState<ProjectDTO | null>(null);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);

  const { data: apiProjects, isLoading } = useProjects();
  const { data: teamMembersData = [] } = useTeamMembers();
  const allMembers = teamMembersData.map((m) => m.username).filter(Boolean);

  const projects = (apiProjects ?? []).map((p) => ({
    raw: p,
    id: p.id,
    title: p.name,
    description: p.description ?? "",
    status: p.status === "draft" ? "outline" : p.status,
    progress: p.status === "completed" ? 100 : p.status === "draft" ? 0 : 50,
    updatedAt: p.updatedAt?.slice(0, 10) ?? "",
    createdAt: p.createdAt?.slice(0, 10) ?? "",
    coverUrl: p.coverUrl,
  }));

  const filtered = projects.filter((p) => {
    if (searchTerm && !p.title.toLowerCase().includes(searchTerm.toLowerCase())) return false;
    if (dateRange.start && p.createdAt < dateRange.start) return false;
    if (dateRange.end && p.createdAt > dateRange.end) return false;
    return true;
  });

  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
  const safePage = Math.min(page, totalPages);
  const pagedProjects = filtered.slice((safePage - 1) * pageSize, safePage * pageSize);

  useEffect(() => {
    setPage(1);
  }, [searchTerm, dateRange.start, dateRange.end, selectedMembers.length, pageSize]);

  useEffect(() => {
    if (page > totalPages) setPage(totalPages);
  }, [page, totalPages]);

  return (
    <div className="h-full overflow-auto bg-[#f6f7fb] p-5 text-[#0f172a]">
      <div className="mx-auto max-w-[1440px]">

        {/* Header */}
        <div className="mb-5 flex items-center justify-between">
          <div>
            <h1 className="mb-1 text-2xl font-semibold text-[#111827]">剧本生短剧</h1>
          </div>
          <Link
            to="/new-project"
            className="flex h-9 items-center gap-2 rounded-md bg-[#1664ff] px-4 text-sm font-medium text-white transition hover:bg-[#0f56d9]"
          >
            <Plus className="w-4 h-4" />
            新建项目
          </Link>
        </div>

        {/* Search & Filters */}
        <div className="mb-4 rounded-lg border border-[#e1e6f0] bg-white p-4">
          <div className="grid grid-cols-1 gap-3 lg:grid-cols-[minmax(320px,1fr)_minmax(260px,340px)_minmax(140px,160px)_auto]">
            <div>
              <div className="relative">
                <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[#8a94a6]" />
                <input
                  type="text"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  placeholder="搜索短剧项目名称"
                  className="h-9 w-full rounded-md border border-[#d6dbe7] bg-white pl-9 pr-3 text-sm text-[#111827] outline-none transition placeholder:text-[#98a2b3] focus:border-[#1664ff] focus:ring-2 focus:ring-[#1664ff]/10"
                />
              </div>
            </div>
            <div className="flex h-9 items-center rounded-md border border-[#d6dbe7] bg-white px-3">
              <div className="relative min-w-0 flex-1">
                <input
                  type="date"
                  value={dateRange.start}
                  onChange={(e) => setDateRange({ ...dateRange, start: e.target.value })}
                  className="h-7 w-full bg-transparent text-sm text-[#111827] outline-none"
                />
              </div>
              <span className="px-2 text-sm text-[#98a2b3]">-</span>
              <div className="relative min-w-0 flex-1">
                <input
                  type="date"
                  value={dateRange.end}
                  onChange={(e) => setDateRange({ ...dateRange, end: e.target.value })}
                  className="h-7 w-full bg-transparent text-sm text-[#111827] outline-none"
                />
              </div>
              <Calendar className="ml-2 h-4 w-4 text-[#667085]" />
            </div>
            <div>
              <div className="relative">
                <button
                  onClick={() => setShowMemberFilter(!showMemberFilter)}
                  className="flex h-9 w-full items-center justify-between rounded-md border border-[#d6dbe7] bg-white px-3 text-left text-sm text-[#111827] transition hover:border-[#b8c2d6]"
                >
                  <span className="flex items-center gap-2">
                    <Filter className="h-4 w-4 text-[#8a94a6]" />
                    {selectedMembers.length > 0 ? `${selectedMembers.length}个成员` : "选择成员"}
                  </span>
                  <span className="text-xs text-[#8a94a6]">{showMemberFilter ? "▲" : "▼"}</span>
                </button>
                {showMemberFilter && (
                  <div className="absolute left-0 right-0 top-full z-20 mt-2 rounded-lg border border-[#dfe3ee] bg-white p-3 shadow-lg">
                    <div className="flex flex-wrap gap-2">
                      {allMembers.map((member) => (
                        <button
                          key={member}
                          onClick={() => setSelectedMembers((prev) =>
                            prev.includes(member) ? prev.filter((m) => m !== member) : [...prev, member]
                          )}
                          className={`rounded-md px-3 py-1.5 text-xs transition-colors ${
                            selectedMembers.includes(member) ? "bg-[#1664ff] text-white" : "bg-[#f2f4f8] text-[#344054] hover:bg-[#e8edf6]"
                          }`}
                        >
                          {member}
                        </button>
                      ))}
                    </div>
                    {selectedMembers.length > 0 && (
                      <button onClick={() => setSelectedMembers([])} className="mt-3 text-xs text-destructive hover:underline">
                        清除筛选
                      </button>
                    )}
                  </div>
                )}
              </div>
            </div>
            <Link
              to="/new-project"
              className="flex h-9 items-center justify-center gap-2 rounded-md bg-[#5d5bff] px-4 text-sm font-medium text-white transition hover:bg-[#4d4af0]"
            >
              <Plus className="h-4 w-4" />
              创建项目
            </Link>
          </div>
        </div>

        {/* Projects Grid */}
        {isLoading ? (
          <div className="flex items-center justify-center py-20">
            <Loader2 className="w-8 h-8 animate-spin text-primary" />
          </div>
        ) : filtered.length > 0 ? (
          <>
          <div className="grid grid-cols-1 gap-x-8 gap-y-10 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5">
            {pagedProjects.map((project) => (
              <div key={project.id} className="group relative">

                {/* Cover */}
                <Link to={`/project/${project.id}`} className="block aspect-[16/10] overflow-hidden rounded-lg bg-[#eef1f7]">
                  <ProjectCover
                    url={project.coverUrl}
                    name={project.title}
                    className="group-hover:scale-105 transition-transform duration-300"
                  />
                </Link>

                {/* Card body */}
                <div className="relative pt-3">
                  <Link to={`/project/${project.id}`} className="block pr-9">
                    <div className="flex min-w-0 items-center gap-2">
                      <h3 className="line-clamp-1 font-medium text-[#111827]">{project.title}</h3>
                      <span className="shrink-0 rounded bg-[#ecebff] px-1.5 py-0.5 text-xs text-[#5d5bff]">
                        {project.progress === 100 ? "已完成" : "创作中"}
                      </span>
                    </div>
                    <div className="mt-2 text-xs text-[#a0a9bc]">
                      {project.createdAt ? `${project.createdAt.replace("T", " ").slice(0, 19)} 创建` : "—"}
                    </div>
                  </Link>
                  <div className="absolute right-0 top-3 flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100">
                    <button
                      onClick={(e) => { e.preventDefault(); setEditingProject(project.raw); }}
                      className="flex h-7 w-7 items-center justify-center rounded text-[#475467] hover:bg-[#eef1f7]"
                      title="编辑项目"
                    >
                      <Pencil className="h-3.5 w-3.5" />
                    </button>
                    <button
                      onClick={(e) => { e.preventDefault(); setDeletingProject(project.raw); }}
                      className="flex h-7 w-7 items-center justify-center rounded text-[#475467] hover:bg-[#fff1f0] hover:text-[#d92d20]"
                      title="删除项目"
                    >
                      <MoreHorizontal className="h-4 w-4" />
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
          <div className="mt-12 flex items-center justify-end gap-2 text-sm text-[#344054]">
            <span className="mr-1">共 {filtered.length} 条</span>
            <button
              onClick={() => setPage((value) => Math.max(1, value - 1))}
              disabled={safePage === 1}
              className="flex h-8 w-8 items-center justify-center rounded-md border border-[#d6dbe7] bg-white disabled:cursor-not-allowed disabled:opacity-50"
            >
              ‹
            </button>
            <span className="flex h-8 min-w-8 items-center justify-center rounded-md border border-[#5d5bff] bg-white px-2 text-[#5d5bff]">
              {safePage}
            </span>
            <button
              onClick={() => setPage((value) => Math.min(totalPages, value + 1))}
              disabled={safePage === totalPages}
              className="flex h-8 w-8 items-center justify-center rounded-md border border-[#d6dbe7] bg-white disabled:cursor-not-allowed disabled:opacity-50"
            >
              ›
            </button>
            <select
              value={pageSize}
              onChange={(e) => setPageSize(Number(e.target.value))}
              className="ml-2 h-8 rounded-md border border-[#d6dbe7] bg-white px-3 text-sm outline-none"
            >
              {[10, 20, 50].map((size) => (
                <option key={size} value={size}>{size} 条/页</option>
              ))}
            </select>
            <span className="ml-2">前往</span>
            <input
              value={safePage}
              onChange={(e) => {
                const value = Number(e.target.value);
                if (Number.isFinite(value)) setPage(Math.min(Math.max(1, value), totalPages));
              }}
              className="h-8 w-14 rounded-md border border-[#d6dbe7] bg-white px-2 text-center outline-none"
            />
            <span>页</span>
          </div>
          </>
        ) : projects.length === 0 ? (
          <div className="rounded-lg border border-dashed border-[#cfd6e4] bg-white py-16 text-center">
            <Film className="mx-auto mb-4 h-14 w-14 text-[#98a2b3]" />
            <p className="mb-4 text-[#667085]">还没有项目，开始创建第一个吧</p>
            <Link
              to="/new-project"
              className="inline-flex h-9 items-center gap-2 rounded-md bg-[#1664ff] px-4 text-sm font-medium text-white transition hover:bg-[#0f56d9]"
            >
              <Plus className="h-4 w-4" />
              新建项目
            </Link>
          </div>
        ) : (
          <div className="rounded-lg border border-dashed border-[#cfd6e4] bg-white py-16 text-center">
            <Film className="mx-auto mb-4 h-14 w-14 text-[#98a2b3]" />
            <p className="text-[#667085]">没有找到符合条件的项目</p>
            <button
              onClick={() => { setSearchTerm(""); setDateRange({ start: "", end: "" }); setSelectedMembers([]); }}
              className="mt-4 text-sm text-[#1664ff] hover:underline"
            >
              清除所有筛选条件
            </button>
          </div>
        )}
      </div>

      {/* Modals */}
      {editingProject && (
        <EditModal
          project={editingProject}
          onClose={() => setEditingProject(null)}
        />
      )}
      {deletingProject && (
        <DeleteConfirm
          project={deletingProject}
          onClose={() => setDeletingProject(null)}
        />
      )}
    </div>
  );
}
