import type { ChangeEvent } from "react";
import { Upload, RefreshCw, Eye, Trash2, X } from "lucide-react";

interface Material {
  id: string;
  name: string;
  scene: string;
  size_mb: number;
  path: string;
}

interface MaterialSelectorProps {
  materials: Material[];
  selectedMaterial: string;
  isUploading: boolean;
  uploadProgress: number;
  uploadError: string | null;
  fetchError: string | null;
  apiBase: string;
  onUploadChange: (event: ChangeEvent<HTMLInputElement>) => void;
  onRefresh: () => void;
  onSelectMaterial: (id: string) => void;
  onPreviewMaterial: (path: string) => void;
  onDeleteMaterial: (id: string) => void;
  onClearUploadError: () => void;
  registerMaterialRef: (id: string, element: HTMLDivElement | null) => void;
}

export function MaterialSelector({
  materials,
  selectedMaterial,
  isUploading,
  uploadProgress,
  uploadError,
  fetchError,
  apiBase,
  onUploadChange,
  onRefresh,
  onSelectMaterial,
  onPreviewMaterial,
  onDeleteMaterial,
  onClearUploadError,
  registerMaterialRef,
}: MaterialSelectorProps) {
  return (
    <div className="bg-white/5 rounded-2xl p-4 sm:p-6 border border-white/10 backdrop-blur-sm">
      <div className="flex justify-between items-center gap-2 mb-4">
        <h2 className="text-base sm:text-lg font-semibold text-white flex items-center gap-2 whitespace-nowrap">
          📹 选择素材视频
          <span className="ml-1 text-[11px] sm:text-xs text-gray-400/90 font-normal">
            (上传自拍视频)
          </span>
        </h2>
        <div className="flex gap-1.5">
          <input
            type="file"
            id="video-upload"
            accept=".mp4,.mov,.avi"
            onChange={onUploadChange}
            className="hidden"
          />
          <label
            htmlFor="video-upload"
            className={`px-2 py-1 text-xs rounded cursor-pointer transition-all whitespace-nowrap flex items-center gap-1 ${isUploading
              ? "bg-gray-600 cursor-not-allowed text-gray-400"
              : "bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white"
              }`}
          >
            <Upload className="h-3.5 w-3.5" />
            上传
          </label>
          <button
            onClick={onRefresh}
            className="px-2 py-1 text-xs bg-white/10 hover:bg-white/20 rounded text-gray-300 whitespace-nowrap flex items-center gap-1"
          >
            <RefreshCw className="h-3.5 w-3.5" />
            刷新
          </button>
        </div>
      </div>

      {isUploading && (
        <div className="mb-4 p-4 bg-purple-500/10 rounded-xl border border-purple-500/30">
          <div className="flex justify-between text-sm text-purple-300 mb-2">
            <span>📤 上传中...</span>
            <span>{uploadProgress}%</span>
          </div>
          <div className="h-2 bg-black/30 rounded-full overflow-hidden">
            <div
              className="h-full bg-gradient-to-r from-purple-500 to-pink-500 transition-all duration-300"
              style={{ width: `${uploadProgress}%` }}
            />
          </div>
        </div>
      )}

      {uploadError && (
        <div className="mb-4 p-4 bg-red-500/20 text-red-200 rounded-xl text-sm flex justify-between items-center">
          <span>❌ {uploadError}</span>
          <button onClick={onClearUploadError} className="text-red-300 hover:text-white">
            <X className="h-3.5 w-3.5" />
          </button>
        </div>
      )}

      {fetchError ? (
        <div className="p-4 bg-red-500/20 text-red-200 rounded-xl text-sm mb-4">
          获取素材失败: {fetchError}
          <br />
          API: {apiBase}/api/materials/
        </div>
      ) : materials.length === 0 ? (
        <div className="text-center py-8 text-gray-400">
          <div className="text-5xl mb-4">📁</div>
          <p>暂无素材视频</p>
          <p className="text-sm mt-2">
            点击上方「📤 上传视频」按钮添加素材
          </p>
        </div>
      ) : (
        <div
          className="space-y-2 max-h-64 overflow-y-auto hide-scrollbar"
          style={{ contentVisibility: 'auto' }}
        >
          {materials.map((m) => (
            <div
              key={m.id}
              ref={(el) => registerMaterialRef(m.id, el)}
              className={`p-3 rounded-lg border transition-all flex items-center justify-between group ${selectedMaterial === m.id
                ? "border-purple-500 bg-purple-500/20"
                : "border-white/10 bg-white/5 hover:border-white/30"
                }`}
            >
              <button onClick={() => onSelectMaterial(m.id)} className="flex-1 text-left">
                <div className="text-white text-sm truncate">{m.scene || m.name}</div>
                <div className="text-gray-400 text-xs">{m.size_mb.toFixed(1)} MB</div>
              </button>
              <div className="flex items-center gap-2 pl-2">
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    if (m.path) {
                      onPreviewMaterial(m.path);
                    }
                  }}
                  className="p-1 text-gray-500 hover:text-white opacity-0 group-hover:opacity-100 transition-opacity"
                  title="预览视频"
                >
                  <Eye className="h-4 w-4" />
                </button>
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    onDeleteMaterial(m.id);
                  }}
                  className="p-1 text-gray-500 hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity"
                  title="删除素材"
                >
                  <Trash2 className="h-4 w-4" />
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
