"use client";

import { useEffect, useState } from "react";
import { Plus, Trash2, FolderPlus, Pencil, X } from "lucide-react";
import MediaUploader, { type UploadResult } from "@/components/admin/MediaUploader";

interface Category {
  _id: string;
  name: string;
  slug: string;
  order: number;
}

interface Product {
  _id: string;
  title: string;
  slug: string;
  description?: string;
  categoryId: string;
  mediaFileId: string;
  mediaType: "image" | "gif" | "video";
}

export default function AdminPortfolioPage() {
  const [categories, setCategories] = useState<Category[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeCat, setActiveCat] = useState<string>("all");

  // Forms
  const [newCat, setNewCat] = useState("");
  const [showProductForm, setShowProductForm] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);

  async function load() {
    setLoading(true);
    const [cRes, pRes] = await Promise.all([
      fetch("/api/categories").then((r) => r.json()),
      fetch("/api/portfolio").then((r) => r.json()),
    ]);
    setCategories(cRes);
    setProducts(pRes);
    setLoading(false);
  }

  useEffect(() => {
    load();
  }, []);

  async function createCategory(e: React.FormEvent) {
    e.preventDefault();
    if (!newCat.trim()) return;
    const res = await fetch("/api/categories", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name: newCat.trim() }),
    });
    if (res.ok) {
      setNewCat("");
      load();
    } else {
      const data = await res.json();
      alert(data.error || "Hata");
    }
  }

  async function deleteCategory(id: string) {
    if (!confirm("Bu kategoriyi silmek istiyor musunuz?")) return;
    const res = await fetch(`/api/categories/${id}`, { method: "DELETE" });
    if (!res.ok) {
      const data = await res.json();
      alert(data.error || "Silinemedi");
    }
    load();
  }

  async function deleteProduct(id: string) {
    if (!confirm("Bu ürünü silmek istiyor musunuz?")) return;
    await fetch(`/api/portfolio/${id}`, { method: "DELETE" });
    load();
  }

  const visibleProducts =
    activeCat === "all"
      ? products
      : products.filter((p) => p.categoryId === activeCat);

  return (
    <div>
      <header className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-white">Portfolyo Yönetimi</h1>
          <p className="text-sm text-brand-300">
            Kategorileri ve ürünleri buradan yönetin.
          </p>
        </div>
        <button
          className="btn-primary"
          onClick={() => {
            setEditingProduct(null);
            setShowProductForm(true);
          }}
          disabled={categories.length === 0}
        >
          <Plus className="w-4 h-4" />
          Yeni Ürün
        </button>
      </header>

      {/* Categories */}
      <section className="glass-strong rounded-2xl p-5 mb-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-base font-semibold text-white inline-flex items-center gap-2">
            <FolderPlus className="w-4 h-4 text-brand-300" />
            Kategoriler
          </h2>
        </div>

        <form onSubmit={createCategory} className="flex gap-2 mb-4">
          <input
            type="text"
            value={newCat}
            onChange={(e) => setNewCat(e.target.value)}
            placeholder="Yeni kategori adı (örn. Spawn Tasarımları)"
            className="flex-1 bg-brand-900/40 border border-brand-700/40 rounded-lg px-3 py-2 text-sm text-white placeholder:text-brand-400 outline-none focus:border-brand-400"
          />
          <button type="submit" className="btn-secondary">
            <Plus className="w-4 h-4" />
            Ekle
          </button>
        </form>

        <div className="flex flex-wrap gap-2">
          {categories.length === 0 ? (
            <p className="text-sm text-brand-400">Henüz kategori yok.</p>
          ) : (
            categories.map((c) => (
              <span
                key={c._id}
                className="inline-flex items-center gap-2 pl-3 pr-1 py-1 rounded-full bg-brand-700/40 border border-brand-600/40 text-sm text-white"
              >
                {c.name}
                <button
                  onClick={() => deleteCategory(c._id)}
                  className="w-6 h-6 rounded-full bg-red-500/20 hover:bg-red-500/40 flex items-center justify-center text-red-200"
                  aria-label="Sil"
                >
                  <X className="w-3 h-3" />
                </button>
              </span>
            ))
          )}
        </div>
      </section>

      {/* Filter tabs */}
      <div className="flex flex-wrap gap-2 mb-4">
        <button
          onClick={() => setActiveCat("all")}
          className={`px-3 py-1.5 rounded-lg text-xs font-medium border ${
            activeCat === "all"
              ? "bg-brand-700/50 text-white border-brand-400"
              : "bg-brand-900/40 text-brand-300 border-brand-700/40"
          }`}
        >
          Tümü ({products.length})
        </button>
        {categories.map((c) => {
          const count = products.filter((p) => p.categoryId === c._id).length;
          return (
            <button
              key={c._id}
              onClick={() => setActiveCat(c._id)}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium border ${
                activeCat === c._id
                  ? "bg-brand-700/50 text-white border-brand-400"
                  : "bg-brand-900/40 text-brand-300 border-brand-700/40"
              }`}
            >
              {c.name} ({count})
            </button>
          );
        })}
      </div>

      {/* Products grid */}
      {loading ? (
        <p className="text-brand-300">Yükleniyor...</p>
      ) : visibleProducts.length === 0 ? (
        <div className="glass rounded-2xl p-10 text-center">
          <p className="text-brand-300">
            {categories.length === 0
              ? "Önce kategori oluşturun, sonra ürün ekleyebilirsiniz."
              : "Bu kategoride ürün yok."}
          </p>
        </div>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
          {visibleProducts.map((p) => (
            <div key={p._id} className="glass rounded-xl overflow-hidden">
              <div className="aspect-square bg-black/40">
                {p.mediaType === "video" ? (
                  <video
                    src={`/api/files/${p.mediaFileId}`}
                    muted
                    loop
                    autoPlay
                    playsInline
                    className="w-full h-full object-cover"
                  />
                ) : (
                  <img
                    src={`/api/files/${p.mediaFileId}`}
                    alt={p.title}
                    className="w-full h-full object-cover"
                  />
                )}
              </div>
              <div className="p-3">
                <div className="text-sm font-semibold text-white truncate">
                  {p.title}
                </div>
                <div className="mt-2 flex items-center gap-2">
                  <button
                    onClick={() => {
                      setEditingProduct(p);
                      setShowProductForm(true);
                    }}
                    className="flex-1 inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded-md bg-brand-700/40 hover:bg-brand-700/60 text-xs text-white"
                  >
                    <Pencil className="w-3 h-3" /> Düzenle
                  </button>
                  <button
                    onClick={() => deleteProduct(p._id)}
                    className="px-2 py-1.5 rounded-md bg-red-500/20 hover:bg-red-500/40 text-xs text-red-200"
                    aria-label="Sil"
                  >
                    <Trash2 className="w-3 h-3" />
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {showProductForm && (
        <ProductFormModal
          categories={categories}
          product={editingProduct}
          onClose={() => {
            setShowProductForm(false);
            setEditingProduct(null);
          }}
          onSaved={() => {
            setShowProductForm(false);
            setEditingProduct(null);
            load();
          }}
        />
      )}
    </div>
  );
}

function ProductFormModal({
  categories,
  product,
  onClose,
  onSaved,
}: {
  categories: Category[];
  product: Product | null;
  onClose: () => void;
  onSaved: () => void;
}) {
  const [title, setTitle] = useState(product?.title ?? "");
  const [description, setDescription] = useState(product?.description ?? "");
  const [categoryId, setCategoryId] = useState(
    product?.categoryId ?? categories[0]?._id ?? "",
  );
  const [media, setMedia] = useState<UploadResult | null>(
    product
      ? {
          fileId: product.mediaFileId,
          contentType: "",
          mediaType: product.mediaType,
          size: 0,
          name: product.title,
        }
      : null,
  );
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    if (!title.trim()) return setError("Başlık gerekli");
    if (!categoryId) return setError("Kategori seçin");
    if (!media) return setError("Medya yükleyin");

    setSaving(true);
    const payload = {
      title: title.trim(),
      description,
      categoryId,
      mediaFileId: media.fileId,
      mediaType: media.mediaType,
      mediaContentType: media.contentType,
    };

    const url = product ? `/api/portfolio/${product._id}` : "/api/portfolio";
    const method = product ? "PATCH" : "POST";
    const res = await fetch(url, {
      method,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });
    setSaving(false);
    if (!res.ok) {
      const d = await res.json();
      setError(d.error || "Hata");
      return;
    }
    onSaved();
  }

  return (
    <div
      className="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm flex items-center justify-center p-4"
      onClick={onClose}
    >
      <div
        className="bg-[#0c1320] border border-brand-700/40 rounded-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="p-5 border-b border-brand-700/30 flex items-center justify-between">
          <h3 className="text-lg font-bold text-white">
            {product ? "Ürünü Düzenle" : "Yeni Ürün"}
          </h3>
          <button onClick={onClose} className="text-brand-300 hover:text-white">
            <X className="w-5 h-5" />
          </button>
        </div>
        <form onSubmit={submit} className="p-5 space-y-4">
          <div>
            <label className="block text-sm text-brand-200 mb-1">Başlık</label>
            <input
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className="w-full bg-brand-900/40 border border-brand-700/40 rounded-lg px-3 py-2 text-white outline-none focus:border-brand-400"
              required
            />
          </div>
          <div>
            <label className="block text-sm text-brand-200 mb-1">Kategori</label>
            <select
              value={categoryId}
              onChange={(e) => setCategoryId(e.target.value)}
              className="w-full bg-brand-900/40 border border-brand-700/40 rounded-lg px-3 py-2 text-white outline-none focus:border-brand-400"
            >
              {categories.map((c) => (
                <option key={c._id} value={c._id}>
                  {c.name}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm text-brand-200 mb-1">
              Açıklama (opsiyonel)
            </label>
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              rows={3}
              className="w-full bg-brand-900/40 border border-brand-700/40 rounded-lg px-3 py-2 text-white outline-none focus:border-brand-400"
            />
          </div>

          <MediaUploader value={media} onChange={setMedia} />

          {error && (
            <p className="text-sm text-red-300 bg-red-500/10 border border-red-500/30 rounded-lg p-3">
              {error}
            </p>
          )}

          <div className="flex justify-end gap-2 pt-2">
            <button
              type="button"
              onClick={onClose}
              className="btn-secondary"
            >
              İptal
            </button>
            <button type="submit" className="btn-primary" disabled={saving}>
              {saving ? "Kaydediliyor..." : product ? "Güncelle" : "Oluştur"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
