import { useState, useRef } from "react";
import { Link, useNavigate } from "react-router";
import {
  Plus, Film, Users, Clock, Play, Search, Calendar,
  Filter, Loader2, Pencil, Trash2, X, Check, Upload,
} 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,
  getAspectRatioLabel,
  getProjectStyleLabel,
  getResolutionLabel,
  projectStyleOptions,
  resolutionOptions,
} from "../../lib/projectStyles";

// ── Default cover generator ─────────────────────────────────────────────────
function getProjectGradient(name: string): string {
  let h = 0;
  for (let i = 0; i < name.length; i++) {
    h = (Math.imul(31, h) + name.charCodeAt(i)) | 0;
  }
  const hue = ((h >>> 0) % 360);
  return `linear-gradient(135deg, hsl(${hue},60%,40%), hsl(${(hue + 45) % 360},65%,55%))`;
}

function ProjectCover({ url, name, className = "" }: { url?: string; name: string; className?: string }) {
  const initials = name.slice(0, 2);
  if (url) {
    return <img src={url} alt={name} className={`w-full h-full object-cover ${className}`} />;
  }
  return (
    <div
      className={`w-full h-full flex items-center justify-center ${className}`}
      style={{ background: getProjectGradient(name) }}
    >
      <span className="text-white text-2xl font-bold tracking-wider select-none opacity-80">
        {initials}
      </span>
    </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>
  );
}

// ── Status helpers ────────────────────────────────────────────────────────────
const statusText: Record<string, string> = {
  outline:    "大纲阶段",
  storyboard: "分镜制作",
  video:      "视频生成",
  draft:      "草稿",
  processing: "处理中",
  completed:  "已完成",
};
const statusColor: Record<string, string> = {
  outline:    "bg-blue-100 text-blue-700",
  storyboard: "bg-yellow-100 text-yellow-700",
  video:      "bg-green-100 text-green-700",
  draft:      "bg-gray-100 text-gray-600",
  processing: "bg-orange-100 text-orange-700",
  completed:  "bg-green-100 text-green-700",
};

// ── 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 { 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,
    tags: [
      { key: "style", label: getProjectStyleLabel(p.style) },
      { key: "aspectRatio", label: getAspectRatioLabel(p.aspectRatio) },
      { key: "resolution", label: getResolutionLabel(p.resolution) },
    ].filter((tag) => tag.label !== "未设置"),
  }));

  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;
  });

  return (
    <div className="h-full overflow-auto bg-background p-6">
      <div className="max-w-7xl mx-auto">

        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-2xl font-semibold text-foreground mb-1">我的项目</h1>
            <p className="text-sm text-muted-foreground">管理和创作您的AI短剧项目</p>
          </div>
          <Link
            to="/new-project"
            className="px-5 py-2.5 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white flex items-center gap-2 hover:shadow-md transition-all text-sm"
          >
            <Plus className="w-4 h-4" />
            新建项目
          </Link>
        </div>

        {/* Search & Filters */}
        <div className="mb-6 p-4 rounded-xl border border-border bg-card">
          <div className="grid grid-cols-5 gap-4">
            <div className="col-span-2">
              <label className="block text-xs text-muted-foreground mb-2">搜索项目</label>
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <input
                  type="text"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  placeholder="输入项目名称搜索..."
                  className="w-full pl-9 pr-4 py-2 rounded-lg border border-border bg-background text-sm text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>
            </div>
            <div>
              <label className="block text-xs text-muted-foreground mb-2">开始日期</label>
              <div className="relative">
                <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <input
                  type="date"
                  value={dateRange.start}
                  onChange={(e) => setDateRange({ ...dateRange, start: e.target.value })}
                  className="w-full pl-9 pr-4 py-2 rounded-lg border border-border bg-background text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>
            </div>
            <div>
              <label className="block text-xs text-muted-foreground mb-2">结束日期</label>
              <div className="relative">
                <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <input
                  type="date"
                  value={dateRange.end}
                  onChange={(e) => setDateRange({ ...dateRange, end: e.target.value })}
                  className="w-full pl-9 pr-4 py-2 rounded-lg border border-border bg-background text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>
            </div>
            <div>
              <label className="block text-xs text-muted-foreground mb-2">按成员筛选</label>
              <div className="relative">
                <button
                  onClick={() => setShowMemberFilter(!showMemberFilter)}
                  className="w-full px-4 py-2 rounded-lg border border-border bg-background text-sm text-foreground text-left flex items-center justify-between hover:bg-muted transition-colors"
                >
                  <span className="flex items-center gap-2">
                    <Filter className="w-4 h-4 text-muted-foreground" />
                    {selectedMembers.length > 0 ? `${selectedMembers.length}个成员` : "选择成员"}
                  </span>
                  <span className="text-xs text-muted-foreground">{showMemberFilter ? "▲" : "▼"}</span>
                </button>
                {showMemberFilter && (
                  <div className="absolute top-full left-0 right-0 mt-2 p-3 rounded-lg border border-border bg-card shadow-lg z-10">
                    <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={`px-3 py-1.5 rounded-lg text-xs transition-colors ${
                            selectedMembers.includes(member) ? "bg-primary text-white" : "bg-muted text-foreground hover:bg-muted-foreground/10"
                          }`}
                        >
                          {member}
                        </button>
                      ))}
                    </div>
                    {selectedMembers.length > 0 && (
                      <button onClick={() => setSelectedMembers([])} className="mt-3 text-xs text-destructive hover:underline">
                        清除筛选
                      </button>
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-4 gap-4 mb-6">
          {[
            { label: "总项目", value: filtered.length, icon: Film },
            { label: "进行中", value: filtered.filter((p) => p.progress < 100).length, icon: Play },
            { label: "团队成员", value: allMembers.length, icon: Users },
            { label: "已完成", value: filtered.filter((p) => p.progress === 100).length, icon: Clock },
          ].map((s) => (
            <div key={s.label} className="rounded-xl border border-border bg-card p-4">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-accent flex items-center justify-center">
                  <s.icon className="w-5 h-5 text-primary" />
                </div>
                <div>
                  <div className="text-2xl font-semibold text-foreground">{s.value}</div>
                  <div className="text-xs text-muted-foreground">{s.label}</div>
                </div>
              </div>
            </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-3 gap-4">
            {filtered.map((project) => (
              <div key={project.id} className="group relative rounded-xl border border-border bg-card overflow-hidden hover:shadow-md transition-all">

                {/* Cover */}
                <Link to={`/project/${project.id}`} className="block aspect-video bg-muted overflow-hidden">
                  <ProjectCover
                    url={project.coverUrl}
                    name={project.title}
                    className="group-hover:scale-105 transition-transform duration-300"
                  />
                  {/* Status badge */}
                  <div className={`absolute top-3 right-3 px-2.5 py-1 rounded-md text-xs font-medium ${statusColor[project.status] ?? "bg-gray-100 text-gray-600"}`}>
                    {statusText[project.status] ?? project.status}
                  </div>
                </Link>

                {/* Action buttons — visible on hover */}
                <div className="absolute top-3 left-3 flex gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity">
                  <button
                    onClick={(e) => { e.preventDefault(); setEditingProject(project.raw); }}
                    className="w-7 h-7 rounded-lg bg-black/60 backdrop-blur-sm flex items-center justify-center hover:bg-black/80 transition"
                    title="编辑项目"
                  >
                    <Pencil className="w-3.5 h-3.5 text-white" />
                  </button>
                  <button
                    onClick={(e) => { e.preventDefault(); setDeletingProject(project.raw); }}
                    className="w-7 h-7 rounded-lg bg-black/60 backdrop-blur-sm flex items-center justify-center hover:bg-red-600/80 transition"
                    title="删除项目"
                  >
                    <Trash2 className="w-3.5 h-3.5 text-white" />
                  </button>
                </div>

                {/* Card body */}
                <Link to={`/project/${project.id}`} className="block p-4">
                  <h3 className="font-medium text-foreground mb-1.5 line-clamp-1">{project.title}</h3>
                  {project.description && (
                    <p className="text-xs text-muted-foreground mb-3 line-clamp-2 leading-relaxed">
                      {project.description}
                    </p>
                  )}

                  {project.tags.length > 0 && (
                    <div className="flex flex-wrap gap-1.5 mb-3">
                      {project.tags.slice(0, 3).map((tag) => (
                        <span key={tag.key} className="px-2 py-0.5 rounded bg-muted text-xs text-foreground">
                          {tag.label}
                        </span>
                      ))}
                    </div>
                  )}

                  <div className="flex items-center gap-3 text-xs text-muted-foreground mb-3">
                    <div className="flex items-center gap-1">
                      <Clock className="w-3 h-3" />
                      {project.updatedAt
                        ? new Date(project.updatedAt).toLocaleDateString("zh-CN", { month: "numeric", day: "numeric" })
                        : "—"}
                    </div>
                  </div>

                  <div className="space-y-1.5">
                    <div className="flex items-center justify-between text-xs text-muted-foreground">
                      <span>完成度</span>
                      <span>{project.progress}%</span>
                    </div>
                    <div className="h-1.5 rounded-full bg-muted overflow-hidden">
                      <div
                        className="h-full bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] rounded-full transition-all"
                        style={{ width: `${project.progress}%` }}
                      />
                    </div>
                  </div>
                </Link>
              </div>
            ))}
          </div>
        ) : projects.length === 0 ? (
          <div className="text-center py-16">
            <Film className="w-16 h-16 text-muted-foreground mx-auto mb-4" />
            <p className="text-muted-foreground mb-4">还没有项目，开始创建第一个吧</p>
            <Link
              to="/new-project"
              className="inline-flex items-center gap-2 px-5 py-2.5 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white text-sm hover:shadow-md transition-all"
            >
              <Plus className="w-4 h-4" />
              新建项目
            </Link>
          </div>
        ) : (
          <div className="text-center py-16">
            <Film className="w-16 h-16 text-muted-foreground mx-auto mb-4" />
            <p className="text-muted-foreground">没有找到符合条件的项目</p>
            <button
              onClick={() => { setSearchTerm(""); setDateRange({ start: "", end: "" }); setSelectedMembers([]); }}
              className="mt-4 text-sm text-primary hover:underline"
            >
              清除所有筛选条件
            </button>
          </div>
        )}
      </div>

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