/**
 * 업로드 대기 파일 아이템 컴포넌트
 */
import { memo } from 'react';
import { Reorder } from 'framer-motion';
import { GripVertical, Trash2, Users, User, Users2 } from 'lucide-react';

/**
 * @param {Object} props
 * @param {Object} props.file - 파일 데이터
 * @param {number} props.index - 인덱스
 * @param {number} props.startNumber - 시작 번호
 * @param {string} props.photoType - 사진 타입 (concept/teaser)
 * @param {Array} props.members - 멤버 목록
 * @param {Function} props.onPreview - 미리보기 핸들러
 * @param {Function} props.onDelete - 삭제 핸들러
 * @param {Function} props.onUpdateFile - 파일 업데이트 핸들러
 * @param {Function} props.onToggleMember - 멤버 토글 핸들러
 * @param {Function} props.onChangeGroupType - 그룹 타입 변경 핸들러
 * @param {Function} props.onMoveToPosition - 위치 이동 핸들러
 * @param {Array} props.pendingFiles - 전체 대기 파일 목록 (위치 계산용)
 */
const PendingFileItem = memo(function PendingFileItem({
  file,
  index,
  startNumber,
  photoType,
  members,
  onPreview,
  onDelete,
  onUpdateFile,
  onToggleMember,
  onChangeGroupType,
  onMoveToPosition,
  pendingFiles,
}) {
  const groupTypes = [
    { value: 'group', icon: Users, label: '단체' },
    { value: 'solo', icon: User, label: '개인' },
    { value: 'unit', icon: Users2, label: '유닛' },
  ];

  return (
    <Reorder.Item
      value={file}
      className="bg-gray-50 rounded-xl p-4 cursor-grab active:cursor-grabbing"
    >
      <div className="flex gap-4 items-center">
        {/* 드래그 핸들 + 순서 번호 */}
        <div className="flex items-center gap-2">
          <GripVertical size={18} className="text-gray-300" />
          <input
            type="text"
            inputMode="numeric"
            defaultValue={String(startNumber + index).padStart(2, '0')}
            key={`order-${file.id}-${index}-${startNumber}`}
            onBlur={(e) => {
              const val = e.target.value.trim();
              const scrollY = window.scrollY;
              const currentIndex = pendingFiles.findIndex((f) => f.id === file.id);
              const currentOrder = startNumber + currentIndex;

              if (val && !isNaN(val) && parseInt(val) !== currentOrder) {
                onMoveToPosition(file.id, val);
              }

              const newIndex = pendingFiles.findIndex((f) => f.id === file.id);
              e.target.value = String(startNumber + newIndex).padStart(2, '0');

              requestAnimationFrame(() => {
                window.scrollTo(0, scrollY);
              });
            }}
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                e.target.blur();
              }
            }}
            className="w-10 h-8 bg-primary/10 text-primary rounded-lg text-center text-sm font-bold border-0 focus:outline-none focus:ring-2 focus:ring-primary [appearance:textfield]"
          />
        </div>

        {/* 썸네일 */}
        {file.isVideo ? (
          <div className="relative w-[180px] h-[180px] flex-shrink-0">
            <video
              src={file.preview}
              className="w-full h-full rounded-lg object-cover cursor-pointer hover:opacity-80 transition-opacity select-none"
              onClick={() => onPreview(file)}
              muted
            />
            <div
              className="absolute inset-0 flex items-center justify-center bg-black/30 rounded-lg cursor-pointer"
              onClick={() => onPreview(file)}
            >
              <div className="w-12 h-12 bg-white/90 rounded-full flex items-center justify-center">
                <div className="w-0 h-0 border-l-[14px] border-l-gray-800 border-y-[8px] border-y-transparent ml-1" />
              </div>
            </div>
          </div>
        ) : (
          <img
            src={file.preview}
            alt={file.filename}
            draggable="false"
            loading="lazy"
            className="w-[180px] h-[180px] rounded-lg object-cover cursor-pointer hover:opacity-80 transition-opacity flex-shrink-0 select-none"
            onClick={() => onPreview(file)}
          />
        )}

        {/* 메타 정보 */}
        <div className="flex-1 space-y-3 h-[200px] overflow-hidden">
          <p className="text-base font-medium text-gray-900 truncate">{file.filename}</p>

          {photoType === 'concept' && (
            <>
              {/* 단체/솔로/유닛 선택 */}
              <div className="flex items-center gap-2">
                <span className="text-sm text-gray-500 w-16">타입:</span>
                <div className="flex gap-1.5">
                  {groupTypes.map(({ value, icon: Icon, label }) => (
                    <button
                      key={value}
                      onClick={() => onChangeGroupType(file.id, value)}
                      className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm transition-colors ${
                        file.groupType === value
                          ? 'bg-primary text-white'
                          : 'bg-white text-gray-600 hover:bg-gray-100 border border-gray-200'
                      }`}
                    >
                      <Icon size={14} />
                      {label}
                    </button>
                  ))}
                </div>
              </div>

              {/* 멤버 태깅 */}
              <div className="flex flex-col gap-2 min-h-8">
                <div className="flex items-center gap-2 flex-wrap">
                  <span className="text-sm text-gray-500 w-16">멤버:</span>
                  {file.groupType === 'group' ? (
                    <span className="text-sm text-gray-400">단체 사진은 멤버 태깅이 필요 없습니다</span>
                  ) : (
                    <>
                      {members
                        .filter((m) => !m.is_former)
                        .map((member) => (
                          <button
                            key={member.id}
                            onClick={() => onToggleMember(file.id, member.id)}
                            className={`px-3 py-1 rounded-full text-sm transition-colors ${
                              file.members.includes(member.id)
                                ? 'bg-primary text-white border border-primary'
                                : 'bg-white text-gray-600 hover:bg-gray-100 border border-gray-200'
                            }`}
                          >
                            {member.name}
                          </button>
                        ))}
                    </>
                  )}
                </div>
                {file.groupType !== 'group' && members.filter((m) => m.is_former).length > 0 && (
                  <div className="flex items-center gap-2 flex-wrap">
                    <span className="text-sm text-gray-400 w-16"></span>
                    {members
                      .filter((m) => m.is_former)
                      .map((member) => (
                        <button
                          key={member.id}
                          onClick={() => onToggleMember(file.id, member.id)}
                          className={`px-3 py-1 rounded-full text-sm transition-colors ${
                            file.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-200'
                          }`}
                        >
                          {member.name}
                        </button>
                      ))}
                  </div>
                )}
              </div>

              {/* 컨셉명 */}
              <div className="flex items-center gap-2">
                <span className="text-sm text-gray-500 w-16">컨셉명:</span>
                <input
                  type="text"
                  value={file.conceptName}
                  onChange={(e) => onUpdateFile(file.id, 'conceptName', e.target.value)}
                  className="flex-1 px-3 py-1.5 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-1 focus:ring-primary"
                  placeholder="컨셉명을 입력하세요"
                />
              </div>
            </>
          )}
        </div>

        {/* 삭제 버튼 */}
        <button
          onClick={() => onDelete(file.id)}
          className="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors self-start"
        >
          <Trash2 size={18} />
        </button>
      </div>
    </Reorder.Item>
  );
});

export default PendingFileItem;
