import React, { useState, useMemo, useRef, useEffect } from 'react';
import { useParams } from 'next/navigation';
import { useShallow } from 'zustand/react/shallow';
import { Layers, Trash2, Loader2, Users, Clapperboard, Box, Image as ImageIcon, Sparkles, X } from 'lucide-react';
import { Episode, EpisodeId } from '@/types';
import { InputControl, SelectControl } from '../../../shared/FormControls';
import { DefaultService } from '@lib/api';
import { useProjectStore } from '@lib/store/project';
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";

interface EpisodeDetailsProps {
    episode: Episode;
    onClose: () => void;
    onUpdateEpisode: (id: EpisodeId, updates: Partial<Episode>) => void;
    onDeleteEpisode?: (id: EpisodeId) => void;
}

export const EpisodeDetails: React.FC<EpisodeDetailsProps> = ({
    episode,
    onClose,
    onUpdateEpisode,
    onDeleteEpisode
}) => {
    const params = useParams();
    const projectId = params.id as string;
    const { setProject, storyboards, assets } = useProjectStore(
        useShallow((s) => ({ setProject: s.setProject, storyboards: s.storyboards, assets: s.assets }))
    );
    const [isAnalyzing, setIsAnalyzing] = useState(false);
    const [showDeleteAlert, setShowDeleteAlert] = useState(false);

    // Get storyboards for this episode
    const episodeStoryboards = useMemo(() => 
        storyboards.filter(sb => sb.episodeId === episode.id).sort((a, b) => a.order - b.order),
    [storyboards, episode.id]);

    // Get assets used in this episode's storyboards
    const episodeAssets = useMemo(() => {
        const charIds = new Set<string>();
        const sceneIds = new Set<string>();
        const propIds = new Set<string>();

        episodeStoryboards.forEach(sb => {
            sb.characterIds.forEach(id => charIds.add(id));
            if (sb.sceneId) sceneIds.add(sb.sceneId);
            sb.propIds.forEach(id => propIds.add(id));
        });

        return {
            characters: assets.filter(a => charIds.has(a.id)),
            scenes: assets.filter(a => sceneIds.has(a.id)),
            props: assets.filter(a => propIds.has(a.id))
        };
    }, [episodeStoryboards, assets]);

    const handleAnalyze = async () => {
        if (!episode.content) {
            alert("请先输入章节正文内容");
            return;
        }
        
        setIsAnalyzing(true);
        try {
            const response = await DefaultService.analyzeEpisode(projectId, episode.id);
            // BaseResponse structure: { code, message, data: { ... } }
            const updatedProject = (response as any).data?.data;
            if (updatedProject) {
                setProject(updatedProject);
            }
        } catch (error) {
            console.error("Analysis failed:", error);
            alert("智能解析失败，请重试");
        } finally {
            setIsAnalyzing(false);
        }
    };

    return (
        <>
            {/* Overlay Background */}
            <div 
                className="absolute inset-0 bg-black/50 backdrop-blur-sm z-40 animate-in fade-in duration-200"
                onClick={onClose}
            />

            {/* Sidebar Panel */}
            <div className="absolute right-0 top-0 bottom-0 w-[480px] bg-background border-l border-border shadow-2xl z-50 flex flex-col animate-in slide-in-from-right duration-300">
                
                {/* Header */}
                <div className="h-14 flex items-center justify-between px-6 border-b border-border shrink-0">
                    <div className="flex items-center gap-2">
                        <Layers className="w-4 h-4 text-primary" />
                        <h3 className="text-sm font-semibold">章节详情</h3>
                    </div>
                    <div className="flex items-center gap-2">
                        <span className="text-xs bg-blue-600/10 text-blue-400 px-2 py-1 rounded border border-blue-600/20 uppercase">
                            {episode.status}
                        </span>
                        <Button variant="ghost" size="icon" className="h-8 w-8" onClick={onClose}>
                            <X className="h-4 w-4" />
                        </Button>
                    </div>
                </div>

                {/* Content */}
                <div className="flex-1 overflow-y-auto p-6 space-y-6">
                    {/* Stats Summary */}
                    <div className="grid grid-cols-4 gap-3">
                        <div className="bg-muted/30 border border-border rounded-lg p-3 text-center">
                            <div className="text-xs text-muted-foreground mb-1 flex justify-center">
                                <Clapperboard size={14}/>
                            </div>
                            <div className="text-sm font-semibold text-foreground">{episodeStoryboards.length}</div>
                            <div className="text-[10px] text-muted-foreground mt-0.5">分镜</div>
                        </div>
                        <div className="bg-muted/30 border border-border rounded-lg p-3 text-center">
                            <div className="text-xs text-muted-foreground mb-1 flex justify-center">
                                <Users size={14}/>
                            </div>
                            <div className="text-sm font-semibold text-foreground">{episodeAssets.characters.length}</div>
                            <div className="text-[10px] text-muted-foreground mt-0.5">角色</div>
                        </div>
                        <div className="bg-muted/30 border border-border rounded-lg p-3 text-center">
                            <div className="text-xs text-muted-foreground mb-1 flex justify-center">
                                <ImageIcon size={14}/>
                            </div>
                            <div className="text-sm font-semibold text-foreground">{episodeAssets.scenes.length}</div>
                            <div className="text-[10px] text-muted-foreground mt-0.5">场景</div>
                        </div>
                        <div className="bg-muted/30 border border-border rounded-lg p-3 text-center">
                            <div className="text-xs text-muted-foreground mb-1 flex justify-center">
                                <Box size={14}/>
                            </div>
                            <div className="text-sm font-semibold text-foreground">{episodeAssets.props.length}</div>
                            <div className="text-[10px] text-muted-foreground mt-0.5">道具</div>
                        </div>
                    </div>

                    {/* Form Fields */}
                    <div className="space-y-4">
                        <InputControl 
                            label="章节标题" 
                            value={episode.title} 
                            onChange={(v) => onUpdateEpisode(episode.id, { title: v })}
                        />

                        <div className="grid grid-cols-2 gap-4">
                            <InputControl 
                                label="序号" 
                                value={episode.order.toString()} 
                                type="number"
                                onChange={(v) => onUpdateEpisode(episode.id, { order: parseInt(v) || episode.order })}
                            />

                            <SelectControl 
                                label="状态" 
                                options={[
                                    { label: '草稿', value: 'draft' },
                                    { label: '制作中', value: 'production' },
                                    { label: '已完成', value: 'completed' }
                                ]} 
                                value={episode.status} 
                                onChange={(v) => onUpdateEpisode(episode.id, { status: v as any })}
                            />
                        </div>

                        <div className="space-y-2">
                            <label className="text-xs text-muted-foreground font-medium">章节概要</label>
                            <Textarea 
                                className="w-full h-24 bg-background border border-border rounded-lg p-3 text-sm text-foreground placeholder-muted-foreground resize-none focus:outline-none focus:border-primary/50 leading-relaxed"
                                value={episode.desc || ''}
                                onChange={(e) => onUpdateEpisode(episode.id, { desc: e.target.value })}
                                placeholder="输入章节的剧情简介..."
                            />
                        </div>

                        <div className="space-y-2">
                            <label className="text-xs text-muted-foreground font-medium">正文内容</label>
                            <Textarea 
                                className="w-full h-64 bg-background border border-border rounded-lg p-3 text-sm text-foreground placeholder-muted-foreground resize-none focus:outline-none focus:border-primary/50 leading-relaxed font-mono"
                                value={episode.content}
                                onChange={(e) => onUpdateEpisode(episode.id, { content: e.target.value })}
                                placeholder="输入章节正文内容..."
                            />
                        </div>
                    </div>
                </div>

                {/* Footer Actions */}
                <div className="h-16 border-t border-border px-6 flex items-center gap-2 shrink-0">
                    <Button 
                        className="flex-1 gap-2 bg-gradient-to-r from-blue-600 to-cyan-600 hover:from-blue-500 hover:to-cyan-500 text-white"
                        onClick={handleAnalyze}
                        disabled={isAnalyzing}
                    >
                        {isAnalyzing ? <Loader2 size={16} className="animate-spin" /> : <Sparkles size={16} />}
                        <span>{isAnalyzing ? '解析中...' : '智能解析章节'}</span>
                    </Button>
                    {onDeleteEpisode && (
                        <Button 
                            variant="ghost"
                            size="icon"
                            className="bg-red-500/10 hover:bg-red-500/20 text-red-500 border border-red-500/20"
                            onClick={() => setShowDeleteAlert(true)}
                            title="删除章节"
                        >
                            <Trash2 size={16} />
                        </Button>
                    )}
                </div>
            </div>

            {/* Delete Confirmation Dialog */}
            <AlertDialog open={showDeleteAlert} onOpenChange={setShowDeleteAlert}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>确认删除章节?</AlertDialogTitle>
                        <AlertDialogDescription>
                            此操作无法撤销。该章节及其所有分镜将被永久删除。
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>取消</AlertDialogCancel>
                        <AlertDialogAction 
                            onClick={() => {
                                onDeleteEpisode?.(episode.id);
                                setShowDeleteAlert(false);
                                onClose();
                            }} 
                            className="bg-red-500 hover:bg-red-600"
                        >
                            删除
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </>
    );
};
