'use client';

import { useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import {
  ArrowLeft,
  Loader2,
  Package,
  Tag,
  Layers,
  Image as ImageIcon,
  // Info,
  Plus,
  AlertTriangle,
  RefreshCw,
  Save,
  Sparkles,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import {
  useAdminProductBySlug,
  useCategories,
  useUpdateProduct,
} from '@/hooks';
import type {
  ProductStatus,
  VariantPayload,
  ProductCategory,
  UpdateProductPayload,
} from '@/lib/services/product.service';

import {
  Section,
  Field,
  DarkInput,
  DarkTextarea,
  DirtyDot,
} from '@/components/ui/form-elements';
import { CategoryPicker } from '../../components/CategoryPicker';
import { VariantRow } from '../../components/VariantRow';

// ── Discard dialog ─────────────────────────────────────────────────────
function DiscardDialog({
  onConfirm,
  onCancel,
}: {
  onConfirm: () => void;
  onCancel: () => void;
}) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        className="absolute inset-0 bg-black/60 backdrop-blur-sm"
        onClick={onCancel}
      />
      <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 }}
        className="relative bg-white border border-gray-200 rounded-3xl p-6 w-full max-w-sm overflow-hidden shadow-2xl"
      >
        <div className="absolute top-0 left-1/2 -translate-x-1/2 w-32 h-32 bg-amber-500/20 blur-3xl pointer-events-none rounded-full" />
        <div className="flex items-center gap-4 mb-6 relative z-10">
          <div className="w-12 h-12 rounded-full border border-amber-500/20 bg-amber-500/10 flex items-center justify-center shrink-0">
            <AlertTriangle className="w-6 h-6 text-amber-400" />
          </div>
          <div>
            <h3 className="text-lg font-black text-gray-900 tracking-wide">
              Buang Perubahan?
            </h3>
            <p className="text-[10px] text-gray-500 font-bold uppercase tracking-widest mt-0.5">
              Data belum disimpan
            </p>
          </div>
        </div>
        <p className="text-sm font-medium text-gray-600 mb-8 leading-relaxed relative z-10">
          Semua perubahan yang Anda buat pada produk ini akan hilang dan tidak
          dapat dikembalikan.
        </p>
        <div className="flex gap-3 relative z-10">
          <button
            onClick={onCancel}
            className="flex-1 py-3 px-4 rounded-xl text-xs font-bold text-gray-600 bg-white border border-gray-200 hover:bg-gray-50 hover:text-gray-900 uppercase tracking-wider transition-all shadow-sm"
          >
            Lanjut Edit
          </button>
          <button
            onClick={onConfirm}
            className="flex-1 py-3 px-4 rounded-xl text-xs font-bold text-white bg-amber-500 hover:bg-amber-600 uppercase tracking-wider transition-all shadow-sm"
          >
            Buang
          </button>
        </div>
      </motion.div>
    </div>
  );
}

// ── Main Page ──────────────────────────────────────────────────────────
interface FormErrors {
  name?: string;
  sku?: string;
  category_id?: string;
  base_price?: string;
  variants?: string;
}
type EditableVariant = VariantPayload & { _id?: string; _isNew?: boolean };

export default function EditProductPage() {
  const router = useRouter();
  const params = useParams();
  const slug = params.slug as string;

  const { data: product, isLoading } = useAdminProductBySlug(slug);
  const { data: categories = [], isLoading: isCategoriesLoading } =
    useCategories();
  const updateProduct = useUpdateProduct();

  // Form states
  const [name, setName] = useState('');
  const [sku, setSku] = useState('');
  const [description, setDescription] = useState('');
  const [shortDescription, setShortDescription] = useState('');
  const [basePrice, setBasePrice] = useState<number | ''>('');
  const [status, setStatus] = useState<ProductStatus>('active');
  const [isFeatured, setIsFeatured] = useState(false);
  const [category, setCategory] = useState<ProductCategory | null>(null);
  const [variants, setVariants] = useState<EditableVariant[]>([]);
  const [primaryImageUrl, setPrimaryImageUrl] = useState('');
  const [seoTitle, setSeoTitle] = useState('');
  const [seoDescription, setSeoDescription] = useState('');
  const [errors, setErrors] = useState<FormErrors>({});

  const [showDiscard, setShowDiscard] = useState(false);

  const [initializedId, setInitializedId] = useState<string | null>(null);

  if (product && initializedId !== product.id) {
    setName(product.name);
    setSku(product.sku);
    setDescription(product.description ?? '');
    setShortDescription(product.short_description ?? '');
    setBasePrice(product.base_price ? Number(product.base_price) : '');
    setStatus(product.status);
    setIsFeatured(product.is_featured);
    setCategory(product.category);

    // Mapping varian dengan aman
    setVariants(
      product.variants.map((v) => {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const { id, ...rest } = v as any;
        return {
          ...rest,
          _id: id,
          price: Number(v.price),
          stock: Number(v.stock),
          weight: v.weight ? Number(v.weight) : undefined,
          price_distributor: v.price_distributor
            ? Number(v.price_distributor)
            : undefined,
        };
      })
    );

    setPrimaryImageUrl(product.primary_image_url ?? '');

    // Tandai bahwa form sudah diisi untuk ID produk ini
    setInitializedId(product.id);
  }

  // Hitung state kotor langsung selama render tanpa useEffect
  const checkIsDirty = (): boolean => {
    if (!product) return false;
    if (name !== product.name) return true;
    if (sku !== product.sku) return true;
    if (description !== (product.description ?? '')) return true;
    if (shortDescription !== (product.short_description ?? '')) return true;
    if (basePrice !== (product.base_price ? Number(product.base_price) : ''))
      return true;
    if (status !== product.status) return true;
    if (isFeatured !== product.is_featured) return true;
    if (category?.id !== product.category?.id) return true;
    if (primaryImageUrl !== (product.primary_image_url ?? '')) return true;

    // Cek perbedaan pada varian
    if (variants.length !== product.variants.length) return true;
    const variantsDirty = variants.some((v, i) => {
      const pv = product.variants[i];
      if (!pv) return true;
      if (v.name !== pv.name) return true;
      if (v.sku !== pv.sku) return true;
      if (v.price !== Number(pv.price)) return true;
      if (v.stock !== Number(pv.stock)) return true;
      // Perhatikan: pv.weight bisa berupa string jika datang dari API
      if (v.weight !== (pv.weight ? Number(pv.weight) : undefined)) return true;
      if (
        v.price_distributor !==
        (pv.price_distributor ? Number(pv.price_distributor) : undefined)
      )
        return true;
      return false;
    });
    if (variantsDirty) return true;

    return false;
  };

  const isDirty = checkIsDirty();

  const updateVariant = (i: number, updated: EditableVariant) =>
    setVariants((prev) => prev.map((v, j) => (j === i ? updated : v)));
  const removeVariant = (i: number) =>
    setVariants((prev) => prev.filter((_, j) => j !== i));
  const addVariant = () =>
    setVariants((prev) => [
      ...prev,
      { name: '', sku: '', price: 0, stock: 0, _isNew: true },
    ]);

  const validate = (): boolean => {
    const e: FormErrors = {};
    if (!name.trim()) e.name = 'Nama produk wajib diisi.';
    if (!sku.trim()) e.sku = 'SKU wajib diisi.';
    if (!category) e.category_id = 'Pilih kategori terlebih dahulu.';
    if (basePrice === '' || Number(basePrice) < 0)
      e.base_price = 'Harga dasar wajib diisi.';
    if (variants.length === 0) e.variants = 'Minimal 1 varian diperlukan.';
    if (variants.some((v) => !v.name || !v.sku))
      e.variants = 'Setiap varian harus memiliki nama dan SKU.';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleSubmit = async () => {
    if (!product || !validate()) return;

    const payload: UpdateProductPayload = {
      category_id: category!.id,
      name: name.trim(),
      sku: sku.trim().toUpperCase(),
      description: description || null,
      short_description: shortDescription || null,
      base_price: Number(basePrice),
      status,
      is_featured: isFeatured,

      variants: variants.map((v) => {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const { _id, _isNew, ...rest } = v as any;
        return {
          ...rest,
          id: _id,
          stock: Number(rest.stock || 0),
          price: Number(rest.price || 0),
          price_distributor: rest.price_distributor
            ? Number(rest.price_distributor)
            : null,
        };
      }),

      primary_image_url: primaryImageUrl || null,
      meta: {
        seo_title: seoTitle || null,
        seo_description: seoDescription || null,
      },
    };

    updateProduct.mutate(
      { id: product.id, payload },
      {
        onSuccess: () => {
          router.push(`/dashboard/admin/products/${product.slug}`);
        },
      }
    );
  };

  const handleBack = () => {
    if (!product) return router.push('/dashboard/admin/products');
    if (isDirty) setShowDiscard(true);
    else router.push(`/dashboard/admin/products/${product.slug}`);
  };

  if (isLoading) {
    return (
      <div className="max-w-4xl mx-auto space-y-6 pt-6 relative z-10">
        <div className="h-14 bg-white rounded-2xl w-1/3 animate-pulse shadow-sm" />
        {Array.from({ length: 3 }).map((_, i) => (
          <div
            key={i}
            className="h-64 bg-white rounded-3xl animate-pulse shadow-sm"
          />
        ))}
      </div>
    );
  }

  if (!product) {
    return (
      <div className="flex flex-col items-center justify-center py-32 text-center relative z-10">
        <div className="w-20 h-20 bg-white border border-gray-200 rounded-full flex items-center justify-center mb-6 shadow-sm">
          <Package className="w-10 h-10 text-gray-400" />
        </div>
        <p className="font-black text-gray-900 text-2xl tracking-tight mb-2">
          Produk Tidak Ditemukan
        </p>
        <button
          onClick={() => router.back()}
          className="mt-4 text-sm font-bold text-yellow-600 hover:text-yellow-700 transition-colors"
        >
          Kembali ke Daftar
        </button>
      </div>
    );
  }

  return (
    <>
      <div className="min-h-screen bg-transparent text-gray-900 relative overflow-hidden pb-32 sm:pb-24">
        {/* Background Glow Blobs */}
        <div className="absolute top-0 right-0 w-[500px] h-[500px] bg-yellow-400/10 rounded-full blur-[120px] pointer-events-none z-0" />
        <div className="absolute bottom-1/4 left-0 w-[400px] h-[400px] bg-yellow-400/10 rounded-full blur-[120px] pointer-events-none z-0" />

        <div className="relative z-10 max-w-4xl mx-auto space-y-8 pt-6 px-4 sm:px-6">
          {/* ── Topbar ── */}
          <motion.div
            initial={{ opacity: 0, y: 12 }}
            animate={{ opacity: 1, y: 0 }}
            className="flex flex-col sm:flex-row sm:items-center justify-between gap-6"
          >
            <div className="flex items-start gap-4">
              <button
                onClick={handleBack}
                className="p-3 rounded-xl bg-white/60 backdrop-blur-md border border-gray-200 text-gray-500 hover:text-gray-900 hover:bg-white shadow-sm transition-all mt-1 shrink-0"
              >
                <ArrowLeft className="w-5 h-5" />
              </button>
              <div>
                <div className="flex items-center gap-3">
                  <h1 className="text-3xl font-black text-gray-900 tracking-tight leading-none mb-2">
                    Edit Produk
                  </h1>
                  {isDirty && <DirtyDot />}
                </div>
                <p className="text-xs font-mono font-medium text-gray-500 tracking-widest bg-gray-100 border border-gray-200 px-2 py-1 rounded-md inline-block">
                  {product.sku}
                </p>
              </div>
            </div>

            <div className="hidden sm:flex items-center gap-3">
              <button
                type="button"
                onClick={handleBack}
                className="px-6 py-3.5 rounded-xl text-sm font-bold text-gray-600 border border-gray-200 bg-white/60 hover:bg-white hover:text-gray-900 shadow-sm transition-all"
              >
                Batal
              </button>
              <button
                type="button"
                onClick={() => {
                  if (product) {
                    setName(product.name);
                    setSku(product.sku);
                    setDescription(product.description ?? '');
                    setShortDescription(product.short_description ?? '');
                    setBasePrice(
                      product.base_price ? Number(product.base_price) : ''
                    );
                    setStatus(product.status);
                    setIsFeatured(product.is_featured);
                    setCategory(product.category);
                    setVariants(
                      product.variants.map((v) => ({
                        _id: v.id,
                        name: v.name,
                        sku: v.sku,
                        price: Number(v.price),
                        stock: v.stock,
                        weight: v.weight ? Number(v.weight) : undefined,
                        price_distributor: v.price_distributor
                          ? Number(v.price_distributor)
                          : undefined,
                        attributes: v.attributes,
                      }))
                    );
                    setPrimaryImageUrl(product.primary_image_url ?? '');
                  }
                }}
                className="px-4 py-3.5 rounded-xl text-gray-600 border border-gray-200 bg-white/60 hover:bg-white hover:text-gray-900 shadow-sm transition-all"
              >
                <RefreshCw className="w-4 h-4" />
              </button>
              <button
                type="button"
                onClick={handleSubmit}
                disabled={updateProduct.isPending}
                className="flex items-center gap-2 px-8 py-3.5 rounded-xl bg-yellow-400 hover:bg-yellow-500 text-yellow-900 text-sm font-bold tracking-wide transition-all shadow-lg shadow-yellow-400/20 disabled:opacity-60"
              >
                {updateProduct.isPending ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <Save className="w-4 h-4" />
                )}
                Simpan Perubahan
              </button>
            </div>
          </motion.div>

          {/* Dirty banner */}
          <AnimatePresence>
            {isDirty && (
              <motion.div
                initial={{ opacity: 0, y: -8 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -8 }}
                className="flex items-center gap-3 bg-amber-50 border border-amber-200 rounded-2xl px-5 py-4 text-sm text-amber-700 font-medium shadow-sm"
              >
                <AlertTriangle className="w-4 h-4 shrink-0" />
                <span>Ada perubahan yang belum disimpan.</span>
              </motion.div>
            )}
          </AnimatePresence>

          <div className="space-y-6">
            {/* 1 – Info */}
            <Section icon={Package} title="Informasi Produk" delay={0.05}>
              <div className="space-y-6">
                <div className="grid sm:grid-cols-2 gap-6">
                  <Field label="Nama Produk" required error={errors.name}>
                    <DarkInput
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      placeholder="Garam Himalaya Premium"
                      maxLength={255}
                    />
                  </Field>
                  <Field
                    label="SKU Produk"
                    required
                    hint="Kode unik produk"
                    error={errors.sku}
                  >
                    <DarkInput
                      value={sku}
                      onChange={(e) => setSku(e.target.value.toUpperCase())}
                      placeholder="GRM-HML-001"
                      maxLength={50}
                    />
                  </Field>
                </div>
                <Field label="Deskripsi Lengkap">
                  <DarkTextarea
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    placeholder="Deskripsi lengkap produk..."
                    rows={6}
                  />
                </Field>
                <Field label="Deskripsi Singkat" hint="Maks. 500 karakter">
                  <DarkTextarea
                    value={shortDescription}
                    onChange={(e) => setShortDescription(e.target.value)}
                    placeholder="Ringkasan singkat produk..."
                    maxLength={500}
                    rows={3}
                  />
                  <p className="text-right text-[10px] font-bold text-gray-500 uppercase tracking-widest mt-2">
                    {shortDescription.length} / 500
                  </p>
                </Field>
              </div>
            </Section>

            {/* 2 – Category & pricing */}
            <Section icon={Tag} title="Kategori & Harga" delay={0.08}>
              <div className="grid sm:grid-cols-2 gap-6">
                <Field label="Kategori" required error={errors.category_id}>
                  <CategoryPicker
                    categories={categories}
                    selected={category}
                    onSelect={setCategory}
                    isLoading={isCategoriesLoading}
                  />
                </Field>
                <Field
                  label="Harga Dasar (Rp)"
                  required
                  error={errors.base_price}
                >
                  <DarkInput
                    type="number"
                    min={0}
                    value={basePrice}
                    onChange={(e) =>
                      setBasePrice(e.target.value ? Number(e.target.value) : '')
                    }
                    placeholder="0"
                  />
                </Field>
                <Field label="Status Publikasi">
                  <div className="flex gap-3 bg-gray-50 p-1.5 rounded-xl border border-gray-200 shadow-sm">
                    {(['active', 'inactive', 'draft'] as ProductStatus[]).map(
                      (s) => (
                        <button
                          key={s}
                          type="button"
                          onClick={() => setStatus(s)}
                          className={cn(
                            'flex-1 py-2.5 rounded-lg text-xs font-bold uppercase tracking-wider transition-all',
                            status === s
                              ? s === 'active'
                                ? 'bg-emerald-50 text-emerald-700 shadow-sm border border-emerald-100'
                                : 'bg-white text-gray-900 shadow-sm border border-gray-200'
                              : 'text-gray-500 hover:text-gray-700'
                          )}
                        >
                          {s === 'active' ? 'Aktif' : 'Nonaktif'}
                        </button>
                      )
                    )}
                  </div>
                </Field>
                <Field label="Sorotan">
                  <button
                    type="button"
                    onClick={() => setIsFeatured((v) => !v)}
                    className={cn(
                      'w-full py-3 rounded-xl text-sm font-bold tracking-wide transition-all border flex items-center justify-center gap-2 shadow-sm',
                      isFeatured
                        ? 'bg-yellow-50 border-yellow-200 text-yellow-700'
                        : 'bg-white/40 border-gray-200 text-gray-500 hover:border-gray-300 hover:text-gray-700'
                    )}
                  >
                    {isFeatured ? (
                      <Sparkles className="w-4 h-4 fill-current" />
                    ) : (
                      <Sparkles className="w-4 h-4" />
                    )}
                    {isFeatured
                      ? 'Produk Unggulan (Featured)'
                      : 'Jadikan Unggulan'}
                  </button>
                </Field>
              </div>
            </Section>

            {/* 3 – Variants */}
            <Section
              icon={Layers}
              title="Varian Produk"
              subtitle="Minimal 1 varian diperlukan"
              delay={0.11}
            >
              <div className="space-y-4">
                {errors.variants && (
                  <div className="bg-rose-500/10 border border-rose-500/20 px-4 py-3 rounded-xl flex items-center gap-3 mb-4">
                    <div className="w-1.5 h-1.5 rounded-full bg-rose-500 animate-pulse" />
                    <p className="text-xs font-bold text-rose-400 tracking-wide">
                      {errors.variants}
                    </p>
                  </div>
                )}
                <div className="space-y-3">
                  {variants.map((variant, i) => (
                    <VariantRow
                      key={variant._id ?? `new-${i}`}
                      variant={variant}
                      index={i}
                      isNew={variant._isNew}
                      onChange={(updated) =>
                        updateVariant(i, {
                          ...updated,
                          _id: variant._id,
                          _isNew: variant._isNew,
                        })
                      }
                      onRemove={() => removeVariant(i)}
                      canRemove={variants.length > 1}
                    />
                  ))}
                </div>
                <button
                  type="button"
                  onClick={addVariant}
                  className="w-full flex items-center justify-center gap-2 py-4 rounded-2xl border-2 border-dashed border-gray-300 text-sm font-bold text-gray-500 hover:border-yellow-400 hover:text-yellow-600 hover:bg-yellow-50 transition-all mt-4"
                >
                  <Plus className="w-5 h-5" /> Tambah Varian Baru
                </button>
              </div>
            </Section>

            {/* 4 – Images */}
            <Section
              icon={ImageIcon}
              title="Gambar Produk"
              subtitle="Masukkan URL gambar produk (contoh: /images/products/product-250g.avif)."
              delay={0.14}
            >
              <Field
                label="URL Gambar Utama"
                hint="Path gambar di frontend public folder"
              >
                <DarkInput
                  value={primaryImageUrl}
                  onChange={(e) => setPrimaryImageUrl(e.target.value)}
                  placeholder="/images/products/product-250g.avif"
                />
              </Field>
            </Section>

            {/* 5 – SEO */}
            {/* <Section
              icon={Info}
              title="Optimasi SEO"
              subtitle="Opsional"
              delay={0.17}
            >
              <div className="space-y-6">
                <Field label="SEO Title" hint="Maks. 70 karakter">
                  <DarkInput
                    value={seoTitle}
                    onChange={(e) => setSeoTitle(e.target.value)}
                    maxLength={70}
                    placeholder="Judul halaman untuk Google..."
                  />
                  <p className="text-right text-[10px] font-bold text-gray-500 uppercase tracking-widest mt-2">
                    {seoTitle.length} / 70
                  </p>
                </Field>
                <Field label="SEO Description" hint="Maks. 160 karakter">
                  <DarkTextarea
                    value={seoDescription}
                    onChange={(e) => setSeoDescription(e.target.value)}
                    maxLength={160}
                    rows={3}
                    placeholder="Deskripsi halaman untuk Google..."
                  />
                  <p className="text-right text-[10px] font-bold text-gray-500 uppercase tracking-widest mt-2">
                    {seoDescription.length} / 160
                  </p>
                </Field>
              </div>
            </Section> */}
          </div>
        </div>

        {/* Mobile sticky footer */}
        <div className="fixed bottom-0 left-0 right-0 sm:hidden bg-white/90 backdrop-blur-xl border-t border-gray-200 px-4 py-4 z-40 shadow-[0_-10px_40px_rgba(0,0,0,0.05)]">
          <div className="flex gap-3">
            <button
              type="button"
              onClick={handleBack}
              className="flex-1 py-3.5 text-xs font-bold text-gray-600 bg-white border border-gray-200 rounded-xl transition-colors shadow-sm"
            >
              Batal
            </button>
            <button
              type="button"
              onClick={handleSubmit}
              disabled={updateProduct.isPending}
              className="flex-2 py-3.5 text-xs font-bold text-yellow-900 bg-yellow-400 rounded-xl flex items-center justify-center gap-2 disabled:opacity-60 shadow-lg shadow-yellow-400/20"
            >
              {updateProduct.isPending ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Save className="w-4 h-4" />
              )}{' '}
              Simpan
            </button>
          </div>
        </div>
      </div>

      {/* Discard dialog */}
      <AnimatePresence>
        {showDiscard && (
          <DiscardDialog
            onConfirm={() =>
              router.push(`/dashboard/admin/products/${product.slug}`)
            }
            onCancel={() => setShowDiscard(false)}
          />
        )}
      </AnimatePresence>
    </>
  );
}
