/**
 * 일괄 편집 패널 컴포넌트
 */
import { memo } from 'react';
import { Tag, Users, User, Users2, Check } from 'lucide-react';

/**
 * 범위 문자열 파싱
 */
export const parseRange = (rangeStr, baseNumber = 1) => {
  if (!rangeStr.trim()) return [];
  const indices = new Set();
  const parts = rangeStr.split(',').map((s) => s.trim());

  for (const part of parts) {
    if (part.includes('-')) {
      const [start, end] = part.split('-').map((n) => parseInt(n.trim()));
      if (!isNaN(start) && !isNaN(end)) {
        for (let i = Math.min(start, end); i <= Math.max(start, end); i++) {
          const idx = i - baseNumber;
          if (idx >= 0) indices.add(idx);
        }
      }
    } else {
      const num = parseInt(part);
      if (!isNaN(num)) {
        const idx = num - baseNumber;
        if (idx >= 0) indices.add(idx);
      }
    }
  }
  return Array.from(indices).sort((a, b) => a - b);
};

/**
 * @param {Object} props
 * @param {Object} props.bulkEdit - 일괄 편집 상태
 * @param {Function} props.setBulkEdit - 일괄 편집 상태 설정
 * @param {number} props.startNumber - 시작 번호
 * @param {number} props.pendingFilesCount - 대기 파일 수
 * @param {Array} props.members - 멤버 목록
 * @param {Function} props.onApply - 적용 핸들러
 */
const BulkEditPanel = memo(function BulkEditPanel({
  bulkEdit,
  setBulkEdit,
  startNumber,
  pendingFilesCount,
  members,
  onApply,
}) {
  const groupTypes = [
    { value: 'group', icon: Users, label: '단체' },
    { value: 'solo', icon: User, label: '개인' },
    { value: 'unit', icon: Users2, label: '유닛' },
  ];

  const toggleBulkMember = (memberId) => {
    setBulkEdit((prev) => ({
      ...prev,
      members: prev.members.includes(memberId)
        ? prev.members.filter((m) => m !== memberId)
        : [...prev.members, memberId],
    }));
  };

  return (
    <div className="w-72 flex-shrink-0">
      <div className="sticky top-24 bg-white rounded-2xl shadow-lg border border-gray-100 p-5">
        <h3 className="font-bold text-gray-900 mb-4 flex items-center gap-2">
          <Tag size={18} className="text-primary" />
          일괄 편집
        </h3>

        {/* 번호 범위 */}
        <div className="mb-4">
          <label className="block text-sm font-medium text-gray-700 mb-1.5">번호 범위</label>
          <input
            type="text"
            value={bulkEdit.range}
            onChange={(e) => setBulkEdit((prev) => ({ ...prev, range: e.target.value }))}
            placeholder={`예: ${startNumber}-${startNumber + 4}, ${startNumber + 7}`}
            className="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
          />
          <p className="text-xs text-gray-400 mt-1">
            {startNumber}~{startNumber + pendingFilesCount - 1}번 중{' '}
            {parseRange(bulkEdit.range, startNumber).filter((i) => i < pendingFilesCount).length}개
            선택
          </p>
        </div>

        {/* 타입 선택 */}
        <div className="mb-4">
          <label className="block text-sm font-medium text-gray-700 mb-1.5">타입</label>
          <div className="flex gap-1">
            {groupTypes.map(({ value, icon: Icon, label }) => (
              <button
                key={value}
                onClick={() =>
                  setBulkEdit((prev) => ({
                    ...prev,
                    groupType: prev.groupType === value ? '' : value,
                    members: value === 'group' ? [] : prev.members,
                  }))
                }
                className={`flex-1 py-1.5 px-2 rounded-lg text-xs font-medium transition-colors flex items-center justify-center gap-1 ${
                  bulkEdit.groupType === value
                    ? 'bg-primary text-white'
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                }`}
              >
                <Icon size={14} />
                {label}
              </button>
            ))}
          </div>
        </div>

        {/* 멤버 선택 */}
        {bulkEdit.groupType !== 'group' && (
          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 mb-1.5">
              멤버 {bulkEdit.groupType === 'solo' ? '(1명)' : '(다중 선택)'}
            </label>
            <div className="flex flex-wrap gap-1.5">
              {members
                .filter((m) => !m.is_former)
                .map((member) => (
                  <button
                    key={member.id}
                    onClick={() => {
                      if (bulkEdit.groupType === 'solo') {
                        setBulkEdit((prev) => ({
                          ...prev,
                          members: prev.members.includes(member.id) ? [] : [member.id],
                        }));
                      } else {
                        toggleBulkMember(member.id);
                      }
                    }}
                    className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
                      bulkEdit.members.includes(member.id)
                        ? 'bg-primary text-white border border-primary'
                        : 'bg-gray-100 text-gray-600 hover:bg-gray-200 border border-gray-100'
                    }`}
                  >
                    {member.name}
                  </button>
                ))}
              {members.filter((m) => m.is_former).length > 0 && (
                <span className="text-gray-300 mx-1">|</span>
              )}
              {members
                .filter((m) => m.is_former)
                .map((member) => (
                  <button
                    key={member.id}
                    onClick={() => {
                      if (bulkEdit.groupType === 'solo') {
                        setBulkEdit((prev) => ({
                          ...prev,
                          members: prev.members.includes(member.id) ? [] : [member.id],
                        }));
                      } else {
                        toggleBulkMember(member.id);
                      }
                    }}
                    className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
                      bulkEdit.members.includes(member.id)
                        ? 'bg-gray-500 text-white border border-gray-500'
                        : 'bg-gray-100 text-gray-400 hover:bg-gray-200 border border-gray-100'
                    }`}
                  >
                    {member.name}
                  </button>
                ))}
            </div>
          </div>
        )}

        {/* 컨셉명 */}
        <div className="mb-4">
          <label className="block text-sm font-medium text-gray-700 mb-1.5">컨셉명</label>
          <input
            type="text"
            value={bulkEdit.conceptName}
            onChange={(e) => setBulkEdit((prev) => ({ ...prev, conceptName: e.target.value }))}
            placeholder="컨셉명 입력"
            className="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </div>

        {/* 적용 버튼 */}
        <button
          onClick={onApply}
          disabled={!bulkEdit.range.trim()}
          className={`w-full py-2.5 rounded-lg font-medium transition-colors flex items-center justify-center gap-2 ${
            bulkEdit.range.trim()
              ? 'bg-primary text-white hover:bg-primary/90'
              : 'bg-gray-100 text-gray-400 cursor-not-allowed'
          }`}
        >
          <Check size={18} />
          일괄 적용
        </button>
      </div>
    </div>
  );
});

export default BulkEditPanel;
