// app/admin/edit/[id]/page.tsx
"use client";

import { useState, useEffect, useRef, use } from "react";
import { useRouter } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import {
  UploadCloud,
  FileArchive,
  CheckCircle2,
  AlertCircle,
  Loader2,
  X,
  FileCode2,
  ArrowLeft,
  Trash2,
} from "lucide-react";
import Image from "next/image";
import Link from "next/link";

const CATEGORIES = [
  "Visiting Cards",
  "Wedding Cards",
  "Bill Books",
  "Posters & Banners",
  "Flex Banners",
  "Vector Clipart",
  "Line Art & Border",
  "Dividers & Corners",
  "Social Media Posts",
];

const FILE_TYPES = ["CDR", "PSD", "PNG"];

export default function AdminEditPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const router = useRouter();

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  // Form states
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [category, setCategory] = useState(CATEGORIES[0]);
  const [fileType, setFileType] = useState(FILE_TYPES[0]);
  const [price, setPrice] = useState("");
  const [discountPrice, setDiscountPrice] = useState("");
  const [currentThumbnail, setCurrentThumbnail] = useState("");

  // Optional replacement file
  const [newAssetFile, setNewAssetFile] = useState<File | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    async function fetchProduct() {
      try {
        const res = await fetch(`/api/admin/products/${id}`);
        if (!res.ok) throw new Error("Failed to load product details.");
        const data = await res.json();

        setTitle(data.title);
        setDescription(data.description || "");
        setCategory(data.category);
        setFileType(data.fileType);
        setPrice(String(data.price));
        setDiscountPrice(data.discountPrice ? String(data.discountPrice) : "");
        setCurrentThumbnail(data.thumbnailUrl);
      } catch (err: any) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    }
    fetchProduct();
  }, [id]);

  const handleUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError(null);
    setSuccess(false);

    try {
      const formData = new FormData();
      formData.append("title", title);
      formData.append("description", description);
      formData.append("category", category);
      formData.append("fileType", fileType);
      formData.append("price", price);
      if (discountPrice) formData.append("discountPrice", discountPrice);
      if (newAssetFile) formData.append("asset", newAssetFile);

      const res = await fetch(`/api/admin/products/${id}`, {
        method: "PUT",
        body: formData,
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Update failed.");

      setSuccess(true);
      setTimeout(() => {
        router.push(`/products/${data.product.slug}`);
        router.refresh();
      }, 1200);
    } catch (err: any) {
      setError(err.message || "Failed to update product.");
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!confirm("Are you sure you want to permanently delete this template?")) return;

    try {
      const res = await fetch(`/api/admin/products/${id}`, { method: "DELETE" });
      if (res.ok) {
        router.push("/");
        router.refresh();
      }
    } catch {
      alert("Failed to delete.");
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <Loader2 className="h-8 w-8 text-indigo-500 animate-spin" />
      </div>
    );
  }

  return (
    <div className="max-w-3xl mx-auto py-12 px-4 sm:px-6">
      {/* Header */}
      <div className="flex items-center justify-between mb-8">
        <div>
          <Link href="/" className="text-xs text-zinc-400 hover:text-white flex items-center gap-1 mb-2">
            <ArrowLeft className="h-3.5 w-3.5" /> Back to Store
          </Link>
          <h1 className="text-2xl sm:text-3xl font-black text-white tracking-tight">
            Edit Template
          </h1>
        </div>
        <button
          type="button"
          onClick={handleDelete}
          className="flex items-center gap-1.5 px-3.5 py-2 rounded-xl bg-rose-500/10 text-rose-400 border border-rose-500/20 hover:bg-rose-500/20 text-xs font-semibold transition"
        >
          <Trash2 className="h-4 w-4" /> Delete Template
        </button>
      </div>

      <AnimatePresence>
        {error && (
          <motion.div
            initial={{ opacity: 0, y: -6 }}
            animate={{ opacity: 1, y: 0 }}
            className="mb-6 flex items-center gap-2 p-4 rounded-xl bg-rose-500/10 border border-rose-500/20 text-rose-400 text-xs"
          >
            <AlertCircle className="h-4 w-4 flex-shrink-0" />
            <span>{error}</span>
          </motion.div>
        )}

        {success && (
          <motion.div
            initial={{ opacity: 0, y: -6 }}
            animate={{ opacity: 1, y: 0 }}
            className="mb-6 flex items-center gap-2 p-4 rounded-xl bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-xs"
          >
            <CheckCircle2 className="h-4 w-4 flex-shrink-0" />
            <span>Product updated successfully! Redirecting...</span>
          </motion.div>
        )}
      </AnimatePresence>

      <form onSubmit={handleUpdate} className="space-y-6">
        {/* Current Thumbnail + Replace Option */}
        <div className="bg-zinc-900/60 border border-zinc-800 rounded-2xl p-6">
          <label className="block text-xs font-medium text-zinc-300 mb-3">
            Current Asset & Thumbnail
          </label>
          <div className="flex items-center gap-4">
            <div className="relative h-20 w-28 rounded-xl overflow-hidden bg-zinc-950 border border-zinc-800 flex-shrink-0">
              <Image src={currentThumbnail} alt={title} fill className="object-cover" />
            </div>

            <div className="flex-1 min-w-0">
              <input
                ref={fileInputRef}
                type="file"
                accept=".cdr,.psd,.png"
                className="hidden"
                onChange={(e) => {
                  if (e.target.files && e.target.files[0]) {
                    setNewAssetFile(e.target.files[0]);
                  }
                }}
              />
              <button
                type="button"
                onClick={() => fileInputRef.current?.click()}
                className="text-xs font-semibold px-4 py-2 rounded-xl bg-zinc-800 hover:bg-zinc-700 text-white transition flex items-center gap-2"
              >
                <UploadCloud className="h-4 w-4 text-indigo-400" />
                {newAssetFile ? "Replace Selected File" : "Upload New CDR/PSD (Auto-Regenerates Angles)"}
              </button>

              {newAssetFile && (
                <p className="text-xs text-indigo-400 mt-2 font-medium flex items-center gap-1.5">
                  <FileCode2 className="h-3.5 w-3.5" /> Selected: {newAssetFile.name}
                </p>
              )}
            </div>
          </div>
        </div>

        {/* Edit Fields */}
        <div className="bg-zinc-900/60 border border-zinc-800 rounded-2xl p-6 space-y-4">
          <div>
            <label className="block text-xs font-medium text-zinc-300 mb-1">Title *</label>
            <input
              type="text"
              required
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className="w-full rounded-xl bg-zinc-950 border border-zinc-800 px-4 py-2.5 text-sm text-white focus:border-indigo-500 focus:outline-none"
            />
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-medium text-zinc-300 mb-1">Category *</label>
              <select
                value={category}
                onChange={(e) => setCategory(e.target.value)}
                className="w-full rounded-xl bg-zinc-950 border border-zinc-800 px-4 py-2.5 text-sm text-white focus:border-indigo-500 focus:outline-none"
              >
                {CATEGORIES.map((cat) => (
                  <option key={cat} value={cat}>
                    {cat}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-xs font-medium text-zinc-300 mb-1">File Type</label>
              <div className="grid grid-cols-3 gap-2">
                {FILE_TYPES.map((t) => (
                  <button
                    key={t}
                    type="button"
                    onClick={() => setFileType(t)}
                    className={`py-2 text-xs font-bold rounded-xl border transition ${
                      fileType === t
                        ? "bg-indigo-600 border-indigo-500 text-white"
                        : "bg-zinc-950 border-zinc-800 text-zinc-400"
                    }`}
                  >
                    {t}
                  </button>
                ))}
              </div>
            </div>

            <div>
              <label className="block text-xs font-medium text-zinc-300 mb-1">Price (₹) *</label>
              <input
                type="number"
                step="0.01"
                required
                min="0"
                value={price}
                onChange={(e) => setPrice(e.target.value)}
                className="w-full rounded-xl bg-zinc-950 border border-zinc-800 px-4 py-2.5 text-sm text-white focus:border-indigo-500 focus:outline-none"
              />
            </div>

            <div>
              <label className="block text-xs font-medium text-zinc-300 mb-1">Discount Price (₹)</label>
              <input
                type="number"
                step="0.01"
                min="0"
                value={discountPrice}
                onChange={(e) => setDiscountPrice(e.target.value)}
                className="w-full rounded-xl bg-zinc-950 border border-zinc-800 px-4 py-2.5 text-sm text-white focus:border-indigo-500 focus:outline-none"
              />
            </div>
          </div>

          <div>
            <label className="block text-xs font-medium text-zinc-300 mb-1">Description & Fonts</label>
            <textarea
              rows={4}
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              className="w-full rounded-xl bg-zinc-950 border border-zinc-800 p-4 text-xs text-white focus:border-indigo-500 focus:outline-none resize-none"
            />
          </div>
        </div>

        <button
          type="submit"
          disabled={saving}
          className="w-full flex items-center justify-center gap-2 rounded-xl bg-indigo-600 py-3 text-sm font-semibold text-white hover:bg-indigo-500 transition disabled:opacity-50 shadow-lg shadow-indigo-600/30"
        >
          {saving ? (
            <>
              <Loader2 className="h-5 w-5 animate-spin" /> Saving Changes...
            </>
          ) : (
            "Save & Update Template"
          )}
        </button>
      </form>
    </div>
  );
}