"use client";

import React, { useState } from "react";
import {
  FunnelIcon,
  XMarkIcon,
  CalendarIcon,
  TagIcon,
  DocumentIcon,
  PhotoIcon,
  VideoCameraIcon,
  MusicalNoteIcon,
} from "@heroicons/react/24/outline";

export interface MediaFilterOptions {
  fileTypes: string[];
  dateRange: {
    start?: string;
    end?: string;
  };
  sizeRange: {
    min?: number;
    max?: number;
  };
  tags: string[];
  searchTerm: string;
}

export interface MediaFilterProps {
  filters: MediaFilterOptions;
  onFilterChange: (filters: MediaFilterOptions) => void;
  availableTags: string[];
  className?: string;
}

const FILE_TYPE_OPTIONS = [
  {
    value: "image",
    label: "이미지",
    icon: PhotoIcon,
    types: ["image/jpeg", "image/png", "image/gif", "image/webp"],
  },
  {
    value: "video",
    label: "동영상",
    icon: VideoCameraIcon,
    types: ["video/mp4", "video/webm", "video/avi"],
  },
  {
    value: "audio",
    label: "오디오",
    icon: MusicalNoteIcon,
    types: ["audio/mp3", "audio/wav", "audio/ogg"],
  },
  {
    value: "document",
    label: "문서",
    icon: DocumentIcon,
    types: ["application/pdf", "application/msword", "text/plain"],
  },
];

const SIZE_OPTIONS = [
  { label: "모든 크기", min: 0, max: Infinity },
  { label: "1MB 미만", min: 0, max: 1024 * 1024 },
  { label: "1MB - 10MB", min: 1024 * 1024, max: 10 * 1024 * 1024 },
  { label: "10MB - 100MB", min: 10 * 1024 * 1024, max: 100 * 1024 * 1024 },
  { label: "100MB 이상", min: 100 * 1024 * 1024, max: Infinity },
];

export function MediaFilter({
  filters,
  onFilterChange,
  availableTags,
  className = "",
}: MediaFilterProps) {
  const [isOpen, setIsOpen] = useState(false);

  const updateFilter = <K extends keyof MediaFilterOptions>(
    key: K,
    value: MediaFilterOptions[K]
  ) => {
    onFilterChange({
      ...filters,
      [key]: value,
    });
  };

  const toggleFileType = (typeOption: (typeof FILE_TYPE_OPTIONS)[0]) => {
    const newTypes = filters.fileTypes.includes(typeOption.value)
      ? filters.fileTypes.filter((t) => t !== typeOption.value)
      : [...filters.fileTypes, typeOption.value];
    updateFilter("fileTypes", newTypes);
  };

  const toggleTag = (tag: string) => {
    const newTags = filters.tags.includes(tag)
      ? filters.tags.filter((t) => t !== tag)
      : [...filters.tags, tag];
    updateFilter("tags", newTags);
  };

  const clearFilters = () => {
    onFilterChange({
      fileTypes: [],
      dateRange: {},
      sizeRange: {},
      tags: [],
      searchTerm: "",
    });
  };

  const activeFiltersCount =
    filters.fileTypes.length +
    filters.tags.length +
    (filters.dateRange.start || filters.dateRange.end ? 1 : 0) +
    (filters.sizeRange.min !== undefined || filters.sizeRange.max !== undefined
      ? 1
      : 0);

  return (
    <div className={`relative ${className}`}>
      {/* 필터 버튼 */}
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="relative p-2 border border-gray-300 rounded-md hover:bg-gray-50 focus:ring-2 focus:ring-blue-500"
      >
        <FunnelIcon className="h-4 w-4 text-gray-500" />
        {activeFiltersCount > 0 && (
          <span className="absolute -top-1 -right-1 bg-blue-600 text-white text-xs rounded-full h-5 w-5 flex items-center justify-center">
            {activeFiltersCount}
          </span>
        )}
      </button>

      {/* 필터 패널 */}
      {isOpen && (
        <div className="absolute top-full left-0 z-50 mt-2 w-80 bg-white border border-gray-200 rounded-lg shadow-lg">
          <div className="p-4">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-sm font-medium text-gray-900">필터</h3>
              <div className="flex space-x-2">
                <button
                  onClick={clearFilters}
                  className="text-xs text-gray-500 hover:text-gray-700"
                >
                  초기화
                </button>
                <button
                  onClick={() => setIsOpen(false)}
                  className="text-gray-400 hover:text-gray-600"
                >
                  <XMarkIcon className="h-4 w-4" />
                </button>
              </div>
            </div>

            <div className="space-y-4">
              {/* 파일 형식 필터 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  파일 형식
                </label>
                <div className="space-y-2">
                  {FILE_TYPE_OPTIONS.map((option) => {
                    const IconComponent = option.icon;
                    return (
                      <label key={option.value} className="flex items-center">
                        <input
                          type="checkbox"
                          checked={filters.fileTypes.includes(option.value)}
                          onChange={() => toggleFileType(option)}
                          className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                        />
                        <IconComponent className="ml-2 h-4 w-4 text-gray-400" />
                        <span className="ml-2 text-sm text-gray-700">
                          {option.label}
                        </span>
                      </label>
                    );
                  })}
                </div>
              </div>

              {/* 날짜 범위 필터 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  <CalendarIcon className="inline h-4 w-4 mr-1" />
                  업로드 날짜
                </label>
                <div className="grid grid-cols-2 gap-2">
                  <input
                    type="date"
                    value={filters.dateRange.start || ""}
                    onChange={(e) =>
                      updateFilter("dateRange", {
                        ...filters.dateRange,
                        start: e.target.value,
                      })
                    }
                    className="text-sm border border-gray-300 rounded px-2 py-1 focus:ring-2 focus:ring-blue-500"
                    placeholder="시작일"
                  />
                  <input
                    type="date"
                    value={filters.dateRange.end || ""}
                    onChange={(e) =>
                      updateFilter("dateRange", {
                        ...filters.dateRange,
                        end: e.target.value,
                      })
                    }
                    className="text-sm border border-gray-300 rounded px-2 py-1 focus:ring-2 focus:ring-blue-500"
                    placeholder="종료일"
                  />
                </div>
              </div>

              {/* 파일 크기 필터 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  파일 크기
                </label>
                <div className="space-y-1">
                  {SIZE_OPTIONS.map((option, index) => (
                    <label key={index} className="flex items-center">
                      <input
                        type="radio"
                        name="sizeRange"
                        checked={
                          filters.sizeRange.min === option.min &&
                          filters.sizeRange.max === option.max
                        }
                        onChange={() =>
                          updateFilter("sizeRange", {
                            min: option.min === 0 ? undefined : option.min,
                            max:
                              option.max === Infinity ? undefined : option.max,
                          })
                        }
                        className="text-blue-600 focus:ring-blue-500"
                      />
                      <span className="ml-2 text-sm text-gray-700">
                        {option.label}
                      </span>
                    </label>
                  ))}
                </div>
              </div>

              {/* 태그 필터 */}
              {availableTags.length > 0 && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    <TagIcon className="inline h-4 w-4 mr-1" />
                    태그
                  </label>
                  <div className="max-h-32 overflow-y-auto space-y-1">
                    {availableTags.map((tag) => (
                      <label key={tag} className="flex items-center">
                        <input
                          type="checkbox"
                          checked={filters.tags.includes(tag)}
                          onChange={() => toggleTag(tag)}
                          className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                        />
                        <span className="ml-2 text-sm text-gray-700">
                          {tag}
                        </span>
                      </label>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
