import { useCallback, useMemo, useRef, useState } from "react";
import { RefreshCw, Trash2, Search, ChevronDown, Check } from "lucide-react";
import { SelectPopover } from "@/shared/ui/SelectPopover";

interface GeneratedVideo {
  id: string;
  name: string;
  path: string;
  size_mb: number;
  created_at: number;
}

interface HistoryListProps {
  generatedVideos: GeneratedVideo[];
  selectedVideoId: string | null;
  onSelectVideo: (video: GeneratedVideo) => void;
  onDeleteVideo: (id: string) => void;
  onRefresh: () => void;
  registerVideoRef: (id: string, element: HTMLDivElement | null) => void;
  formatDate: (timestamp: number) => string;
  embedded?: boolean;
}

export function HistoryList({
  generatedVideos,
  selectedVideoId,
  onSelectVideo,
  onDeleteVideo,
  onRefresh,
  registerVideoRef,
  formatDate,
  embedded = false,
}: HistoryListProps) {
  const [videoFilter, setVideoFilter] = useState("");
  const videoListContainerRef = useRef<HTMLDivElement | null>(null);

  const selectedVideo = generatedVideos.find((v) => v.id === selectedVideoId) || null;
  const filteredVideos = useMemo(() => {
    const query = videoFilter.trim().toLowerCase();
    if (!query) return generatedVideos;
    return generatedVideos.filter((v) => formatDate(v.created_at).toLowerCase().includes(query));
  }, [generatedVideos, videoFilter, formatDate]);

  const handleOpenVideoPopover = useCallback(() => {
    setVideoFilter("");

    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        const container = videoListContainerRef.current;
        if (!container) return;
        const selectedRow = container.querySelector<HTMLElement>("[data-video-selected='true']");
        selectedRow?.scrollIntoView({ block: "nearest", behavior: "auto" });
      });
    });
  }, []);

  const content = (
    <>
      {!embedded && (
        <div className="flex justify-between items-center mb-4">
          <h2 className="text-lg font-semibold text-white flex items-center gap-2">历史作品</h2>
          <button
            onClick={onRefresh}
            className="px-3 py-1 text-xs bg-white/10 hover:bg-white/20 rounded text-gray-300 flex items-center gap-1"
          >
            <RefreshCw className="h-3.5 w-3.5" />
            刷新
          </button>
        </div>
      )}
      {generatedVideos.length === 0 ? (
        <div className="text-center py-4 text-gray-500">
          <p>暂无生成的作品</p>
        </div>
      ) : (
        <SelectPopover
          sheetTitle="选择作品"
          onOpen={handleOpenVideoPopover}
          trigger={({ open, toggle }) => (
            <button
              type="button"
              onClick={toggle}
              className="w-full rounded-xl border border-white/10 bg-black/25 px-3 py-2.5 text-left transition-colors hover:border-white/30"
            >
              <span className="flex items-center justify-between gap-3">
                <span className="min-w-0">
                  <span className="block text-xs text-gray-400">当前作品</span>
                  <span className="mt-0.5 block truncate text-sm text-white">
                    {selectedVideo ? formatDate(selectedVideo.created_at) : "请选择作品"}
                  </span>
                </span>
                <ChevronDown className={`h-4 w-4 text-gray-300 transition-transform ${open ? "rotate-180" : ""}`} />
              </span>
            </button>
          )}
        >
          {({ close }) => (
            <div className="space-y-2">
              <div className="rounded-lg border border-white/10 bg-black/30 px-3 py-2">
                <div className="flex items-center gap-2">
                  <Search className="h-4 w-4 text-gray-400" />
                  <input
                    type="text"
                    value={videoFilter}
                    onChange={(e) => setVideoFilter(e.target.value)}
                    placeholder="搜索作品..."
                    className="w-full bg-transparent text-sm text-white placeholder-gray-500 outline-none"
                  />
                </div>
              </div>

              {filteredVideos.length === 0 ? (
                <div className="py-6 text-center text-sm text-gray-400">没有匹配的作品</div>
              ) : (
                <div
                  ref={videoListContainerRef}
                  className="space-y-1"
                  style={{ contentVisibility: "auto" }}
                >
                  {filteredVideos.map((v) => {
                    const isSelected = selectedVideoId === v.id;

                    return (
                      <div
                        key={v.id}
                        ref={(el) => registerVideoRef(v.id, el)}
                        data-popover-selected={isSelected ? "true" : undefined}
                        data-video-selected={isSelected ? "true" : "false"}
                        className={`flex items-center justify-between gap-2 rounded-lg border px-3 py-2 transition-colors ${isSelected
                          ? "border-purple-500 bg-purple-500/20"
                          : "border-white/10 bg-white/5 hover:border-white/30"
                          }`}
                      >
                        <button
                          type="button"
                          onClick={() => {
                            onSelectVideo(v);
                            close();
                          }}
                          className="min-w-0 flex-1 text-left"
                        >
                          <span className="block truncate text-sm text-white">{formatDate(v.created_at)}</span>
                          <span className="mt-0.5 block text-xs text-gray-400">{v.size_mb.toFixed(1)} MB</span>
                        </button>

                        <div className="flex items-center gap-2 pl-2">
                          <button
                            type="button"
                            onClick={(e) => {
                              e.stopPropagation();
                              onDeleteVideo(v.id);
                            }}
                            className="p-1 text-gray-400 hover:text-red-400"
                            title="删除视频"
                          >
                            <Trash2 className="h-4 w-4" />
                          </button>
                          {isSelected && <Check className="h-4 w-4 text-purple-300" />}
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          )}
        </SelectPopover>
      )}
    </>
  );

  if (embedded) return content;

  return (
    <div className="bg-white/5 rounded-2xl p-6 border border-white/10 backdrop-blur-sm">
      {content}
    </div>
  );
}
