'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { motion } from 'framer-motion';
import { ArrowLeft, Loader2, FolderPlus, Info, Save } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useCreateCategory } from '@/hooks';

interface FormErrors {
  name?: string;
}

export default function AddCategoryPage() {
  const router = useRouter();
  const createCategory = useCreateCategory();

  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [isActive, setIsActive] = useState(true);
  const [errors, setErrors] = useState<FormErrors>({});

  const validate = () => {
    const nextErrors: FormErrors = {};
    if (!name.trim()) nextErrors.name = 'Nama kategori wajib diisi.';
    setErrors(nextErrors);
    return Object.keys(nextErrors).length === 0;
  };

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

    createCategory.mutate(
      {
        name: name.trim(),
        is_active: isActive,
        description: description.trim() || null,
      },
      {
        onSuccess: () => {
          router.push('/dashboard/admin/categories');
        },
      }
    );
  };

  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-3xl 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={() => router.back()}
              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 transition-all mt-1 shrink-0 shadow-sm"
            >
              <ArrowLeft className="w-5 h-5" />
            </button>
            <div>
              <h1 className="text-3xl font-black text-gray-900 tracking-tight leading-none mb-2">
                Tambah <span className="text-yellow-600">Kategori</span>
              </h1>
              <p className="text-sm font-medium text-gray-500 tracking-wide">
                Buat kategori baru untuk mengelompokkan produk.
              </p>
            </div>
          </div>

          <div className="hidden sm:flex items-center gap-3">
            <button
              type="button"
              onClick={() => router.back()}
              className="px-6 py-3.5 rounded-xl text-sm font-bold text-gray-500 bg-white border border-gray-200 hover:bg-gray-50 hover:text-gray-900 transition-all shadow-sm"
            >
              Batal
            </button>
            <button
              type="button"
              onClick={handleSubmit}
              disabled={createCategory.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"
            >
              {createCategory.isPending ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Save className="w-4 h-4" />
              )}
              Simpan
            </button>
          </div>
        </motion.div>

        {/* ── Main Form Card ── */}
        <motion.div
          initial={{ opacity: 0, y: 8 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.05 }}
          className="bg-white/60 backdrop-blur-xl border border-gray-200 rounded-3xl overflow-hidden shadow-sm"
        >
          <div className="flex items-center gap-4 px-6 sm:px-8 py-6 border-b border-gray-200 bg-white/40">
            <div className="p-2.5 bg-yellow-50 border border-yellow-200 rounded-xl shrink-0 shadow-sm">
              <FolderPlus className="w-5 h-5 text-yellow-600" />
            </div>
            <div>
              <h2 className="text-sm font-bold text-gray-900 tracking-wide">
                Informasi Kategori
              </h2>
              <p className="text-[10px] text-gray-500 font-bold uppercase tracking-widest mt-1">
                Data utama yang akan ditampilkan
              </p>
            </div>
          </div>

          <div className="p-6 sm:p-8 space-y-6">
            {/* Input Nama */}
            <div className="space-y-2">
              <label className="flex items-center gap-1.5 text-xs font-bold text-gray-500 tracking-wide">
                Nama Kategori <span className="text-rose-500">*</span>
              </label>
              <input
                value={name}
                onChange={(event) => setName(event.target.value)}
                placeholder="Contoh: Garam Dapur Premium"
                maxLength={255}
                className={cn(
                  'w-full px-4 py-3.5 bg-white border rounded-xl text-sm font-medium text-gray-900 placeholder:text-gray-400 focus:outline-none focus:border-yellow-400 focus:ring-1 focus:ring-yellow-400 transition-all shadow-sm',
                  errors.name
                    ? 'border-rose-500/50 ring-1 ring-rose-500/50'
                    : 'border-gray-200'
                )}
              />
              {errors.name && (
                <p className="text-[10px] font-bold text-rose-500 uppercase tracking-widest flex items-center gap-1.5 mt-2">
                  <span className="w-1 h-1 bg-rose-500 rounded-full shrink-0" />
                  {errors.name}
                </p>
              )}
            </div>

            {/* Input Deskripsi */}
            <div className="space-y-2">
              <label className="flex items-center gap-1.5 text-xs font-bold text-gray-500 tracking-wide">
                Deskripsi (Opsional)
              </label>
              <textarea
                value={description}
                onChange={(event) => setDescription(event.target.value)}
                rows={4}
                maxLength={500}
                placeholder="Tuliskan deskripsi singkat mengenai kategori ini..."
                className="w-full px-4 py-3.5 bg-white border border-gray-200 rounded-xl text-sm font-medium text-gray-900 placeholder:text-gray-400 focus:outline-none focus:border-yellow-400 focus:ring-1 focus:ring-yellow-400 transition-all resize-none shadow-sm"
              />
              <p className="text-right text-[10px] font-bold text-gray-400 uppercase tracking-widest mt-2">
                {description.length} / 500
              </p>
            </div>

            {/* Status Toggle */}
            <div className="space-y-2">
              <label className="flex items-center gap-1.5 text-xs font-bold text-gray-500 tracking-wide">
                Status Publikasi
              </label>
              <div className="flex gap-3 bg-gray-50 p-1.5 rounded-xl border border-gray-200 shadow-sm">
                <button
                  type="button"
                  onClick={() => setIsActive(true)}
                  className={cn(
                    'flex-1 py-2.5 rounded-lg text-xs font-bold uppercase tracking-wider transition-all',
                    isActive
                      ? 'bg-emerald-50 text-emerald-700 shadow-sm border border-emerald-100'
                      : 'text-gray-500 hover:text-gray-700'
                  )}
                >
                  Aktif
                </button>
                <button
                  type="button"
                  onClick={() => setIsActive(false)}
                  className={cn(
                    'flex-1 py-2.5 rounded-lg text-xs font-bold uppercase tracking-wider transition-all',
                    !isActive
                      ? 'bg-white text-gray-900 shadow-sm border border-gray-200'
                      : 'text-gray-500 hover:text-gray-700'
                  )}
                >
                  Nonaktif
                </button>
              </div>
            </div>

            {/* Info Box */}
            <div className="mt-4 bg-yellow-50 border border-yellow-200 rounded-2xl p-4 flex items-start gap-3 shadow-sm">
              <div className="p-1.5 bg-yellow-100 rounded-lg shrink-0 mt-0.5 border border-yellow-200">
                <Info className="w-4 h-4 text-yellow-600" />
              </div>
              <p className="text-xs text-gray-600 font-medium leading-relaxed">
                <strong className="text-gray-900">Catatan:</strong> URL (Slug)
                kategori akan dibuat secara otomatis berdasarkan nama kategori
                yang Anda masukkan.
              </p>
            </div>
          </div>
        </motion.div>
      </div>

      {/* ── Mobile Sticky Footer ── */}
      <div className="fixed bottom-0 left-0 right-0 sm:hidden bg-white/95 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={() => router.back()}
            className="flex-1 py-3.5 text-xs font-bold text-gray-500 bg-gray-50 border border-gray-200 rounded-xl transition-colors shadow-sm"
          >
            Batal
          </button>
          <button
            type="button"
            onClick={handleSubmit}
            disabled={createCategory.isPending}
            className="flex-2 py-3.5 text-xs font-bold text-yellow-900 bg-yellow-400 hover:bg-yellow-500 rounded-xl flex items-center justify-center gap-2 disabled:opacity-60 shadow-lg shadow-yellow-400/20"
          >
            {createCategory.isPending ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <Save className="w-4 h-4" />
            )}
            Simpan
          </button>
        </div>
      </div>
    </div>
  );
}
