"use client";

import React, { useState, useEffect } from "react";
import {
  XMarkIcon,
  PencilIcon,
  CheckIcon,
  ArrowDownTrayIcon,
  TagIcon,
  DocumentIcon,
} 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;
  tags?: string[];
  description?: string;
  dimensions?: {
    width: number;
    height: number;
  };
  metadata?: Record<string, unknown>;
}

interface MediaPreviewProps {
  file: MediaFile | null;
  isOpen: boolean;
  onClose: () => void;
  onUpdate?: (file: MediaFile) => void;
  onDelete?: (fileId: string) => void;
  className?: string;
}

export function MediaPreview({
  file,
  isOpen,
  onClose,
  onUpdate,
  onDelete,
  className = "",
}: MediaPreviewProps) {
  const [isEditing, setIsEditing] = useState(false);
  const [editData, setEditData] = useState({
    originalName: "",
    description: "",
    tags: [] as string[],
  });
  const [newTag, setNewTag] = useState("");

  useEffect(() => {
    if (file) {
      setEditData({
        originalName: file.originalName,
        description: file.description || "",
        tags: file.tags || [],
      });
    }
  }, [file]);

  if (!isOpen || !file) return null;

  const handleSave = () => {
    if (onUpdate) {
      onUpdate({
        ...file,
        originalName: editData.originalName,
        description: editData.description,
        tags: editData.tags,
      });
    }
    setIsEditing(false);
  };

  const handleCancel = () => {
    setEditData({
      originalName: file.originalName,
      description: file.description || "",
      tags: file.tags || [],
    });
    setIsEditing(false);
  };

  const addTag = () => {
    if (newTag.trim() && !editData.tags.includes(newTag.trim())) {
      setEditData({
        ...editData,
        tags: [...editData.tags, newTag.trim()],
      });
      setNewTag("");
    }
  };

  const removeTag = (tagToRemove: string) => {
    setEditData({
      ...editData,
      tags: editData.tags.filter((tag) => tag !== tagToRemove),
    });
  };

  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: "long",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const getFileTypeIcon = (mimeType: string) => {
    if (mimeType.startsWith("image/")) return "🖼️";
    if (mimeType.startsWith("video/")) return "🎥";
    if (mimeType.startsWith("audio/")) return "🎵";
    if (mimeType.includes("pdf")) return "📄";
    return "📁";
  };

  const renderPreview = () => {
    const mimeType = file.mimeType;

    if (mimeType.startsWith("image/")) {
      return (
        <div className="aspect-video bg-gray-100 rounded-lg flex items-center justify-center">
          <img
            src={file.url}
            alt={file.originalName}
            className="max-w-full max-h-full object-contain rounded-lg"
            onError={(e) => {
              (e.target as HTMLImageElement).src =
                file.thumbnailUrl || "/placeholder-image.png";
            }}
          />
        </div>
      );
    }

    if (mimeType.startsWith("video/")) {
      return (
        <div className="aspect-video bg-gray-100 rounded-lg">
          <video
            src={file.url}
            controls
            className="w-full h-full rounded-lg"
            poster={file.thumbnailUrl}
          >
            브라우저가 비디오를 지원하지 않습니다.
          </video>
        </div>
      );
    }

    if (mimeType.startsWith("audio/")) {
      return (
        <div className="aspect-video bg-gray-100 rounded-lg flex items-center justify-center">
          <div className="text-center">
            <div className="text-6xl mb-4">🎵</div>
            <audio src={file.url} controls className="w-full max-w-md">
              브라우저가 오디오를 지원하지 않습니다.
            </audio>
          </div>
        </div>
      );
    }

    if (mimeType.includes("pdf")) {
      return (
        <div className="aspect-video bg-gray-100 rounded-lg flex items-center justify-center">
          <div className="text-center">
            <DocumentIcon className="h-16 w-16 text-gray-400 mx-auto mb-4" />
            <p className="text-sm text-gray-600">PDF 미리보기</p>
            <a
              href={file.url}
              target="_blank"
              rel="noopener noreferrer"
              className="text-blue-600 hover:text-blue-800 text-sm underline"
            >
              새 창에서 열기
            </a>
          </div>
        </div>
      );
    }

    return (
      <div className="aspect-video bg-gray-100 rounded-lg flex items-center justify-center">
        <div className="text-center">
          <div className="text-6xl mb-4">{getFileTypeIcon(mimeType)}</div>
          <p className="text-sm text-gray-600">미리보기를 사용할 수 없습니다</p>
        </div>
      </div>
    );
  };

  return (
    <div className={`fixed inset-0 z-50 overflow-y-auto ${className}`}>
      <div className="flex items-center justify-center min-h-screen p-4">
        <div className="fixed inset-0 bg-black opacity-50" onClick={onClose} />

        <div className="relative bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-screen overflow-y-auto">
          {/* 헤더 */}
          <div className="flex items-center justify-between p-6 border-b border-gray-200">
            <div className="flex items-center space-x-3">
              <span className="text-2xl">{getFileTypeIcon(file.mimeType)}</span>
              {isEditing ? (
                <input
                  type="text"
                  value={editData.originalName}
                  onChange={(e) =>
                    setEditData({ ...editData, originalName: e.target.value })
                  }
                  className="text-lg font-semibold border border-gray-300 rounded px-2 py-1 focus:ring-2 focus:ring-blue-500"
                />
              ) : (
                <h2 className="text-lg font-semibold text-gray-900">
                  {file.originalName}
                </h2>
              )}
            </div>

            <div className="flex items-center space-x-2">
              {isEditing ? (
                <>
                  <button
                    onClick={handleSave}
                    className="p-2 text-green-600 hover:bg-green-50 rounded-md"
                  >
                    <CheckIcon className="h-5 w-5" />
                  </button>
                  <button
                    onClick={handleCancel}
                    className="p-2 text-gray-400 hover:bg-gray-50 rounded-md"
                  >
                    <XMarkIcon className="h-5 w-5" />
                  </button>
                </>
              ) : (
                <button
                  onClick={() => setIsEditing(true)}
                  className="p-2 text-gray-400 hover:bg-gray-50 rounded-md"
                >
                  <PencilIcon className="h-5 w-5" />
                </button>
              )}

              <button
                onClick={onClose}
                className="p-2 text-gray-400 hover:bg-gray-50 rounded-md"
              >
                <XMarkIcon className="h-5 w-5" />
              </button>
            </div>
          </div>

          <div className="p-6">
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              {/* 미리보기 */}
              <div className="lg:col-span-2">{renderPreview()}</div>

              {/* 메타데이터 */}
              <div className="space-y-6">
                {/* 기본 정보 */}
                <div>
                  <h3 className="text-sm font-medium text-gray-900 mb-3">
                    파일 정보
                  </h3>
                  <div className="space-y-2 text-sm">
                    <div className="flex justify-between">
                      <span className="text-gray-500">크기:</span>
                      <span className="text-gray-900">
                        {formatFileSize(file.size)}
                      </span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-500">형식:</span>
                      <span className="text-gray-900">{file.mimeType}</span>
                    </div>
                    {file.dimensions && (
                      <div className="flex justify-between">
                        <span className="text-gray-500">크기:</span>
                        <span className="text-gray-900">
                          {file.dimensions.width} × {file.dimensions.height}
                        </span>
                      </div>
                    )}
                    <div className="flex justify-between">
                      <span className="text-gray-500">업로드:</span>
                      <span className="text-gray-900 text-right">
                        {formatDate(file.createdAt)}
                      </span>
                    </div>
                    {typeof file.downloadCount !== "undefined" && (
                      <div className="flex justify-between">
                        <span className="text-gray-500">다운로드:</span>
                        <span className="text-gray-900">
                          {file.downloadCount}회
                        </span>
                      </div>
                    )}
                    {typeof file.viewCount !== "undefined" && (
                      <div className="flex justify-between">
                        <span className="text-gray-500">조회:</span>
                        <span className="text-gray-900">
                          {file.viewCount}회
                        </span>
                      </div>
                    )}
                  </div>
                </div>

                {/* 설명 */}
                <div>
                  <h3 className="text-sm font-medium text-gray-900 mb-3">
                    설명
                  </h3>
                  {isEditing ? (
                    <textarea
                      value={editData.description}
                      onChange={(e) =>
                        setEditData({
                          ...editData,
                          description: e.target.value,
                        })
                      }
                      placeholder="파일 설명을 입력하세요..."
                      className="w-full p-2 border border-gray-300 rounded-md text-sm focus:ring-2 focus:ring-blue-500"
                      rows={3}
                    />
                  ) : (
                    <p className="text-sm text-gray-700">
                      {file.description || "설명이 없습니다."}
                    </p>
                  )}
                </div>

                {/* 태그 */}
                <div>
                  <h3 className="text-sm font-medium text-gray-900 mb-3">
                    <TagIcon className="inline h-4 w-4 mr-1" />
                    태그
                  </h3>

                  {isEditing && (
                    <div className="mb-3">
                      <div className="flex space-x-2">
                        <input
                          type="text"
                          value={newTag}
                          onChange={(e) => setNewTag(e.target.value)}
                          onKeyPress={(e) => e.key === "Enter" && addTag()}
                          placeholder="새 태그..."
                          className="flex-1 text-sm border border-gray-300 rounded px-2 py-1 focus:ring-2 focus:ring-blue-500"
                        />
                        <button
                          onClick={addTag}
                          className="px-3 py-1 bg-blue-600 text-white text-sm rounded hover:bg-blue-700"
                        >
                          추가
                        </button>
                      </div>
                    </div>
                  )}

                  <div className="flex flex-wrap gap-2">
                    {editData.tags.map((tag, index) => (
                      <span
                        key={index}
                        className="inline-flex items-center px-2 py-1 rounded-full text-xs bg-blue-100 text-blue-800"
                      >
                        {tag}
                        {isEditing && (
                          <button
                            onClick={() => removeTag(tag)}
                            className="ml-1 text-blue-600 hover:text-blue-800"
                          >
                            <XMarkIcon className="h-3 w-3" />
                          </button>
                        )}
                      </span>
                    ))}
                    {editData.tags.length === 0 && (
                      <span className="text-sm text-gray-500">
                        태그가 없습니다.
                      </span>
                    )}
                  </div>
                </div>

                {/* 액션 버튼 */}
                <div className="pt-4 border-t border-gray-200">
                  <div className="flex space-x-2">
                    <a
                      href={file.url}
                      download={file.originalName}
                      className="flex-1 flex items-center justify-center px-3 py-2 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700"
                    >
                      <ArrowDownTrayIcon className="h-4 w-4 mr-2" />
                      다운로드
                    </a>

                    {onDelete && (
                      <button
                        onClick={() => {
                          if (confirm("이 파일을 삭제하시겠습니까?")) {
                            onDelete(file.id);
                            onClose();
                          }
                        }}
                        className="px-3 py-2 border border-red-300 text-red-700 text-sm rounded-md hover:bg-red-50"
                      >
                        삭제
                      </button>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
