import React, { useMemo } from 'react';
import { useShallow } from 'zustand/react/shallow';
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Clapperboard, Film, Plus } from 'lucide-react';
import { Storyboard } from '@/types';
import { useProjectStore } from '@/lib/store/project';
import { StoryboardRow } from '../components/StoryboardRow';
import { EmptyState } from "@/components/ui/empty-state";
const { AutoSizer } = require("react-virtualized-auto-sizer");
import { List, RowComponentProps } from "react-window";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

interface StoryboardsTabProps {
  selectedEpisodeId: string;
  onEpisodeChange: (episodeId: string) => void;
  setSelectedStoryboard: (sb: Storyboard | null) => void;
  onCreateStoryboard: () => void;
}

export const StoryboardsTab: React.FC<StoryboardsTabProps> = ({
  selectedEpisodeId,
  onEpisodeChange,
  setSelectedStoryboard,
  onCreateStoryboard
}) => {
  const { episodes, storyboards } = useProjectStore(
    useShallow((s) => ({ episodes: s.episodes, storyboards: s.storyboards }))
  );
  const rowHeight = 120;

  // Filtered Storyboards
  const filteredStoryboards = useMemo(() => {
    return storyboards
      .filter(sb => {
        if (selectedEpisodeId === 'all') return true;
        return sb.episodeId === selectedEpisodeId;
      })
      .sort((a, b) => a.order - b.order);
  }, [selectedEpisodeId, storyboards]);

  // Group storyboards by episode for display when "all" is selected
  const storyboardsByEpisode = useMemo(() => {
    return episodes.reduce((acc, episode) => {
      acc[episode.id] = storyboards
        .filter(sb => sb.episodeId === episode.id)
        .sort((a, b) => a.order - b.order);
      return acc;
    }, {} as Record<string, Storyboard[]>);
  }, [episodes, storyboards]);

  const virtualizedItems = useMemo(() => {
    return {
      items: filteredStoryboards,
      onSelect: setSelectedStoryboard
    };
  }, [filteredStoryboards, setSelectedStoryboard]);

  const Row = ({ index, style, items, onSelect }: RowComponentProps<typeof virtualizedItems>) => {
    const sb = items[index];
    if (!sb) return null;

    return (
      <div style={style} className="px-1">
        <StoryboardRow key={sb.id} sb={sb} onClick={() => onSelect(sb)} />
      </div>
    );
  };

  return (
    <div className="animate-in fade-in duration-300">
      {/* Header Controls */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-4">
          <span className="text-sm font-medium text-muted-foreground">按剧集筛选：</span>
          <Select value={selectedEpisodeId} onValueChange={onEpisodeChange}>
            <SelectTrigger className="w-[200px] h-9 rounded-full border-border/50 bg-muted/30">
              <SelectValue placeholder="全部剧集" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部剧集</SelectItem>
              {episodes.map(ep => (
                <SelectItem key={ep.id} value={ep.id}>
                  第 {ep.order} 集: {ep.title}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Badge variant="outline" className="h-7 px-3 rounded-full">
            {selectedEpisodeId === 'all' ? storyboards.length : filteredStoryboards.length} 镜
          </Badge>
        </div>
        <Button size="sm" className="rounded-full gap-2" onClick={onCreateStoryboard}>
          <Plus className="w-4 h-4" />
          创建分镜
        </Button>
      </div>

      {/* Content */}
      {selectedEpisodeId === 'all' ? (
         // Grouped View
         <div className="space-y-10">
            {episodes.map(episode => {
               const epStoryboards = storyboardsByEpisode[episode.id] || [];
               if (epStoryboards.length === 0) return null;
               
               return (
                 <div key={episode.id} className="space-y-4">
                    <div className="flex items-center gap-3 pb-2 border-b">
                      <h3 className="font-semibold text-base">第 {episode.order} 集: {episode.title}</h3>
                      <Badge variant="secondary" className="text-[10px]">{epStoryboards.length} 镜</Badge>
                    </div>
                    <div className="space-y-3">
                      {epStoryboards.map(sb => (
                        <StoryboardRow key={sb.id} sb={sb} onClick={() => setSelectedStoryboard(sb)} />
                      ))}
                    </div>
                 </div>
               )
            })}
            {episodes.length === 0 && (
              <EmptyState 
                icon={Clapperboard}
                title="暂无剧集"
                description="创建剧集后可以添加分镜"
                className="py-20"
              />
            )}
         </div>
      ) : (
         // Flat View for single episode
         <>
            {filteredStoryboards.length > 200 ? (
              <div className="h-[60vh]">
                <AutoSizer>
                  {({ height, width }: { height: number; width: number }) => {
                    if (height === undefined || width === undefined) return null;

                    return (
                      <List
                        rowComponent={Row}
                        rowCount={virtualizedItems.items.length}
                        rowHeight={rowHeight}
                        rowProps={virtualizedItems}
                        style={{ height, width }}
                      />
                    );
                  }}
                </AutoSizer>
              </div>
            ) : (
              <div className="space-y-3">
                {filteredStoryboards.map(sb => (
                  <StoryboardRow key={sb.id} sb={sb} onClick={() => setSelectedStoryboard(sb)} />
                ))}
              </div>
            )}
            {filteredStoryboards.length === 0 && (
              <EmptyState 
                icon={Film}
                title="该剧集暂无分镜"
                description="点击创建分镜按钮添加第一个分镜"
                className="py-20"
              />
            )}
         </>
      )}
    </div>
  );
};
