'use client';

import React, { useState, useMemo, useEffect } from 'react';
import { cn } from '@/utils';
import { Clapperboard, Folder, LayoutGrid, Plus, X, ChevronDown, ChevronRight } from 'lucide-react';
import { SidebarCard } from './SidebarCard';
import { GeneralCanvas, Episode } from '@/types';
import { EmptyState } from '@/components/ui/empty-state';

interface RightSidebarPanelProps {
  activeTab: 'storyboard' | 'asset' | 'general' | null;
  onClose: () => void;
  storyboards: any[];
  episodes?: Episode[];
  assets: any[];
  generalCanvases?: GeneralCanvas[];
  activeItemId: string | null;
  onNavigate: (id: string, type: 'storyboard' | 'asset' | 'general') => void;
  onCreateGeneralCanvas?: () => void;
  onContextMenu?: (e: React.MouseEvent, item: any, type: 'storyboard' | 'asset' | 'general') => void;
}

export const RightSidebarPanel = ({
  activeTab,
  onClose,
  storyboards,
  episodes = [],
  assets,
  generalCanvases = [],
  activeItemId,
  onNavigate,
  onCreateGeneralCanvas,
  onContextMenu
}: RightSidebarPanelProps) => {
  const [activeAssetTab, setActiveAssetTab] = useState<'character' | 'scene' | 'prop' | 'other'>('character');
  const [expandedEpisodes, setExpandedEpisodes] = useState<Record<string, boolean>>({});

  // Initialize expanded state for episodes
  useEffect(() => {
    if (episodes.length > 0) {
        setExpandedEpisodes(prev => {
            const next = { ...prev };
            let hasChanges = false;
            episodes.forEach(ep => {
                if (next[ep.id] === undefined) {
                    next[ep.id] = true; // Default to expanded
                    hasChanges = true;
                }
            });
            return hasChanges ? next : prev;
        });
    }
  }, [episodes]);

  // Filter valid assets based on active tab
  const visualAssets = useMemo(() => {
      return assets.filter(a => a.type === activeAssetTab);
  }, [assets, activeAssetTab]);

  // Group storyboards by episode
  const groupedStoryboards = useMemo(() => {
      if (!storyboards) return { groups: {}, uncategorized: [] };
      
      const groups: Record<string, any[]> = {};
      const uncategorized: any[] = [];

      storyboards.forEach(item => {
          if (item.episodeId) {
              if (!groups[item.episodeId]) groups[item.episodeId] = [];
              groups[item.episodeId].push(item);
          } else {
              uncategorized.push(item);
          }
      });

      return { groups, uncategorized };
  }, [storyboards]);

  if (!activeTab) return null;

  const isStoryboard = activeTab === 'storyboard';
  const isGeneral = activeTab === 'general';
  
  let items: any[] = [];
  let title = '';
  
  if (isGeneral) {
      items = generalCanvases;
      title = '通用画布';
  } else if (isStoryboard) {
      items = storyboards; // Still used for empty check
      title = '分镜画布';
  } else {
      items = visualAssets;
      title = '资产画布';
  }

  return (
      <>
          <div className="p-4 border-b border-white/5 flex flex-col gap-3 bg-white/5">
              <div className="flex justify-between items-center">
                  <button onClick={onClose}><X size={14} className="text-muted-foreground hover:text-white" /></button>
                  <span className="text-xs font-bold uppercase tracking-widest text-foreground/50">
                      {title}
                  </span>
              </div>

              {isGeneral && (
                  <button 
                    onClick={onCreateGeneralCanvas}
                    className="flex items-center justify-center gap-2 w-full py-2 bg-white/5 hover:bg-white/10 text-xs font-medium rounded-lg transition-colors border border-white/5"
                  >
                    <Plus size={14} />
                    新建通用画布
                  </button>
              )}

              {!isStoryboard && !isGeneral && (
                  <div className="flex bg-black/20 p-1 rounded-lg">
                      {[
                          { id: 'character', label: '角色' },
                          { id: 'scene', label: '场景' },
                          { id: 'prop', label: '道具' },
                          { id: 'other', label: '其他' },
                      ].map(tab => (
                          <button
                              key={tab.id}
                              onClick={() => setActiveAssetTab(tab.id as any)}
                              className={cn(
                                  "flex-1 py-1 text-[10px] font-bold rounded-md transition-all",
                                  activeAssetTab === tab.id 
                                      ? "bg-white/10 text-foreground shadow-sm" 
                                      : "text-muted-foreground hover:text-muted-foreground hover:bg-white/5"
                              )}
                          >
                              {tab.label}
                          </button>
                      ))}
                  </div>
              )}
          </div>
          <div className="flex-1 overflow-y-auto p-2 custom-scrollbar space-y-2">
              {items.length === 0 ? (
                  <EmptyState 
                    icon={isStoryboard ? Clapperboard : isGeneral ? LayoutGrid : Folder}
                    title={`暂无${title}`}
                    className="py-10"
                  />
              ) : isStoryboard ? (
                  <div className="space-y-4">
                      {episodes.map(ep => {
                          const epItems = groupedStoryboards.groups[ep.id];
                          if (!epItems || epItems.length === 0) return null;
                          const isExpanded = expandedEpisodes[ep.id] ?? true;

                          return (
                              <div key={ep.id} className="space-y-1">
                                  <button 
                                      onClick={() => setExpandedEpisodes(prev => ({ ...prev, [ep.id]: !isExpanded }))}
                                      className="flex items-center gap-2 w-full text-left px-1 py-1 text-xs font-medium text-muted-foreground hover:text-white transition-colors"
                                  >
                                      {isExpanded ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
                                      <span>{ep.title || `Episode ${ep.order}`}</span>
                                      <span className="text-[10px] opacity-50 ml-auto">{epItems.length}</span>
                                  </button>
                                  
                                  {isExpanded && (
                                      <div className="grid grid-cols-2 gap-2 animate-in slide-in-from-top-2 duration-200">
                                          {epItems.map(item => (
                                              <SidebarCard
                                                  key={item.id}
                                                  item={item}
                                                  type="storyboard"
                                                  activeItemId={activeItemId}
                                                  onNavigate={onNavigate as any}
                                                  onContextMenu={onContextMenu}
                                              />
                                          ))}
                                      </div>
                                  )}
                              </div>
                          );
                      })}

                      {/* Uncategorized Items */}
                      {groupedStoryboards.uncategorized.length > 0 && (
                          <div className="space-y-1">
                              {episodes.length > 0 && (
                                  <div className="px-1 py-1 text-xs font-medium text-muted-foreground opacity-50">
                                      未分类
                                  </div>
                              )}
                              <div className="grid grid-cols-2 gap-2">
                                  {groupedStoryboards.uncategorized.map(item => (
                                      <SidebarCard
                                          key={item.id}
                                          item={item}
                                          type="storyboard"
                                          activeItemId={activeItemId}
                                          onNavigate={onNavigate as any}
                                          onContextMenu={onContextMenu}
                                      />
                                  ))}
                              </div>
                          </div>
                      )}
                  </div>
              ) : (
                  <div className="grid grid-cols-2 gap-2">
                      {items.map(item => (
                        <SidebarCard
                          key={item.id}
                          item={item}
                          type={isStoryboard ? 'storyboard' : isGeneral ? 'general' : 'asset'}
                          activeItemId={activeItemId}
                          onNavigate={onNavigate as any}
                          onContextMenu={onContextMenu}
                        />
                      ))}
                  </div>
              )}
          </div>
      </>
  );
};
