"use client";

import { useState, useMemo, useCallback } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  Plus,
  Search,
  FolderOpen,
  Clock,
  CheckCircle,
  Video,
  AlertCircle,
  ExternalLink,
  Loader2,
  Trash2,
  X,
} from "lucide-react";
import Link from "next/link";
import { cn } from "@/lib/utils";
import { useProjects, useDeleteProject } from "@/hooks/use-api";

const statusFilters = [
  { id: "all", label: "Tümü" },
  { id: "draft", label: "Taslak" },
  { id: "scripting", label: "Senaryo" },
  { id: "rendering", label: "İşleniyor" },
  { id: "completed", label: "Tamamlanan" },
  { id: "failed", label: "Başarısız" },
];

const statusMap: Record<
  string,
  { icon: typeof Clock; color: string; label: string; bgColor: string }
> = {
  draft: {
    icon: Clock,
    color: "text-amber-400",
    bgColor: "bg-amber-500/10",
    label: "Taslak",
  },
  scripting: {
    icon: Clock,
    color: "text-blue-400",
    bgColor: "bg-blue-500/10",
    label: "Senaryo",
  },
  reviewing: {
    icon: Clock,
    color: "text-purple-400",
    bgColor: "bg-purple-500/10",
    label: "İnceleme",
  },
  rendering: {
    icon: Video,
    color: "text-cyan-400",
    bgColor: "bg-cyan-500/10",
    label: "Render",
  },
  completed: {
    icon: CheckCircle,
    color: "text-emerald-400",
    bgColor: "bg-emerald-500/10",
    label: "Tamamlandı",
  },
  failed: {
    icon: AlertCircle,
    color: "text-red-400",
    bgColor: "bg-red-500/10",
    label: "Hatalı",
  },
};

interface ProjectItem {
  id: string;
  title: string;
  status: string;
  createdAt: string;
  updatedAt?: string;
  language?: string;
  progress?: number;
  creditsUsed?: number;
}

export default function ProjectsPage() {
  const [activeFilter, setActiveFilter] = useState("all");
  const [searchQuery, setSearchQuery] = useState("");
  const [deleteTarget, setDeleteTarget] = useState<{ id: string; title: string } | null>(null);

  const { data, isLoading } = useProjects({ limit: 100 });
  const deleteMutation = useDeleteProject();

  // Silme onay modal'ını aç (native confirm yerine)
  const openDeleteConfirm = useCallback((e: React.MouseEvent, project: ProjectItem) => {
    e.preventDefault();
    e.stopPropagation();
    setDeleteTarget({ id: project.id, title: project.title });
  }, []);

  // Silme işlemini gerçekleştir
  const confirmDelete = useCallback(() => {
    if (!deleteTarget) return;
    deleteMutation.mutate(deleteTarget.id, {
      onSettled: () => {
        setDeleteTarget(null);
      },
    });
  }, [deleteTarget, deleteMutation]);

  // useProjects returns PaginatedResponse<Project> which has .data as Project[]
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const raw = data as any;
  const rawProjects: ProjectItem[] = raw?.data ?? raw ?? [];
  const projects = Array.isArray(rawProjects) ? rawProjects : [];

  const filtered = useMemo(() => {
    return projects.filter((p) => {
      if (activeFilter !== "all" && p.status?.toLowerCase() !== activeFilter)
        return false;
      if (
        searchQuery &&
        !p.title.toLowerCase().includes(searchQuery.toLowerCase())
      )
        return false;
      return true;
    });
  }, [projects, activeFilter, searchQuery]);

  return (
    <div className="max-w-5xl mx-auto space-y-6">
      {/* Başlık */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="font-[family-name:var(--font-display)] text-2xl font-bold">
            Projeler
          </h1>
          <p className="text-sm text-[var(--color-text-muted)] mt-0.5">
            Tüm video projelerini yönet
            {projects.length > 0 && (
              <span className="ml-1 text-violet-400">
                ({projects.length} proje)
              </span>
            )}
          </p>
        </div>
        <Link
          href="/dashboard/projects/new"
          className="btn-primary flex items-center gap-2 text-sm"
        >
          <Plus size={16} />
          <span>Yeni Proje</span>
        </Link>
      </div>

      {/* Arama + Filtreler */}
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="relative flex-1">
          <Search
            size={16}
            className="absolute left-3 top-1/2 -translate-y-1/2 text-[var(--color-text-ghost)]"
          />
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Proje ara..."
            className="w-full pl-9 pr-4 py-2.5 rounded-xl bg-[var(--color-bg-surface)] border border-[var(--color-border-faint)] text-sm text-[var(--color-text-primary)] placeholder:text-[var(--color-text-ghost)] focus:outline-none focus:border-violet-500/40 transition-colors"
          />
        </div>
      </div>

      {/* Status Tabs */}
      <div className="flex items-center gap-1.5 overflow-x-auto pb-1 scrollbar-none">
        {statusFilters.map((filter) => (
          <button
            key={filter.id}
            onClick={() => setActiveFilter(filter.id)}
            className={cn(
              "px-3.5 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition-all",
              activeFilter === filter.id
                ? "bg-violet-500/15 text-violet-400 border border-violet-500/25"
                : "text-[var(--color-text-muted)] border border-[var(--color-border-faint)] hover:border-[var(--color-border-default)]",
            )}
          >
            {filter.label}
          </button>
        ))}
      </div>

      {/* Loading */}
      {isLoading && (
        <div className="flex flex-col items-center justify-center py-16">
          <Loader2
            size={32}
            className="animate-spin text-violet-400 mb-3"
          />
          <p className="text-sm text-[var(--color-text-muted)]">
            Projeler yükleniyor...
          </p>
        </div>
      )}

      {/* Proje Listesi */}
      {!isLoading && (
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.4, ease: [0.16, 1, 0.3, 1] }}
          className="space-y-2"
        >
          {filtered.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-center">
              <FolderOpen
                size={40}
                className="text-[var(--color-text-ghost)] mb-3"
              />
              <p className="text-sm text-[var(--color-text-muted)] mb-1">
                {searchQuery || activeFilter !== "all"
                  ? "Filtrenizle eşleşen proje bulunamadı"
                  : "Henüz proje bulunmuyor"}
              </p>
              {!searchQuery && activeFilter === "all" && (
                <Link
                  href="/dashboard/projects/new"
                  className="mt-3 text-xs text-violet-400 hover:text-violet-300"
                >
                  İlk projenizi oluşturun →
                </Link>
              )}
            </div>
          ) : (
            filtered.map((project) => {
              const st = statusMap[project.status] ?? statusMap.draft;
              const StIcon = st.icon;
              return (
                <div
                  key={project.id}
                  className="flex items-center rounded-xl card hover:border-violet-500/20 transition-all group relative"
                >
                  <Link
                    href={`/dashboard/projects/${project.id}`}
                    className="flex items-center gap-4 p-4 flex-1 min-w-0"
                  >
                    <div
                      className={`w-10 h-10 rounded-xl ${st.bgColor} flex items-center justify-center shrink-0 ${st.color}`}
                    >
                      <StIcon size={18} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-[var(--color-text-primary)] truncate group-hover:text-violet-300 transition-colors">
                        {project.title}
                      </p>
                      <div className="flex items-center gap-3 mt-0.5 text-[11px] text-[var(--color-text-ghost)]">
                        <span>
                          {new Date(project.createdAt).toLocaleDateString(
                            "tr-TR",
                            {
                              day: "numeric",
                              month: "short",
                              year: "numeric",
                            },
                          )}
                        </span>
                        {project.language && <span>• {project.language}</span>}
                        {typeof project.creditsUsed === "number" &&
                          project.creditsUsed > 0 && (
                            <span>• {project.creditsUsed} kredi</span>
                          )}
                      </div>
                    </div>
                    <span
                      className={`text-[10px] font-medium px-2.5 py-1 rounded-full border ${st.color} border-current/20 ${st.bgColor} shrink-0 mr-2`}
                    >
                      {st.label}
                    </span>
                    <ExternalLink
                      size={14}
                      className="text-[var(--color-text-ghost)] group-hover:text-violet-400 transition-colors shrink-0"
                    />
                  </Link>
                  
                  <button
                    onClick={(e) => openDeleteConfirm(e, project)}
                    className="p-2 rounded-lg text-[var(--color-text-ghost)] hover:text-red-400 hover:bg-red-500/10 transition-colors shrink-0 z-10 mr-3"
                    title="Projeyi Sil"
                  >
                    <Trash2 size={16} />
                  </button>
                </div>
              );
            })
          )}
        </motion.div>
      )}

      {/* ─── Silme Onay Modal ─── */}
      <AnimatePresence>
        {deleteTarget && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.15 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"
            onClick={() => !deleteMutation.isPending && setDeleteTarget(null)}
          >
            <motion.div
              initial={{ opacity: 0, scale: 0.95, y: 10 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 10 }}
              transition={{ duration: 0.2, ease: [0.16, 1, 0.3, 1] }}
              className="relative bg-[var(--color-bg-elevated)] border border-[var(--color-border-default)] rounded-2xl p-6 max-w-sm w-full mx-4 shadow-2xl"
              onClick={(e) => e.stopPropagation()}
            >
              {/* Kapatma butonu */}
              <button
                onClick={() => setDeleteTarget(null)}
                disabled={deleteMutation.isPending}
                className="absolute top-3 right-3 p-1 rounded-lg text-[var(--color-text-ghost)] hover:text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-surface)] transition-colors disabled:opacity-50"
              >
                <X size={16} />
              </button>

              {/* Icon */}
              <div className="flex items-center justify-center w-12 h-12 rounded-full bg-red-500/10 mb-4">
                <Trash2 size={22} className="text-red-400" />
              </div>

              {/* İçerik */}
              <h3 className="text-base font-semibold text-[var(--color-text-primary)] mb-1.5">
                Projeyi Sil
              </h3>
              <p className="text-sm text-[var(--color-text-muted)] mb-1">
                Bu projeyi silmek istediğinize emin misiniz?
              </p>
              <p className="text-xs text-[var(--color-text-ghost)] mb-5 line-clamp-2 italic">
                &ldquo;{deleteTarget.title}&rdquo;
              </p>

              {/* Butonlar */}
              <div className="flex items-center gap-3">
                <button
                  onClick={() => setDeleteTarget(null)}
                  disabled={deleteMutation.isPending}
                  className="flex-1 px-4 py-2.5 rounded-xl border border-[var(--color-border-default)] text-sm font-medium text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-surface)] transition-colors disabled:opacity-50"
                >
                  İptal
                </button>
                <button
                  onClick={confirmDelete}
                  disabled={deleteMutation.isPending}
                  className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl bg-red-500 hover:bg-red-600 text-white text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {deleteMutation.isPending ? (
                    <>
                      <Loader2 size={14} className="animate-spin" />
                      Siliniyor...
                    </>
                  ) : (
                    <>
                      <Trash2 size={14} />
                      Evet, Sil
                    </>
                  )}
                </button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
