"use client";

import React, { useState, useCallback, useEffect } from "react";
import { Button } from "@/components/ui/Button";
import { Input } from "@/components/ui/Input";
import { Card } from "@/components/ui/Card";
import { Modal } from "@/components/ui/Modal";

interface MediaFile {
  id: string;
  fileName: string;
  originalName: string;
  mimeType: string;
  size: number;
  url: string;
  cdnUrl?: string;
  thumbnailUrl?: string;
  createdAt: string;
  tags: string[];
  description?: string;
  dimensions?: {
    width: number;
    height: number;
  };
}

interface MediaPickerProps {
  isOpen: boolean;
  onClose: () => void;
  onSelect: (media: MediaFile | MediaFile[]) => void;
  multiSelect?: boolean;
  acceptedTypes?: string[];
  maxFiles?: number;
  className?: string;
}

export function MediaPicker({
  isOpen,
  onClose,
  onSelect,
  multiSelect = false,
  acceptedTypes = ["image/*", "video/*"],
  maxFiles = 1,
  className,
}: MediaPickerProps) {
  const [activeTab, setActiveTab] = useState("library");
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedFiles, setSelectedFiles] = useState<MediaFile[]>([]);
  const [mediaFiles, setMediaFiles] = useState<MediaFile[]>([]);
  const [loading, setLoading] = useState(false);

  // 미디어 파일 불러오기
  const fetchMediaFiles = useCallback(async () => {
    setLoading(true);
    try {
      const response = await fetch("/api/media/upload", {
        method: "GET",
      });

      if (response.ok) {
        const data = await response.json();
        setMediaFiles(data.files || []);
      }
    } catch (error) {
      console.error("Failed to fetch media files:", error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (isOpen) {
      fetchMediaFiles();
    }
  }, [isOpen, fetchMediaFiles]);

  // 파일 필터링
  const filteredFiles = mediaFiles.filter((file) => {
    const matchesSearch = file.originalName
      .toLowerCase()
      .includes(searchTerm.toLowerCase());

    return matchesSearch;
  });

  // 파일 선택 처리
  const handleFileSelect = useCallback(
    (file: MediaFile) => {
      if (multiSelect) {
        setSelectedFiles((prev) => {
          const isSelected = prev.some((f) => f.id === file.id);
          if (isSelected) {
            return prev.filter((f) => f.id !== file.id);
          } else if (prev.length < maxFiles) {
            return [...prev, file];
          }
          return prev;
        });
      } else {
        setSelectedFiles([file]);
      }
    },
    [multiSelect, maxFiles]
  );

  // 선택 확인
  const handleConfirmSelection = () => {
    if (selectedFiles.length > 0) {
      onSelect(multiSelect ? selectedFiles : selectedFiles[0]);
      setSelectedFiles([]);
      onClose();
    }
  };

  return (
    <Modal open={isOpen} onClose={onClose} size="xl" className={className}>
      <div className="p-6 max-h-[80vh] flex flex-col">
        <h2 className="text-xl font-semibold mb-4">미디어 선택</h2>

        {/* 탭 버튼 */}
        <div className="flex mb-4 border-b">
          <button
            className={`px-4 py-2 border-b-2 transition-colors ${
              activeTab === "library"
                ? "border-blue-500 text-blue-600"
                : "border-transparent text-gray-600 hover:text-gray-800"
            }`}
            onClick={() => setActiveTab("library")}
          >
            미디어 라이브러리
          </button>
          <button
            className={`px-4 py-2 border-b-2 transition-colors ${
              activeTab === "upload"
                ? "border-blue-500 text-blue-600"
                : "border-transparent text-gray-600 hover:text-gray-800"
            }`}
            onClick={() => setActiveTab("upload")}
          >
            새 파일 업로드
          </button>
        </div>

        {activeTab === "library" && (
          <div className="flex-1 flex flex-col space-y-4">
            {/* 검색 */}
            <div className="flex items-center gap-4">
              <div className="relative flex-1">
                <Input
                  placeholder="파일명으로 검색..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>
            </div>

            {/* 미디어 파일 그리드 */}
            <div className="flex-1 overflow-auto">
              {loading ? (
                <div className="text-center py-8">로딩 중...</div>
              ) : (
                <div className="grid gap-4 grid-cols-6">
                  {filteredFiles.map((file) => {
                    const isSelected = selectedFiles.some(
                      (f) => f.id === file.id
                    );

                    return (
                      <Card
                        key={file.id}
                        className={`cursor-pointer transition-all aspect-square ${
                          isSelected
                            ? "ring-2 ring-blue-500 bg-blue-50"
                            : "hover:shadow-md"
                        }`}
                        onClick={() => handleFileSelect(file)}
                      >
                        <div className="relative h-full">
                          {file.mimeType.startsWith("image/") ? (
                            <img
                              src={file.thumbnailUrl || file.url}
                              alt={file.originalName}
                              className="w-full h-full object-cover rounded"
                            />
                          ) : (
                            <div className="w-full h-full flex items-center justify-center bg-gray-100 rounded">
                              <span className="text-xs text-gray-500">
                                파일
                              </span>
                            </div>
                          )}

                          <div className="absolute bottom-0 left-0 right-0 p-2 bg-black bg-opacity-50 text-white text-xs rounded-b">
                            <div className="truncate" title={file.originalName}>
                              {file.originalName}
                            </div>
                          </div>
                        </div>
                      </Card>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
        )}

        {activeTab === "upload" && (
          <div className="flex-1 flex flex-col">
            <div className="flex-1 border-2 border-dashed border-gray-300 rounded-lg flex flex-col items-center justify-center gap-4">
              <div className="text-center">
                <p className="text-lg font-medium">파일을 드래그하여 업로드</p>
                <p className="text-gray-500">또는 클릭하여 파일 선택</p>
              </div>

              <input
                type="file"
                multiple={multiSelect}
                accept={acceptedTypes.join(",")}
                className="hidden"
                id="file-upload"
              />
              <label htmlFor="file-upload">
                <Button>파일 선택</Button>
              </label>
            </div>
          </div>
        )}

        {/* 하단 버튼 */}
        <div className="flex items-center justify-between pt-4 border-t mt-4">
          <div className="text-sm text-gray-500">
            {selectedFiles.length > 0 &&
              `${selectedFiles.length}개 파일 선택됨`}
          </div>

          <div className="flex gap-2">
            <Button variant="outline" onClick={onClose}>
              취소
            </Button>
            <Button
              onClick={handleConfirmSelection}
              disabled={selectedFiles.length === 0}
            >
              선택 완료
            </Button>
          </div>
        </div>
      </div>
    </Modal>
  );
}
