'use client';

import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { ChevronDown, SearchIcon, Loader2, Check } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { ProductCategory } from '@/lib/services/product.service';

export function CategoryPicker({
  categories,
  selected,
  onSelect,
  isLoading,
}: {
  categories: ProductCategory[];
  selected: ProductCategory | null;
  onSelect: (c: ProductCategory) => void;
  isLoading?: boolean;
}) {
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState('');

  const filtered = categories.filter((c) =>
    c.name.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="relative">
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className={cn(
          'w-full flex items-center justify-between px-4 py-3.5 bg-white/40 border rounded-xl text-sm font-medium transition-all shadow-sm',
          selected
            ? 'border-gray-200 text-gray-900'
            : 'border-gray-200 text-gray-500 hover:border-gray-300',
          open && 'border-yellow-400 ring-1 ring-yellow-400'
        )}
      >
        <span>{selected?.name ?? 'Pilih kategori...'}</span>
        <ChevronDown
          className={cn(
            'w-4 h-4 text-gray-500 transition-transform duration-200',
            open && 'rotate-180'
          )}
        />
      </button>

      <AnimatePresence>
        {open && (
          <>
            <div
              className="fixed inset-0 z-10"
              onClick={() => setOpen(false)}
            />
            <motion.div
              initial={{ opacity: 0, y: -4, scale: 0.95 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              exit={{ opacity: 0, y: -4, scale: 0.95 }}
              transition={{ duration: 0.15 }}
              className="absolute top-full left-0 right-0 mt-2 z-20 bg-white border border-gray-200 rounded-2xl shadow-xl overflow-hidden"
            >
              <div className="p-3 border-b border-gray-100 bg-gray-50">
                <div className="relative bg-white border border-gray-200 rounded-xl flex items-center px-3 focus-within:border-yellow-400 focus-within:ring-1 focus-within:ring-yellow-400 transition-all shadow-sm">
                  <SearchIcon className="w-4 h-4 text-gray-500 shrink-0" />
                  <input
                    autoFocus
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                    placeholder="Cari kategori..."
                    className="w-full pl-3 pr-2 py-2.5 text-sm bg-transparent text-gray-900 placeholder-gray-400 focus:outline-none"
                  />
                </div>
              </div>
              <div className="max-h-60 overflow-y-auto p-2 custom-scrollbar">
                {isLoading ? (
                  <div className="flex items-center justify-center py-8">
                    <Loader2 className="w-5 h-5 animate-spin text-[#FFD738]" />
                  </div>
                ) : filtered.length === 0 ? (
                  <p className="text-xs font-bold text-gray-500 text-center py-6">
                    Tidak ditemukan
                  </p>
                ) : (
                  filtered.map((c) => (
                    <button
                      key={c.id}
                      type="button"
                      onClick={() => {
                        onSelect(c);
                        setOpen(false);
                        setSearch('');
                      }}
                      className={cn(
                        'w-full flex items-center justify-between gap-3 px-4 py-3 rounded-xl text-sm font-medium transition-colors',
                        selected?.id === c.id
                          ? 'bg-yellow-50 text-yellow-700'
                          : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'
                      )}
                    >
                      <span>{c.name}</span>
                      {selected?.id === c.id && <Check className="w-4 h-4" />}
                    </button>
                  ))
                )}
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
}
