'use client';

import { useState, useRef, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { ChevronDown } from 'lucide-react';

interface Props {
  options: { value: string; label: string }[];
  value: string;
  onChange: (val: string) => void;
  placeholder: string;
  hasError?: boolean;
}

export default function CustomDropdown({ options, value, onChange, placeholder, hasError }: Props) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  const selectedLabel = options.find((o) => o.value === value)?.label ?? '';

  return (
    <div ref={ref} className="relative">
      <button
        type="button"
        onClick={() => setOpen((p) => !p)}
        className={`w-full px-3 py-3 rounded-md border text-sm text-left flex items-center justify-between transition-all outline-none focus:ring-2 ${
          hasError
            ? 'border-red-300 bg-red-50 focus:ring-red-200 focus:border-red-400'
            : 'border-gray-200 bg-white focus:ring-gray-900/10 focus:border-gray-400'
        } ${!value ? 'text-gray-400' : 'text-gray-900'}`}
      >
        <span className="truncate">{selectedLabel || placeholder}</span>
        <motion.span
          animate={{ rotate: open ? 180 : 0 }}
          transition={{ duration: 0.25, ease: [0.4, 0, 0.2, 1] }}
          className="flex-shrink-0 ml-2"
        >
          <ChevronDown className="w-4 h-4 text-gray-400" />
        </motion.span>
      </button>

      <AnimatePresence>
        {open && (
          <motion.div
            initial={{ opacity: 0, gridTemplateRows: '0fr' }}
            animate={{ opacity: 1, gridTemplateRows: '1fr' }}
            exit={{ opacity: 0, gridTemplateRows: '0fr' }}
            transition={{ duration: 0.28, ease: [0.4, 0, 0.2, 1] }}
            style={{ display: 'grid' }}
            className="absolute left-0 right-0 mt-1 z-[9999] bg-white border border-gray-200 rounded-xl shadow-xl shadow-gray-200/60 overflow-hidden"
          >
            <div className="overflow-hidden">
              <ul className="max-h-52 overflow-y-auto py-1 scrollbar-hide">
                {options.map((opt) => (
                  <li key={opt.value}>
                    <button
                      type="button"
                      onClick={() => { onChange(opt.value); setOpen(false); }}
                      className={`w-full text-left px-3 py-2.5 text-sm transition-colors ${
                        value === opt.value
                          ? 'bg-gray-900 text-white font-medium'
                          : 'text-gray-700 hover:bg-gray-50'
                      }`}
                    >
                      {opt.label}
                    </button>
                  </li>
                ))}
              </ul>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}