'use client';

import React, { useState, useEffect } from 'react';
import { useShallow } from 'zustand/react/shallow';
import {
  Dialog,
  DialogContent,
  DialogTitle,
} from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Badge } from "@/components/ui/badge";
import { useProjectStore } from '@/lib/store/project';
import { Asset, Storyboard, AssetType } from '@/types';
import { ModalLayout, ModalSidebar, ModalContent } from "@/components/ui/modal-layout";
import { NavButton } from "@/components/ui/nav-button";
import { SearchInput } from "@/components/ui/search-input";
import { 
  Layers, 
  LayoutDashboard,
  Users,
  Layout,
  BookOpen,
  RefreshCw,
  X,
  Plus,
  Settings
} from 'lucide-react';
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

export type TabType = 'overview' | 'script' | 'assets' | 'storyboards' | 'settings';

import { OverviewTab } from './tabs/OverviewTab';
import { ScriptTab } from './tabs/ScriptTab';
import { AssetsTab } from './tabs/AssetsTab';
import { StoryboardsTab } from './tabs/StoryboardsTab';
import { SettingsTab } from './tabs/SettingsTab';
import { AssetDetails } from './details/AssetDetails';
import { StoryboardDetails } from './details/StoryboardDetails';
import CreateAssetForm from '../../forms/CreateAssetForm';
import CreateShotForm from '../../forms/CreateShotForm';
import { Dialog as RadixDialog, DialogContent as Content, DialogTitle as Title } from "@/components/ui/dialog"; // Alias to avoid conflict

interface ProjectDetailsModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export const ProjectDetailsModal: React.FC<ProjectDetailsModalProps> = ({
  isOpen,
  onClose,
}) => {
  const {
    name,
    assets,
    episodes,
    storyboards,
    addAsset,
    addStoryboard,
    updateAsset,
    deleteAsset,
    updateStoryboard,
    deleteStoryboard,
  } = useProjectStore(
    useShallow((s) => ({
      name: s.name,
      assets: s.assets,
      episodes: s.episodes,
      storyboards: s.storyboards,
      addAsset: s.addAsset,
      addStoryboard: s.addStoryboard,
      updateAsset: s.updateAsset,
      deleteAsset: s.deleteAsset,
      updateStoryboard: s.updateStoryboard,
      deleteStoryboard: s.deleteStoryboard,
    }))
  );

  const [activeTab, setActiveTab] = useState<TabType>('overview');
  // Use IDs instead of objects to ensure data reactivity
  const [selectedAssetId, setSelectedAssetId] = useState<string | null>(null);
  const [selectedStoryboardId, setSelectedStoryboardId] = useState<string | null>(null);
  
  // Creation State
  const [isCreatingAsset, setIsCreatingAsset] = useState<boolean>(false);
  const [creatingAssetType, setCreatingAssetType] = useState<AssetType | null>(null);
  const [isCreatingStoryboard, setIsCreatingStoryboard] = useState<boolean>(false);

  // Derived state for current selection
  const selectedAsset = selectedAssetId ? assets.find(a => a.id === selectedAssetId) || null : null;
  const selectedStoryboard = selectedStoryboardId ? storyboards.find(s => s.id === selectedStoryboardId) || null : null;
  
  // Asset Filtering
  const [assetFilter, setAssetFilter] = useState<AssetType | 'all'>('all');
  const [assetSearch, setAssetSearch] = useState('');

  // Storyboard Filtering
  const [selectedEpisodeId, setSelectedEpisodeId] = useState<string>('all');

  // Close details handlers
  const closeDetails = () => {
    setSelectedAssetId(null);
    setSelectedStoryboardId(null);
  };

  // Auto-close details when switching tabs
  useEffect(() => {
    closeDetails();
  }, [activeTab]);

  // Creation Handlers
  const handleStartCreateAsset = (type: AssetType) => {
    setCreatingAssetType(type);
    setIsCreatingAsset(true);
  };

  const handleStartCreateStoryboard = () => {
    setIsCreatingStoryboard(true);
  };

  const menuItems: { id: TabType; label: string; icon: React.ElementType }[] = [
    { id: 'overview', label: '项目概览', icon: LayoutDashboard },
    { id: 'script', label: '剧本解析', icon: BookOpen },
    { id: 'assets', label: '素材中心', icon: Users },
    { id: 'storyboards', label: '分镜中心', icon: Layout },
    { id: 'settings', label: '项目设置', icon: Settings },
  ];

  // Filtered Storyboards for header badge
  const filteredStoryboards = storyboards.filter(sb => {
    if (selectedEpisodeId === 'all') return true;
    return sb.episodeId === selectedEpisodeId;
  });

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <DialogContent className="max-w-6xl h-[85vh] flex flex-col p-0 gap-0 overflow-hidden border-none outline-none bg-background [&_.dialog-close-button]:hidden">
        
        {/* Full Width Header */}
        <div className="h-14 flex items-center px-6 border-b border-border bg-background shrink-0 justify-between">
          <DialogTitle className="flex items-center gap-2 font-semibold truncate text-foreground text-sm m-0">
            <Layers className="w-4 h-4 text-primary" />
            <span className="truncate" title={name}>{name}</span>
          </DialogTitle>
          <Button variant="ghost" size="icon" className="h-8 w-8 rounded-full" onClick={onClose}>
            <X className="h-4 w-4" />
          </Button>
        </div>

        <ModalLayout>
          {/* Sidebar Navigation */}
          <ModalSidebar>
            <nav className="flex-1 py-4 px-3 space-y-2 overflow-y-auto">
              {menuItems.map((item) => (
                <NavButton
                  key={item.id}
                  isActive={activeTab === item.id}
                  onClick={() => setActiveTab(item.id)}
                  icon={item.icon}
                  label={item.label}
                />
              ))}
            </nav>
            
            {/* Footer / Version Info */}
            <div className="p-4 border-t border-border text-xs text-muted-foreground bg-background">
              <div className="flex justify-between items-center">
                <span>状态</span>
                <span className="flex items-center gap-1.5">
                    <span className="w-2 h-2 rounded-full bg-green-500" />
                    进行中
                </span>
              </div>
            </div>
          </ModalSidebar>

          {/* Main Content Area */}
          <ModalContent>
          
          {/* Content Headers - All removed for cleaner layout */}

          {/* Scrollable Content */}
          <ScrollArea className="flex-1">
            <div className="p-6 pb-24">
              
              {activeTab === 'overview' && (
                <div className="max-w-6xl mx-auto">
                  <OverviewTab />
                </div>
              )}

              {activeTab === 'settings' && (
                <div className="max-w-4xl mx-auto">
                  <SettingsTab />
                </div>
              )}
              
              {activeTab === 'script' && (
                <div className="max-w-4xl mx-auto">
                  <ScriptTab 
                    selectedEpisodeId={selectedEpisodeId} 
                    onEpisodeChange={setSelectedEpisodeId}
                  />
                </div>
              )}
              
              {activeTab === 'assets' && (
                <div className="max-w-7xl mx-auto">
                  <AssetsTab 
                    assetFilter={assetFilter}
                    assetSearch={assetSearch}
                    setAssetFilter={setAssetFilter}
                    setAssetSearch={setAssetSearch}
                    setSelectedAsset={(asset) => setSelectedAssetId(asset?.id || null)}
                    onCreateAsset={handleStartCreateAsset}
                  />
                </div>
              )}
              
              {activeTab === 'storyboards' && (
                <div className="max-w-6xl mx-auto">
                  <StoryboardsTab 
                    selectedEpisodeId={selectedEpisodeId}
                    onEpisodeChange={setSelectedEpisodeId}
                    setSelectedStoryboard={(sb) => setSelectedStoryboardId(sb?.id || null)}
                    onCreateStoryboard={handleStartCreateStoryboard}
                  />
                </div>
              )}
            </div>
          </ScrollArea>

          {/* Details Overlays */}
          {selectedAsset && (
            <AssetDetails 
              asset={selectedAsset} 
              onClose={closeDetails} 
              onUpdateAsset={updateAsset}
              onDeleteAsset={(id) => {
                deleteAsset(id);
                closeDetails();
              }}
            />
          )}

          {selectedStoryboard && (
            <StoryboardDetails 
              storyboard={selectedStoryboard} 
              onClose={closeDetails}
              onSelectAsset={(asset) => setSelectedAssetId(asset.id)}
              onUpdateStoryboard={updateStoryboard}
              onDeleteStoryboard={(id) => {
                deleteStoryboard(id);
                closeDetails();
              }}
            />
          )}

          {/* Creation Modals - Reusing existing forms in a dialog wrapper for now */}
          {/* Note: In a real app we might want dedicated modal components or reuse a generic Modal wrapper */}
          
          {/* Create Asset Modal */}
          <RadixDialog open={isCreatingAsset} onOpenChange={setIsCreatingAsset}>
            <Content className="max-w-3xl max-h-[85vh] overflow-y-auto">
               <Title>创建{creatingAssetType === 'character' ? '角色' : creatingAssetType === 'scene' ? '场景' : '道具'}</Title>
               {creatingAssetType && (
                 <CreateAssetForm 
                    creatingAssetType={creatingAssetType}
                    onCancelCreate={() => setIsCreatingAsset(false)}
                    onCreateAsset={(asset) => {
                      addAsset(asset);
                      setIsCreatingAsset(false);
                    }}
                 />
               )}
            </Content>
          </RadixDialog>

          {/* Create Storyboard Modal */}
          <RadixDialog open={isCreatingStoryboard} onOpenChange={setIsCreatingStoryboard}>
            <Content className="max-w-3xl max-h-[85vh] overflow-y-auto">
              <Title>创建分镜</Title>
              <CreateShotForm 
                onCancelCreate={() => setIsCreatingStoryboard(false)}
                onCreateShot={(storyboard) => {
                  // Handle shot creation with proper type casting
                  // CreateShotForm returns Partial<Storyboard>, ensure required fields are present
                  const newStoryboard = {
                    ...storyboard,
                    episodeId: storyboard.episodeId || episodes[0]?.id || '',
                    order: storyboard.order ?? 0,
                    shot: storyboard.shot || '',
                    desc: storyboard.desc || '',
                    duration: storyboard.duration || '3s',
                    type: storyboard.type || 'medium',
                    characterIds: storyboard.characterIds || [],
                    propIds: storyboard.propIds || [],
                  };
                  addStoryboard(newStoryboard as any);
                  setIsCreatingStoryboard(false);
                }}
                availableScenes={assets.filter(a => a.type === 'scene').map(a => ({ label: a.name, value: a.id }))}
                availableCharacters={assets.filter(a => a.type === 'character').map(a => ({ label: a.name, value: a.id }))}
                availableProps={assets.filter(a => a.type === 'prop').map(a => ({ label: a.name, value: a.id }))}
              />
            </Content>
          </RadixDialog>

          </ModalContent>
        </ModalLayout>
      </DialogContent>
    </Dialog>
  );
};
