"use client";

import React from "react";
import {
  PhotoIcon,
  VideoCameraIcon,
  DocumentIcon,
  TrashIcon,
  EyeIcon,
  ArrowDownTrayIcon,
} from "@heroicons/react/24/outline";

interface MediaFile {
  id: string;
  fileName: string;
  originalName: string;
  mimeType: string;
  size: number;
  url: string;
  thumbnailUrl?: string;
  createdAt: string;
  downloadCount?: number;
  viewCount?: number;
}

interface MediaGridProps {
  files: MediaFile[];
  onFileSelect?: (file: MediaFile) => void;
  onFileDelete?: (fileId: string) => void;
  onFileDownload?: (file: MediaFile) => void;
  selectedFiles?: string[];
  className?: string;
}

export function MediaGrid({
  files,
  onFileSelect,
  onFileDelete,
  onFileDownload,
  selectedFiles = [],
  className = "",
}: MediaGridProps) {
  const getFileIcon = (mimeType: string) => {
    if (mimeType.startsWith("image/")) {
      return <PhotoIcon className="h-8 w-8 text-blue-500" />;
    }
    if (mimeType.startsWith("video/")) {
      return <VideoCameraIcon className="h-8 w-8 text-purple-500" />;
    }
    return <DocumentIcon className="h-8 w-8 text-gray-500" />;
  };

  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return "0 Bytes";
    const k = 1024;
    const sizes = ["Bytes", "KB", "MB", "GB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
  };

  const formatDate = (dateString: string): string => {
    return new Date(dateString).toLocaleDateString("ko-KR", {
      year: "numeric",
      month: "short",
      day: "numeric",
    });
  };

  if (files.length === 0) {
    return (
      <div className={`text-center py-12 ${className}`}>
        <PhotoIcon className="mx-auto h-12 w-12 text-gray-400" />
        <h3 className="mt-2 text-sm font-medium text-gray-900">
          업로드된 파일이 없습니다
        </h3>
        <p className="mt-1 text-sm text-gray-500">
          파일을 업로드하여 미디어 라이브러리를 시작하세요.
        </p>
      </div>
    );
  }

  return (
    <div
      className={`grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 ${className}`}
    >
      {files.map((file) => {
        const isSelected = selectedFiles.includes(file.id);
        const isImage = file.mimeType.startsWith("image/");

        return (
          <div
            key={file.id}
            className={`
              relative group bg-white border rounded-lg overflow-hidden cursor-pointer transition-all duration-200 hover:shadow-md
              ${
                isSelected
                  ? "ring-2 ring-blue-500 border-blue-500"
                  : "border-gray-200"
              }
            `}
            onClick={() => onFileSelect?.(file)}
          >
            {/* 파일 미리보기 */}
            <div className="aspect-square bg-gray-50 flex items-center justify-center">
              {isImage ? (
                <img
                  src={file.thumbnailUrl || file.url}
                  alt={file.originalName}
                  className="w-full h-full object-cover"
                  onError={(e) => {
                    const target = e.target as HTMLImageElement;
                    target.style.display = "none";
                    target.nextElementSibling?.classList.remove("hidden");
                  }}
                />
              ) : null}
              <div className={`${isImage ? "hidden" : ""}`}>
                {getFileIcon(file.mimeType)}
              </div>
            </div>

            {/* 파일 정보 */}
            <div className="p-3">
              <h4
                className="text-sm font-medium text-gray-900 truncate"
                title={file.originalName}
              >
                {file.originalName}
              </h4>
              <div className="mt-1 text-xs text-gray-500 space-y-1">
                <p>{formatFileSize(file.size)}</p>
                <p>{formatDate(file.createdAt)}</p>
                {(file.downloadCount || file.viewCount) && (
                  <div className="flex items-center space-x-2">
                    {file.viewCount && (
                      <span className="flex items-center">
                        <EyeIcon className="h-3 w-3 mr-1" />
                        {file.viewCount}
                      </span>
                    )}
                    {file.downloadCount && (
                      <span className="flex items-center">
                        <ArrowDownTrayIcon className="h-3 w-3 mr-1" />
                        {file.downloadCount}
                      </span>
                    )}
                  </div>
                )}
              </div>
            </div>

            {/* 호버 오버레이 */}
            <div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-40 transition-all duration-200 flex items-center justify-center opacity-0 group-hover:opacity-100">
              <div className="flex space-x-2">
                {onFileDownload && (
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      onFileDownload(file);
                    }}
                    className="p-2 bg-white text-gray-700 rounded-full hover:bg-gray-100 transition-colors"
                    title="다운로드"
                  >
                    <ArrowDownTrayIcon className="h-4 w-4" />
                  </button>
                )}
                {onFileDelete && (
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      if (confirm("이 파일을 삭제하시겠습니까?")) {
                        onFileDelete(file.id);
                      }
                    }}
                    className="p-2 bg-white text-red-600 rounded-full hover:bg-red-50 transition-colors"
                    title="삭제"
                  >
                    <TrashIcon className="h-4 w-4" />
                  </button>
                )}
              </div>
            </div>

            {/* 선택 표시 */}
            {isSelected && (
              <div className="absolute top-2 right-2 bg-blue-500 text-white rounded-full p-1">
                <svg
                  className="h-3 w-3"
                  fill="currentColor"
                  viewBox="0 0 20 20"
                >
                  <path
                    fillRule="evenodd"
                    d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                    clipRule="evenodd"
                  />
                </svg>
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}
