/* eslint-disable @typescript-eslint/no-explicit-any */
'use client';

import { useEffect, useState } from 'react';
import Image from 'next/image';
import { motion, Variants, AnimatePresence } from 'framer-motion';
import {
  Plus,
  Edit2,
  Trash2,
  CheckCircle2,
  XCircle,
  PackageOpen,
  X,
} from 'lucide-react';
import { RewardService, PointItem } from '@/lib/services/reward.service';
import { cn, formatIDR } from '@/lib/utils';
import { toast } from 'sonner';

const fadeUp: Variants = {
  hidden: { opacity: 0, y: 16 },
  visible: (i = 0) => ({
    opacity: 1,
    y: 0,
    transition: { delay: i * 0.07, duration: 0.45, ease: [0.22, 1, 0.36, 1] },
  }),
};

const ELIGIBLE_FOR_CONFIG: Record<
  string,
  { label: string; className: string }
> = {
  all: {
    label: 'Semua',
    className: 'bg-gray-100 text-gray-600 border-gray-200',
  },
  user: {
    label: 'User Saja',
    className: 'bg-emerald-500/10 text-emerald-600 border-emerald-500/20',
  },
  agen: {
    label: 'Agen Saja',
    className: 'bg-blue-500/10 text-blue-600 border-blue-500/20',
  },
};

export default function AdminRewardItemsPage() {
  const [items, setItems] = useState<PointItem[]>([]);
  const [loading, setLoading] = useState(true);

  // Form State
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [formData, setFormData] = useState<Partial<PointItem>>({
    name: '',
    type: 'PHYSICAL',
    stock: 0,
    point_cost: 0,
    discount_type: null,
    discount_value: null,
    expiry_days: 30,
    is_active: true,
    eligible_for: 'all',
    max_redeem: null,
  });

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

  const fetchItems = async () => {
    try {
      const res = await RewardService.adminGetItems();
      setItems(res.data);
    } catch (_error) {
      toast.error('Gagal memuat master data hadiah.');
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (editingId) {
        const res = await RewardService.adminUpdateItem(editingId, formData);
        toast.success(res.message);
      } else {
        const res = await RewardService.adminCreateItem(formData);
        toast.success(res.message);
      }
      setShowForm(false);
      setEditingId(null);
      setFormData({
        name: '',
        type: 'PHYSICAL',
        stock: 0,
        point_cost: 0,
        discount_type: null,
        discount_value: null,
        expiry_days: 30,
        is_active: true,
        eligible_for: 'all',
        max_redeem: null,
      });
      fetchItems();
    } catch (_error) {
      toast.error('Gagal menyimpan data.');
    }
  };

  const handleEdit = (item: PointItem) => {
    setFormData(item);
    setEditingId(item.id);
    setShowForm(true);
  };

  const handleDelete = async (id: number) => {
    if (!confirm('Hapus item ini?')) return;
    try {
      const res = await RewardService.adminDeleteItem(id);
      toast.success(res.message);
      fetchItems();
    } catch (_error) {
      toast.error('Gagal menghapus item.');
    }
  };

  return (
    <div className="min-h-screen bg-transparent relative overflow-hidden pb-24">
      {/* Background Glow Blobs */}
      <div className="fixed top-0 right-0 w-[500px] h-[500px] bg-yellow-400/10 rounded-full blur-[120px] pointer-events-none z-0" />
      <div className="fixed bottom-0 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-7xl mx-auto space-y-6 pt-6 px-4 sm:px-6">
        {/* ── Header ── */}
        <motion.div
          initial="hidden"
          animate="visible"
          variants={fadeUp}
          custom={0}
          className="flex flex-col sm:flex-row sm:items-end justify-between gap-4 relative"
        >
          <div>
            <h1 className="text-3xl sm:text-4xl font-black text-gray-900 tracking-tight leading-none mb-2">
              Master <span className="text-yellow-600">Hadiah</span>
            </h1>
            <p className="text-sm font-medium text-gray-500 tracking-wide">
              Kelola item hadiah dan voucher diskon.
            </p>
          </div>

          {/* Admin Mascot */}
          <div className="absolute right-64 -top-8 w-24 md:w-32 opacity-20 pointer-events-none hidden md:block z-0">
            <Image
              src="/mascots/capt-yodi-chill-pose.avif"
              alt="Captain Yodi"
              width={200}
              height={200}
              className="w-full h-auto object-contain"
            />
          </div>

          {!showForm && (
            <button
              onClick={() => setShowForm(true)}
              className="relative z-10 flex items-center justify-center gap-2 px-6 py-3 bg-white border border-gray-200 hover:border-yellow-400 hover:bg-yellow-50 text-gray-600 hover:text-yellow-700 rounded-xl text-sm font-bold transition-all shadow-sm shrink-0"
            >
              <Plus className="w-4 h-4" />
              Tambah Item
            </button>
          )}
        </motion.div>

        {/* ── Form Modal/Drawer ── */}
        <AnimatePresence>
          {showForm && (
            <motion.div
              initial={{ opacity: 0, height: 0, y: -20 }}
              animate={{ opacity: 1, height: 'auto', y: 0 }}
              exit={{ opacity: 0, height: 0, y: -20 }}
              className="overflow-hidden"
            >
              <div className="bg-white/80 backdrop-blur-xl p-6 md:p-8 rounded-3xl shadow-sm border border-gray-200">
                <div className="flex justify-between items-center mb-6">
                  <h3 className="font-black text-gray-900 text-xl tracking-tight">
                    {editingId ? 'Edit Item' : 'Tambah Item Baru'}
                  </h3>
                  <button
                    type="button"
                    onClick={() => {
                      setShowForm(false);
                      setEditingId(null);
                    }}
                    className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-full transition-colors"
                  >
                    <X className="w-5 h-5" />
                  </button>
                </div>

                <form onSubmit={handleSave} className="space-y-6">
                  <div className="grid sm:grid-cols-2 gap-6">
                    <div>
                      <label className="block text-xs font-bold text-gray-700 mb-2">
                        Nama Item <span className="text-rose-500">*</span>
                      </label>
                      <input
                        required
                        type="text"
                        value={formData.name || ''}
                        onChange={(e) =>
                          setFormData({ ...formData, name: e.target.value })
                        }
                        className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm bg-gray-50 focus:bg-white focus:outline-none focus:border-yellow-400 focus:ring-1 focus:ring-yellow-400 transition-all shadow-sm"
                        placeholder="Misal: Payung Cantik"
                      />
                    </div>

                    <div>
                      <label className="block text-xs font-bold text-gray-700 mb-2">
                        Tipe <span className="text-rose-500">*</span>
                      </label>
                      <select
                        value={formData.type || 'PHYSICAL'}
                        onChange={(e) =>
                          setFormData({
                            ...formData,
                            type: e.target.value as any,
                          })
                        }
                        className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm bg-gray-50 focus:bg-white focus:outline-none focus:border-yellow-400 focus:ring-1 focus:ring-yellow-400 transition-all shadow-sm"
                      >
                        <option value="PHYSICAL">Barang Fisik</option>
                        <option value="VOUCHER">Voucher Diskon</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-xs font-bold text-gray-700 mb-2">
                        Stok <span className="text-rose-500">*</span>
                      </label>
                      <input
                        required
                        type="number"
                        min="0"
                        value={formData.stock || 0}
                        onChange={(e) =>
                          setFormData({
                            ...formData,
                            stock: parseInt(e.target.value),
                          })
                        }
                        className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm bg-gray-50 focus:bg-white focus:outline-none focus:border-yellow-400 focus:ring-1 focus:ring-yellow-400 transition-all shadow-sm"
                      />
                    </div>

                    <div>
                      <label className="block text-xs font-bold text-gray-700 mb-2">
                        Harga Poin <span className="text-rose-500">*</span>
                      </label>
                      <input
                        required
                        type="number"
                        min="0"
                        value={formData.point_cost || 0}
                        onChange={(e) =>
                          setFormData({
                            ...formData,
                            point_cost: parseInt(e.target.value),
                          })
                        }
                        className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm bg-gray-50 focus:bg-white focus:outline-none focus:border-yellow-400 focus:ring-1 focus:ring-yellow-400 transition-all shadow-sm"
                      />
                    </div>

                    <div>
                      <label className="block text-xs font-bold text-gray-700 mb-2">
                        Maks Penukaran
                      </label>
                      <input
                        type="number"
                        min="1"
                        value={formData.max_redeem || ''}
                        onChange={(e) =>
                          setFormData({
                            ...formData,
                            max_redeem: e.target.value
                              ? parseInt(e.target.value)
                              : null,
                          })
                        }
                        placeholder="Tidak terbatas"
                        className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm bg-gray-50 focus:bg-white focus:outline-none focus:border-yellow-400 focus:ring-1 focus:ring-yellow-400 transition-all shadow-sm"
                      />
                      <p className="text-[10px] text-gray-500 mt-1">
                        Kosongkan jika tidak ada batas
                      </p>
                    </div>

                    {/* ── Eligible For ── */}
                    <div>
                      <label className="block text-xs font-bold text-gray-700 mb-2">
                        Berlaku Untuk <span className="text-rose-500">*</span>
                      </label>
                      <select
                        value={formData.eligible_for || 'all'}
                        onChange={(e) =>
                          setFormData({
                            ...formData,
                            eligible_for: e.target.value as any,
                          })
                        }
                        className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm bg-gray-50 focus:bg-white focus:outline-none focus:border-yellow-400 focus:ring-1 focus:ring-yellow-400 transition-all shadow-sm"
                      >
                        <option value="all">Semua (User & Agen)</option>
                        <option value="user">Hanya User</option>
                        <option value="agen">Hanya Agen</option>
                      </select>
                    </div>

                    {formData.type === 'VOUCHER' && (
                      <>
                        <div>
                          <label className="block text-xs font-bold text-gray-700 mb-2">
                            Tipe Diskon <span className="text-rose-500">*</span>
                          </label>
                          <select
                            value={formData.discount_type || 'FIXED'}
                            onChange={(e) =>
                              setFormData({
                                ...formData,
                                discount_type: e.target.value as any,
                              })
                            }
                            className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm bg-gray-50 focus:bg-white focus:outline-none focus:border-yellow-400 focus:ring-1 focus:ring-yellow-400 transition-all shadow-sm"
                          >
                            <option value="FIXED">Nominal (Rp)</option>
                            <option value="PERCENTAGE">Persentase (%)</option>
                          </select>
                        </div>
                        <div>
                          <label className="block text-xs font-bold text-gray-700 mb-2">
                            Nilai Diskon{' '}
                            <span className="text-rose-500">*</span>
                          </label>
                          <input
                            required
                            type="number"
                            min="0"
                            value={formData.discount_value || 0}
                            onChange={(e) =>
                              setFormData({
                                ...formData,
                                discount_value: parseInt(e.target.value),
                              })
                            }
                            className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm bg-gray-50 focus:bg-white focus:outline-none focus:border-yellow-400 focus:ring-1 focus:ring-yellow-400 transition-all shadow-sm"
                          />
                        </div>
                        <div>
                          <label className="block text-xs font-bold text-gray-700 mb-2">
                            Masa Berlaku (Hari){' '}
                            <span className="text-rose-500">*</span>
                          </label>
                          <input
                            required
                            type="number"
                            min="1"
                            value={formData.expiry_days || 30}
                            onChange={(e) =>
                              setFormData({
                                ...formData,
                                expiry_days: parseInt(e.target.value),
                              })
                            }
                            className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm bg-gray-50 focus:bg-white focus:outline-none focus:border-yellow-400 focus:ring-1 focus:ring-yellow-400 transition-all shadow-sm"
                          />
                        </div>
                      </>
                    )}
                  </div>

                  <div className="flex items-center gap-3 bg-gray-50 p-4 rounded-xl border border-gray-200 w-max shadow-sm">
                    <input
                      type="checkbox"
                      id="is_active"
                      checked={formData.is_active}
                      onChange={(e) =>
                        setFormData({
                          ...formData,
                          is_active: e.target.checked,
                        })
                      }
                      className="w-5 h-5 rounded border-gray-300 text-yellow-500 focus:ring-yellow-500 cursor-pointer"
                    />
                    <label
                      htmlFor="is_active"
                      className="text-sm font-bold text-gray-700 cursor-pointer"
                    >
                      Aktifkan Item Ini (Dapat ditukar)
                    </label>
                  </div>

                  <div className="flex gap-3 justify-end pt-4 border-t border-gray-200 mt-6">
                    <button
                      type="button"
                      onClick={() => {
                        setShowForm(false);
                        setEditingId(null);
                      }}
                      className="px-6 py-3 text-sm font-bold text-gray-600 hover:bg-gray-100 rounded-xl transition-colors"
                    >
                      Batal
                    </button>
                    <button
                      type="submit"
                      className="px-8 py-3 text-sm font-bold text-yellow-950 bg-yellow-400 rounded-xl hover:bg-yellow-500 transition-colors shadow-sm"
                    >
                      Simpan Item
                    </button>
                  </div>
                </form>
              </div>
            </motion.div>
          )}
        </AnimatePresence>

        {/* ── Data Table ── */}
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="relative bg-white/60 backdrop-blur-xl border border-gray-200 rounded-3xl overflow-hidden shadow-sm"
        >
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="bg-gray-50/50 border-b border-gray-200">
                  <th className="px-6 py-4 text-[10px] font-bold text-gray-500 uppercase tracking-widest whitespace-nowrap">
                    Nama Item
                  </th>
                  <th className="px-6 py-4 text-[10px] font-bold text-gray-500 uppercase tracking-widest whitespace-nowrap">
                    Tipe
                  </th>
                  <th className="px-6 py-4 text-[10px] font-bold text-gray-500 uppercase tracking-widest whitespace-nowrap">
                    Berlaku Untuk
                  </th>
                  <th className="px-6 py-4 text-[10px] font-bold text-gray-500 uppercase tracking-widest whitespace-nowrap">
                    Poin
                  </th>
                  <th className="px-6 py-4 text-[10px] font-bold text-gray-500 uppercase tracking-widest whitespace-nowrap">
                    Stok
                  </th>
                  <th className="px-6 py-4 text-[10px] font-bold text-gray-500 uppercase tracking-widest whitespace-nowrap">
                    Max Redeem
                  </th>
                  <th className="px-6 py-4 text-[10px] font-bold text-gray-500 uppercase tracking-widest whitespace-nowrap">
                    Status
                  </th>
                  <th className="px-6 py-4 text-[10px] font-bold text-gray-500 uppercase tracking-widest text-right whitespace-nowrap">
                    Aksi
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {loading ? (
                  <tr>
                    <td
                      colSpan={7}
                      className="px-6 py-10 text-center text-sm font-medium text-gray-500"
                    >
                      Memuat data hadiah...
                    </td>
                  </tr>
                ) : items.length === 0 ? (
                  <tr>
                    <td
                      colSpan={7}
                      className="px-6 py-16 text-center text-sm text-gray-500"
                    >
                      <div className="flex flex-col items-center justify-center">
                        <div className="w-16 h-16 bg-white border border-gray-200 rounded-full flex items-center justify-center mx-auto mb-4 shadow-sm">
                          <PackageOpen className="w-8 h-8 text-gray-400" />
                        </div>
                        <p className="font-bold text-gray-900 text-lg tracking-wide mb-1">
                          Belum ada item hadiah
                        </p>
                        <p className="text-sm font-medium text-gray-500">
                          Silakan tambahkan item baru.
                        </p>
                      </div>
                    </td>
                  </tr>
                ) : (
                  items.map((item) => {
                    const eligibleConfig =
                      ELIGIBLE_FOR_CONFIG[item.eligible_for] ??
                      ELIGIBLE_FOR_CONFIG.all;

                    return (
                      <tr
                        key={item.id}
                        className="hover:bg-gray-50/50 transition-colors"
                      >
                        <td className="px-6 py-5">
                          <div className="font-bold text-gray-900 text-sm">
                            {item.name}
                          </div>
                          {item.type === 'VOUCHER' && (
                            <div className="text-[10px] text-emerald-600 mt-1 uppercase font-black tracking-wider">
                              Diskon:{' '}
                              {item.discount_type === 'PERCENTAGE'
                                ? `${item.discount_value}%`
                                : formatIDR(item.discount_value || 0)}
                            </div>
                          )}
                        </td>
                        <td className="px-6 py-5">
                          <span
                            className={cn(
                              'inline-flex items-center px-2.5 py-1 text-[10px] font-bold uppercase tracking-widest border rounded-full',
                              item.type === 'PHYSICAL'
                                ? 'bg-blue-500/10 text-blue-600 border-blue-500/20'
                                : 'bg-purple-500/10 text-purple-600 border-purple-500/20'
                            )}
                          >
                            {item.type}
                          </span>
                        </td>
                        <td className="px-6 py-5">
                          <span
                            className={cn(
                              'inline-flex items-center px-2.5 py-1 text-[10px] font-bold uppercase tracking-widest border rounded-full',
                              eligibleConfig.className
                            )}
                          >
                            {eligibleConfig.label}
                          </span>
                        </td>
                        <td className="px-6 py-5">
                          <span className="font-black text-yellow-600 tracking-tight">
                            {item.point_cost}
                          </span>
                        </td>
                        <td className="px-6 py-5 font-bold text-gray-700">
                          {item.stock}
                        </td>
                        <td className="px-6 py-5 font-bold text-gray-700">
                          {item.max_redeem || '∞'}
                        </td>
                        <td className="px-6 py-5">
                          {item.is_active ? (
                            <span className="flex w-fit items-center gap-1.5 px-2.5 py-1 bg-emerald-500/10 border border-emerald-500/20 text-emerald-600 text-[10px] font-bold uppercase tracking-widest rounded-full">
                              <CheckCircle2 className="w-3.5 h-3.5" /> Aktif
                            </span>
                          ) : (
                            <span className="flex w-fit items-center gap-1.5 px-2.5 py-1 bg-gray-100 border border-gray-200 text-gray-500 text-[10px] font-bold uppercase tracking-widest rounded-full">
                              <XCircle className="w-3.5 h-3.5" /> Inaktif
                            </span>
                          )}
                        </td>
                        <td className="px-6 py-5">
                          <div className="flex items-center justify-end gap-2">
                            <button
                              onClick={() => handleEdit(item)}
                              className="p-2 text-blue-600 bg-blue-50 hover:bg-blue-100 rounded-lg transition-colors border border-transparent hover:border-blue-200"
                              title="Edit Item"
                            >
                              <Edit2 className="w-4 h-4" />
                            </button>
                            <button
                              onClick={() => handleDelete(item.id)}
                              className="p-2 text-rose-600 bg-rose-50 hover:bg-rose-100 rounded-lg transition-colors border border-transparent hover:border-rose-200"
                              title="Hapus Item"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </div>
                        </td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
          </div>
        </motion.div>
      </div>
    </div>
  );
}
