'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, Image as ImageIcon } from 'lucide-react';
import { Asset } from '@/types';
import AssetInfoTab from './AssetInfoTab';
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 AssetDetailsProps {
  asset: Asset;
  onClose: () => void;
  onUpdateAsset: (id: string, updates: Partial<Asset>) => void;
  onDeleteAsset: (id: string) => void;
}

export const AssetDetails: React.FC<AssetDetailsProps> = ({ 
  asset, 
  onClose,
  onUpdateAsset,
  onDeleteAsset
}) => {
  const [footerContent, setFooterContent] = useState<React.ReactNode>(null);
  const [hoverPreview, setHoverPreview] = useState<{ url: string, x: number, y: number } | null>(null);
  
  // Media Dialog State
  const [activeMediaTab, setActiveMediaTab] = useState<'image' | 'video'>('image');
  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);

  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>
          <div className="flex gap-2">
             <Badge variant="outline" className="capitalize text-[10px]">{asset.type}</Badge>
          </div>
       </div>
       <ScrollArea className="flex-1">
          <div className="p-8 max-w-[1400px] mx-auto w-full h-full">
            <div className="grid grid-cols-[300px_1fr] gap-8 h-full">
               {/* Left Side - Image/Preview */}
               <div className="flex flex-col gap-4">
                 <div className="w-[200px] aspect-square bg-muted/30 rounded-2xl overflow-hidden border flex items-center justify-center p-4 relative mx-auto">
                    {(asset.imageUrl || asset.imageUrls?.[0]) ? (
                       <div className="relative w-full h-full">
                           <Image 
                             src={asset.imageUrl || asset.imageUrls?.[0] || ''} 
                             alt={asset.name} 
                             fill 
                             className="object-contain" 
                           />
                       </div>
                    ) : (
                       <ImageIcon className="w-12 h-12 text-muted-foreground/20" />
                    )}
                    {/* 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: 200, // Added explicit height for Image fill
                        }}
                      >
                        <div className="relative w-full h-full">
                             <Image src={hoverPreview.url} alt="Preview" fill className="object-cover" />
                        </div>
                      </div>
                    )}
                 </div>
                 {asset.audioUrl && (
                    <div className="p-4 border rounded-xl bg-muted/10">
                      <h4 className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider mb-2">音频预览</h4>
                      <audio controls src={asset.audioUrl} className="w-full h-8" />
                    </div>
                 )}
               </div>
               
               {/* Right Side - Editing Tabs */}
               <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>
                      <AssetInfoTab 
                        selectedAsset={asset}
                        onUpdateAsset={onUpdateAsset}
                        onDeleteAsset={onDeleteAsset}
                        setFooter={setFooterContent}
                        isActive={true}
                        onClose={onClose}
                      />
                  </div>

                  {/* Media Assets (Unified) */}
                  <div>
                        <h3 className="text-sm font-semibold mb-4 flex items-center gap-2">
                            <div className="w-1 h-4 bg-indigo-500 rounded-full" />
                            素材库
                        </h3>
                        <div className="border rounded-xl overflow-hidden bg-background/50 min-h-[400px] flex flex-col">
                            <MediaManager
                                containerId={`asset-media-${asset.id}`}
                                activeTab={activeMediaTab}
                                onTabChange={setActiveMediaTab}
                                hideTabs={false}
                                scrollable={false}
                                className="h-auto"
                                viewMode={mediaViewMode}
                                onViewModeChange={setMediaViewMode}
                                gridCols={mediaGridCols}
                                setGridCols={setMediaGridCols}
                                listCols={mediaListCols}
                                setListCols={setMediaListCols}
                                imageUrls={asset.imageUrls || []}
                                videoUrls={asset.videoUrls || []}
                                generations={asset.generations}
                                currentCoverUrl={asset.imageUrl}
                                onPreview={(media) => {
                                    setPreviewMedia({ url: media.url, type: media.type });
                                }}
                                onSetCover={(id, url) => onUpdateAsset(asset.id, { imageUrl: url })}
                                onDeleteImage={(id, url) => {
                                    const newUrls = (asset.imageUrls || []).filter(u => u !== url);
                                    onUpdateAsset(asset.id, { imageUrls: newUrls });
                                }}
                                onDeleteVideo={(id, url) => {
                                    const newUrls = (asset.videoUrls || []).filter(u => u !== url);
                                    onUpdateAsset(asset.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>
  );
};
