/**
 * 카테고리 추가/수정 모달 컴포넌트
 */
import { memo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { HexColorPicker } from 'react-colorful';
import { COLOR_OPTIONS } from '@/utils/color';

/**
 * @param {Object} props
 * @param {boolean} props.isOpen - 모달 열림 여부
 * @param {Function} props.onClose - 모달 닫기 핸들러
 * @param {Object|null} props.editingCategory - 수정 중인 카테고리 (null이면 추가 모드)
 * @param {Object} props.formData - 폼 데이터 { name, color }
 * @param {Function} props.setFormData - 폼 데이터 업데이트 함수
 * @param {boolean} props.colorPickerOpen - 컬러 피커 열림 여부
 * @param {Function} props.setColorPickerOpen - 컬러 피커 상태 변경 함수
 * @param {Function} props.onSave - 저장 핸들러
 */
const CategoryFormModal = memo(function CategoryFormModal({
  isOpen,
  onClose,
  editingCategory,
  formData,
  setFormData,
  colorPickerOpen,
  setColorPickerOpen,
  onSave,
}) {
  return (
    <AnimatePresence>
      {isOpen && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="fixed inset-0 bg-black/50 flex items-center justify-center z-50"
          onClick={onClose}
        >
          <motion.div
            initial={{ scale: 0.9, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0.9, opacity: 0 }}
            className="bg-white rounded-2xl p-6 w-full mx-4 shadow-xl"
            style={{ maxWidth: '452px', minWidth: '452px' }}
            onClick={(e) => e.stopPropagation()}
          >
            <h3 className="text-xl font-bold text-gray-900 mb-6">
              {editingCategory ? '카테고리 수정' : '카테고리 추가'}
            </h3>

            {/* 카테고리 이름 */}
            <div className="mb-6">
              <label className="block text-sm font-medium text-gray-700 mb-2">카테고리 이름 *</label>
              <input
                type="text"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                placeholder="예: 방송, 이벤트"
                className="w-full px-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              />
            </div>

            {/* 색상 선택 */}
            <div className="mb-8">
              <label className="block text-sm font-medium text-gray-700 mb-3">색상 선택 *</label>
              <div className="flex flex-wrap gap-3">
                {COLOR_OPTIONS.map((color) => (
                  <button
                    key={color.id}
                    type="button"
                    onClick={() => setFormData({ ...formData, color: color.id })}
                    className={`w-10 h-10 rounded-full ${color.bg} transition-all ${
                      formData.color === color.id
                        ? 'ring-2 ring-offset-2 ring-gray-400 scale-110'
                        : 'hover:scale-105'
                    }`}
                    title={color.name}
                  />
                ))}
                {/* 커스텀 색상 - 무지개 그라디언트 버튼 */}
                <div className="relative">
                  <button
                    type="button"
                    onClick={(e) => {
                      e.stopPropagation();
                      setColorPickerOpen(!colorPickerOpen);
                    }}
                    className={`w-10 h-10 rounded-full transition-all ${
                      formData.color?.startsWith('#')
                        ? 'ring-2 ring-offset-2 ring-gray-400 scale-110'
                        : 'hover:scale-105'
                    }`}
                    style={{
                      background: formData.color?.startsWith('#')
                        ? formData.color
                        : 'conic-gradient(from 0deg, #ff0000, #ff8000, #ffff00, #00ff00, #00ffff, #0000ff, #8000ff, #ff0080, #ff0000)',
                    }}
                    title="커스텀 색상"
                  />
                  {/* 색상 선택 팝업 */}
                  <AnimatePresence>
                    {colorPickerOpen && (
                      <>
                        {/* 바깥 영역 클릭시 컬러피커만 닫기 */}
                        <div
                          className="fixed inset-0 z-40"
                          onClick={(e) => {
                            e.stopPropagation();
                            setColorPickerOpen(false);
                          }}
                        />
                        <motion.div
                          initial={{ opacity: 0, scale: 0.9, y: -10 }}
                          animate={{ opacity: 1, scale: 1, y: 0 }}
                          exit={{ opacity: 0, scale: 0.9, y: -10 }}
                          className="absolute top-12 left-0 z-50 p-4 bg-white rounded-2xl shadow-xl border border-gray-100"
                          style={{ width: '240px' }}
                          onClick={(e) => e.stopPropagation()}
                        >
                          <HexColorPicker
                            color={formData.color?.startsWith('#') ? formData.color : '#6b7280'}
                            onChange={(color) => setFormData({ ...formData, color })}
                            style={{ width: '100%', height: '180px' }}
                          />
                          <div className="mt-4 flex items-center">
                            <span className="px-3 py-2 text-sm bg-gray-100 border border-r-0 border-gray-200 rounded-l-lg text-gray-500">
                              #
                            </span>
                            <input
                              type="text"
                              value={formData.color?.startsWith('#') ? formData.color.slice(1) : ''}
                              onChange={(e) => {
                                const val = e.target.value.replace(/[^0-9A-Fa-f]/g, '').slice(0, 6);
                                if (val) {
                                  setFormData({ ...formData, color: '#' + val });
                                }
                              }}
                              placeholder="FFFFFF"
                              className="w-full px-3 py-2 text-sm border border-gray-200 rounded-r-lg focus:outline-none focus:ring-2 focus:ring-primary"
                              style={{ minWidth: 0 }}
                            />
                          </div>
                          <div className="mt-3 flex justify-end gap-2">
                            <button
                              type="button"
                              onClick={() => {
                                setFormData({ ...formData, color: 'blue' });
                                setColorPickerOpen(false);
                              }}
                              className="px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
                            >
                              취소
                            </button>
                            <button
                              type="button"
                              onClick={() => setColorPickerOpen(false)}
                              className="px-3 py-1.5 text-sm bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors"
                            >
                              확인
                            </button>
                          </div>
                        </motion.div>
                      </>
                    )}
                  </AnimatePresence>
                </div>
              </div>
            </div>

            {/* 버튼 */}
            <div className="flex justify-end gap-3">
              <button
                type="button"
                onClick={onClose}
                className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
              >
                취소
              </button>
              <button
                type="button"
                onClick={onSave}
                className="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors"
              >
                {editingCategory ? '수정' : '추가'}
              </button>
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
});

export default CategoryFormModal;
