"use client";

import { useState, useMemo, useCallback, useEffect } from "react";
import { createPortal } from "react-dom";
import { motion, AnimatePresence } from "framer-motion";
import {
  Plus,
  Search,
  FolderOpen,
  Clock,
  CheckCircle,
  Video,
  AlertCircle,
  ExternalLink,
  Loader2,
  Trash2,
  X,
  Languages,
  ChevronDown,
} from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { cn } from "@/lib/utils";
import { useProjects, useDeleteProject } from "@/hooks/use-api";
import { languages } from "@/components/projects/ProjectConfiguration";
import { toaster as toast } from '@/components/ui/feedback/toaster';
import { apiClient } from "@/lib/api/api-service";

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-neutral-400",
    bgColor: "bg-neutral-200 dark:bg-neutral-800",
    label: "Senaryo",
  },
  reviewing: {
    icon: Clock,
    color: "text-neutral-500",
    bgColor: "bg-neutral-200 dark:bg-neutral-800",
    label: "İnceleme",
  },
  rendering: {
    icon: Video,
    color: "text-[var(--color-text-primary)]",
    bgColor: "bg-neutral-200 dark:bg-neutral-800",
    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;
  parentId?: string | null;
}

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

  const [translateTarget, setTranslateTarget] = useState<ProjectItem | null>(null);
  const [targetLanguage, setTargetLanguage] = useState<string>("");
  const [isTranslating, setIsTranslating] = useState(false);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

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

  const confirmTranslate = async () => {
    if (!translateTarget || !targetLanguage) return;
    try {
      setIsTranslating(true);
      const res = await apiClient.post(`/projects/${translateTarget.id}/translate`, { targetLanguage });
      toast.success({ title: "Proje başarıyla çevrildi!" });
      
      // Çeviri tamamlanınca ana projeyi otomatik olarak genişletiyoruz
      setExpandedProjects((prev) => ({ ...prev, [translateTarget.id]: true }));
      
      setTranslateTarget(null);
      setTargetLanguage("");
      refetch();
      // Yönlendirmek istersen: router.push(`/dashboard/projects/${res.data.id}`);
    } catch (err: any) {
      toast.error(err?.response?.data?.message || "Çeviri sırasında bir hata oluştu.");
    } finally {
      setIsTranslating(false);
    }
  };

  const toggleExpand = useCallback((e: React.MouseEvent, id: string) => {
    e.preventDefault();
    e.stopPropagation();
    setExpandedProjects((prev) => ({ ...prev, [id]: !prev[id] }));
  }, []);

  // 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]);

  const rootProjects = useMemo(() => {
    return filtered.filter(p => !p.parentId);
  }, [filtered]);

  const childrenMap = useMemo(() => {
    const map: Record<string, ProjectItem[]> = {};
    filtered.forEach(p => {
      if (p.parentId) {
        if (!map[p.parentId]) map[p.parentId] = [];
        map[p.parentId].push(p);
      }
    });
    return map;
  }, [filtered]);

  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-[var(--color-text-primary)] font-medium">
                ({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-neutral-500 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-neutral-200 text-black border border-neutral-400 dark:bg-neutral-800 dark:text-white dark:border-neutral-600"
                : "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-[var(--color-text-primary)] 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-[var(--color-text-primary)] hover:text-[var(--color-text-secondary)] font-medium"
                >
                  İlk projenizi oluşturun →
                </Link>
              )}
            </div>
          ) : (
            rootProjects.map((project) => {
              const children = childrenMap[project.id] || [];
              const hasChildren = children.length > 0;
              const isExpanded = expandedProjects[project.id];
              
              const renderCard = (p: ProjectItem, isChild = false) => {
                const st = statusMap[p.status] ?? statusMap.draft;
                const StIcon = st.icon;
                return (
                  <div
                    key={p.id}
                    className={cn(
                      "flex items-center rounded-xl card hover:border-neutral-400 dark:hover:border-neutral-600 transition-all group relative",
                      isChild && "bg-[var(--color-bg-surface)]"
                    )}
                  >
                    <Link
                      href={`/dashboard/projects/${p.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-[var(--color-text-secondary)] transition-colors">
                          {p.title}
                        </p>
                        <div className="flex items-center gap-3 mt-0.5 text-[11px] text-[var(--color-text-ghost)]">
                          <span>
                            {new Date(p.createdAt).toLocaleDateString(
                              "tr-TR",
                              {
                                day: "numeric",
                                month: "short",
                                year: "numeric",
                              },
                            )}
                          </span>
                          {p.language && <span>• {p.language}</span>}
                          {typeof p.creditsUsed === "number" &&
                            p.creditsUsed > 0 && (
                              <span>• {p.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-[var(--color-text-primary)] transition-colors shrink-0"
                      />
                    </Link>
                    
                  <div className="flex items-center">
                    <button
                      onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        setTranslateTarget(p);
                      }}
                      className="p-2 rounded-lg text-[var(--color-text-ghost)] hover:text-blue-400 hover:bg-blue-500/10 transition-colors shrink-0 z-10"
                      title="Projeyi Çevir"
                    >
                      <Languages size={16} />
                    </button>
                    
                    <button
                      onClick={(e) => openDeleteConfirm(e, p)}
                      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 mx-1"
                      title="Projeyi Sil"
                    >
                      <Trash2 size={16} />
                    </button>
                    
                    {!isChild && hasChildren && (
                       <button
                         onClick={(e) => toggleExpand(e, p.id)}
                         className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-medium text-[var(--color-text-ghost)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-surface)] transition-colors shrink-0 z-10 mr-1 border border-transparent hover:border-[var(--color-border-faint)]"
                         title="Çevirileri Göster"
                       >
                         <span className="flex items-center gap-1">
                           <Languages size={12} />
                           {children.length} Çeviri
                         </span>
                         <ChevronDown size={14} className={cn("transition-transform", isExpanded && "rotate-180")} />
                       </button>
                    )}
                  </div>
                </div>
              );
            };

            return (
              <div key={project.id} className="space-y-2">
                {renderCard(project)}
                {isExpanded && hasChildren && (
                  <div className="pl-6 md:pl-10 space-y-2 relative before:absolute before:left-[1.25rem] md:before:left-[2.25rem] before:top-0 before:bottom-0 before:w-px before:bg-neutral-200 dark:before:bg-neutral-800">
                    {children.map(child => renderCard(child, true))}
                  </div>
                )}
              </div>
            );
          })
        )}
      </motion.div>
    )}

    {/* ─── Silme Onay Modal ─── */}
    {mounted && createPortal(
      <div className="portal-container">
        <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>

        {/* ─── Çeviri Modal ─── */}
        <AnimatePresence>
          {translateTarget && (
        <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={() => !isTranslating && setTranslateTarget(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={() => setTranslateTarget(null)}
              disabled={isTranslating}
              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-blue-500/10 mb-4">
              <Languages size={22} className="text-blue-400" />
            </div>

            {/* İçerik */}
            <h3 className="text-base font-semibold text-[var(--color-text-primary)] mb-1.5">
              Projeyi Çevir
            </h3>
            <p className="text-sm text-[var(--color-text-muted)] mb-3">
              "{translateTarget.title}" projesini başka bir dile çevirin. (1 kredi)
            </p>

            <select
              value={targetLanguage}
              onChange={(e) => setTargetLanguage(e.target.value)}
              disabled={isTranslating}
              className="w-full bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-xl px-4 py-2.5 text-sm text-[var(--color-text-primary)] mb-5"
            >
              <option value="">Dil Seçin...</option>
              {languages.map((lang) => (
                <option key={lang.code} value={lang.code}>
                  {lang.flag} {lang.label}
                </option>
              ))}
            </select>

            {/* Butonlar */}
            <div className="flex items-center gap-3">
              <button
                onClick={() => setTranslateTarget(null)}
                disabled={isTranslating}
                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={confirmTranslate}
                disabled={isTranslating || !targetLanguage}
                className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl bg-blue-500 hover:bg-blue-600 text-white text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isTranslating ? (
                  <>
                    <Loader2 size={14} className="animate-spin" />
                    Çevriliyor...
                  </>
                ) : (
                  <>
                    <Languages size={14} />
                    Çevir (1 🪙)
                  </>
                )}
              </button>
            </div>
          </motion.div>
        </motion.div>
      )}
      </AnimatePresence>
    </div>,
    document.body
  )}
  </div>
);
}
