'use client';

import React, { useState } from 'react';
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { X, Film, Clock, MapPin, Sun } from 'lucide-react';
import { Storyboard, Asset } from '@/types';
import { useProjectStore } from '@/lib/store/project';
import ShotInfoTab from './ShotInfoTab';
import { MediaManager } from '@components/common/MediaManager';
import { ViewMode } from '@components/common/ViewDisplayControl';
import { Dialog, DialogContent } from "@/components/ui/dialog";
import Image from 'next/image';

interface StoryboardDetailsProps {
  storyboard: Storyboard;
  onClose: () => void;
  onSelectAsset: (asset: Asset) => void;
  onUpdateStoryboard: (id: string, updates: Partial<Storyboard>) => void;
  onDeleteStoryboard: (id: string) => void;
}

export const StoryboardDetails: React.FC<StoryboardDetailsProps> = ({ 
  storyboard, 
  onClose,
  onSelectAsset,
  onUpdateStoryboard,
  onDeleteStoryboard
}) => {
  const assets = useProjectStore((s) => s.assets);
  const [footerContent, setFooterContent] = useState<React.ReactNode>(null);
  const [hoverPreview, setHoverPreview] = useState<{ url: string, x: number, y: number } | null>(null);

  // Media Dialog State
  const [mediaViewMode, setMediaViewMode] = useState<ViewMode>('grid');
  const [mediaGridCols, setMediaGridCols] = useState(4);
  const [mediaListCols, setMediaListCols] = useState(1);
  const [previewMedia, setPreviewMedia] = useState<{ url: string, type: 'image' | 'video' } | null>(null);

  // Prepare options for SelectControls
  const availableScenes = assets
    .filter(a => a.type === 'scene')
    .map(a => ({ label: a.name, value: a.id }));
    
  const availableCharacters = assets
    .filter(a => a.type === 'character')
    .map(a => ({ label: a.name, value: a.id }));

  const availableProps = assets
    .filter(a => a.type === 'prop')
    .map(a => ({ label: a.name, value: a.id }));

  return (
    <div className="absolute inset-0 z-50 bg-background flex flex-col animate-in slide-in-from-right-10 duration-200 shadow-2xl">
       <div className="flex items-center justify-between px-6 py-4 border-b bg-muted/10">
          <div className="flex items-center gap-3">
            <Button variant="ghost" size="icon" onClick={onClose} className="h-8 w-8 rounded-full">
              <X className="w-4 h-4" />
            </Button>
            <span className="font-semibold text-base">分镜详情</span>
          </div>
          <Badge variant="secondary" className="text-[10px]">镜头 {storyboard.shot}</Badge>
       </div>
       <ScrollArea className="flex-1">
          <div className="p-8 max-w-[1600px] mx-auto w-full h-full">
            <div className="grid grid-cols-[400px_1fr] gap-8 h-full">
               <div className="flex flex-col gap-4">
                  <div className="w-[300px] aspect-video bg-black/5 rounded-2xl overflow-hidden border relative mx-auto">
                     {storyboard.imageUrls?.[0] ? (
                       <Image src={storyboard.imageUrls[0]} alt="Storyboard" fill className="object-contain" />
                     ) : (
                       <div className="w-full h-full flex items-center justify-center"><Film className="w-10 h-10 opacity-10"/></div>
                     )}
                     {/* Hover Preview Overlay */}
                     {hoverPreview && (
                       <div 
                         className="fixed z-[60] pointer-events-none rounded-lg overflow-hidden border shadow-xl bg-background"
                         style={{
                           left: hoverPreview.x + 20,
                           top: hoverPreview.y - 100,
                           width: 200,
                           height: 112, // Approx aspect video height
                         }}
                       >
                         <div className="relative w-full h-full">
                            <Image src={hoverPreview.url} alt="Preview" fill className="object-cover" />
                         </div>
                       </div>
                     )}
                  </div>
                  {storyboard.videoUrls?.[0] && (
                    <video src={storyboard.videoUrls[0]} controls className="w-full rounded-xl border bg-black" />
                  )}
               </div>

               <div className="flex flex-col h-full min-h-[500px] space-y-8">
                  {/* Basic Info */}
                  <div>
                      <h3 className="text-sm font-semibold mb-4 flex items-center gap-2">
                        <div className="w-1 h-4 bg-primary rounded-full" />
                        镜头信息
                      </h3>
                      <ShotInfoTab 
                        selectedStoryboard={storyboard}
                        onUpdateStoryboard={onUpdateStoryboard}
                        onDeleteStoryboard={onDeleteStoryboard}
                        availableScenes={availableScenes}
                        availableCharacters={availableCharacters}
                        availableProps={availableProps}
                        setFooter={setFooterContent}
                        isActive={true}
                        onClose={onClose}
                      />
                  </div>

                  {/* Image Assets */}
                  <div>
                        <h3 className="text-sm font-semibold mb-4 flex items-center gap-2">
                            <div className="w-1 h-4 bg-blue-500 rounded-full" />
                            图片素材
                        </h3>
                        <div className="border rounded-xl overflow-hidden bg-background/50">
                            <MediaManager
                                containerId={`storyboard-media-image-${storyboard.id}`}
                                activeTab="image"
                                onTabChange={() => {}}
                                hideTabs={true}
                                scrollable={false}
                                className="h-auto"
                                viewMode={mediaViewMode}
                                onViewModeChange={setMediaViewMode}
                                gridCols={mediaGridCols}
                                setGridCols={setMediaGridCols}
                                listCols={mediaListCols}
                                setListCols={setMediaListCols}
                                imageUrls={storyboard.imageUrls || []}
                                videoUrls={[]}
                                generations={storyboard.generations}
                                currentCoverUrl={storyboard.imageUrls?.[0]}
                                onPreview={(media) => {
                                    setPreviewMedia({ url: media.url, type: media.type });
                                }}
                                onSetCover={(id, url) => {
                                    // Set as first image
                                    const otherUrls = (storyboard.imageUrls || []).filter(u => u !== url);
                                    onUpdateStoryboard(storyboard.id, { imageUrls: [url, ...otherUrls] });
                                }}
                                onDeleteImage={(id, url) => {
                                    const newUrls = (storyboard.imageUrls || []).filter(u => u !== url);
                                    onUpdateStoryboard(storyboard.id, { imageUrls: newUrls });
                                }}
                                showList={false}
                            />
                        </div>
                  </div>
                    
                  {/* Video Assets */}
                  <div>
                        <h3 className="text-sm font-semibold mb-4 flex items-center gap-2">
                            <div className="w-1 h-4 bg-purple-500 rounded-full" />
                            视频素材
                        </h3>
                        <div className="border rounded-xl overflow-hidden bg-background/50">
                            <MediaManager
                                containerId={`storyboard-media-video-${storyboard.id}`}
                                activeTab="video"
                                onTabChange={() => {}}
                                hideTabs={true}
                                scrollable={false}
                                className="h-auto"
                                viewMode={mediaViewMode}
                                onViewModeChange={setMediaViewMode}
                                gridCols={mediaGridCols}
                                setGridCols={setMediaGridCols}
                                listCols={mediaListCols}
                                setListCols={setMediaListCols}
                                imageUrls={[]}
                                videoUrls={storyboard.videoUrls || []}
                                generations={storyboard.generations}
                                onPreview={(media) => {
                                    setPreviewMedia({ url: media.url, type: media.type });
                                }}
                                onDeleteVideo={(id, url) => {
                                    const newUrls = (storyboard.videoUrls || []).filter(u => u !== url);
                                    onUpdateStoryboard(storyboard.id, { videoUrls: newUrls });
                                }}
                                showList={false}
                            />
                        </div>
                  </div>

                  {/* Footer Actions */}
                  <div className="mt-6 pt-4 border-t sticky bottom-0 bg-background py-4 z-10">
                    {footerContent}
                  </div>
               </div>
            </div>
          </div>
       </ScrollArea>

       {/* Media Preview Dialog */}
       <Dialog open={!!previewMedia} onOpenChange={(open) => !open && setPreviewMedia(null)}>
         <DialogContent className="max-w-4xl p-0 overflow-hidden bg-black/90 border-none">
           <div className="relative flex items-center justify-center w-full h-full min-h-[500px]">
             {previewMedia?.type === 'image' ? (
               <div className="relative w-full h-[80vh]">
                   <Image src={previewMedia.url} alt="Preview" fill className="object-contain" />
               </div>
             ) : previewMedia?.type === 'video' ? (
               <video src={previewMedia.url} controls className="max-w-full max-h-[80vh]" autoPlay />
             ) : null}
           </div>
         </DialogContent>
       </Dialog>
    </div>
  );
};
