"use client";

import React from "react";
import {
  ChevronUpDownIcon,
  ChevronUpIcon,
  ChevronDownIcon,
} from "@heroicons/react/24/outline";

export type SortField =
  | "name"
  | "size"
  | "date"
  | "type"
  | "downloads"
  | "views";
export type SortDirection = "asc" | "desc";

export interface SortOptions {
  field: SortField;
  direction: SortDirection;
}

interface MediaSortProps {
  sortOptions: SortOptions;
  onSortChange: (options: SortOptions) => void;
  className?: string;
}

const SORT_OPTIONS: Array<{ field: SortField; label: string }> = [
  { field: "name", label: "이름" },
  { field: "date", label: "업로드 날짜" },
  { field: "size", label: "파일 크기" },
  { field: "type", label: "파일 형식" },
  { field: "downloads", label: "다운로드 수" },
  { field: "views", label: "조회 수" },
];

export function MediaSort({
  sortOptions,
  onSortChange,
  className = "",
}: MediaSortProps) {
  const handleFieldChange = (field: SortField) => {
    // 같은 필드를 선택하면 정렬 방향을 토글
    if (sortOptions.field === field) {
      onSortChange({
        field,
        direction: sortOptions.direction === "asc" ? "desc" : "asc",
      });
    } else {
      // 다른 필드를 선택하면 오름차순으로 시작
      onSortChange({
        field,
        direction: "asc",
      });
    }
  };

  const getSortIcon = (field: SortField) => {
    if (sortOptions.field !== field) {
      return <ChevronUpDownIcon className="h-4 w-4 text-gray-400" />;
    }

    return sortOptions.direction === "asc" ? (
      <ChevronUpIcon className="h-4 w-4 text-blue-600" />
    ) : (
      <ChevronDownIcon className="h-4 w-4 text-blue-600" />
    );
  };

  const getSortLabel = () => {
    const option = SORT_OPTIONS.find((opt) => opt.field === sortOptions.field);
    const direction = sortOptions.direction === "asc" ? "오름차순" : "내림차순";
    return `${option?.label} ${direction}`;
  };

  return (
    <div className={`relative inline-block text-left ${className}`}>
      <div className="flex items-center space-x-1">
        <span className="text-sm text-gray-500">정렬:</span>
        <div className="flex items-center space-x-1 bg-white border border-gray-300 rounded-md">
          {SORT_OPTIONS.map((option) => (
            <button
              key={option.field}
              onClick={() => handleFieldChange(option.field)}
              className={`
                flex items-center space-x-1 px-3 py-1 text-sm rounded-md transition-colors
                ${
                  sortOptions.field === option.field
                    ? "bg-blue-50 text-blue-700 border-blue-200"
                    : "text-gray-700 hover:bg-gray-50"
                }
              `}
            >
              <span>{option.label}</span>
              {getSortIcon(option.field)}
            </button>
          ))}
        </div>
      </div>

      {/* 현재 정렬 상태 표시 */}
      <div className="mt-1">
        <span className="text-xs text-gray-500">
          현재 정렬: {getSortLabel()}
        </span>
      </div>
    </div>
  );
}
