import React from 'react';
import { useShallow } from 'zustand/react/shallow';
import { Badge } from "@/components/ui/badge";
import { BookOpen, FileText, RefreshCw } from 'lucide-react';
import { useProjectStore } from '@/lib/store/project';
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { EmptyState } from "@/components/ui/empty-state";

interface ScriptTabProps {
  selectedEpisodeId: string;
  onEpisodeChange: (episodeId: string) => void;
}

export const ScriptTab: React.FC<ScriptTabProps> = ({ selectedEpisodeId, onEpisodeChange }) => {
  const { episodes, updateEpisode } = useProjectStore(
    useShallow((s) => ({ episodes: s.episodes, updateEpisode: s.updateEpisode }))
  );

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed': return 'bg-green-500/10 text-green-500 border-green-500/20';
      case 'production': return 'bg-blue-500/10 text-blue-500 border-blue-500/20';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const renderEpisodeEditor = (episode: any) => (
    <div key={episode.id} className="flex flex-col gap-4 border rounded-xl p-6 bg-card">
      <div className="flex flex-col gap-3 pb-4 border-b">
        <div className="flex items-center justify-between">
          <h3 className="text-base font-semibold flex items-center gap-2">
            <span className="text-muted-foreground">第 {episode.order} 集:</span> 
            <Input 
              value={episode.title}
              onChange={(e) => updateEpisode(episode.id, { title: e.target.value })}
              className="h-8 w-64 font-semibold bg-transparent border-transparent hover:border-border focus:border-primary transition-all"
            />
          </h3>
          <div className="flex items-center gap-3">
             <Select 
                value={episode.status} 
                onValueChange={(v) => updateEpisode(episode.id, { status: v as any })}
             >
                <SelectTrigger className={`h-7 w-[100px] text-xs border ${getStatusColor(episode.status)}`}>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="draft">草稿</SelectItem>
                  <SelectItem value="production">制作中</SelectItem>
                  <SelectItem value="completed">已完成</SelectItem>
                </SelectContent>
             </Select>
             <Badge variant="outline" className="text-[10px] h-7">
               {episode.content?.length || 0} 字
             </Badge>
          </div>
        </div>
        
        <div className="flex items-start gap-3 bg-muted/30 p-3 rounded-lg">
           <FileText className="w-4 h-4 text-muted-foreground mt-1 flex-shrink-0" />
           <Input
             placeholder="本集简介..."
             value={episode.desc || ''}
             onChange={(e) => updateEpisode(episode.id, { desc: e.target.value })}
             className="h-auto py-1 border-0 bg-transparent shadow-none focus-visible:ring-0 text-sm text-muted-foreground placeholder:text-muted-foreground/50"
           />
        </div>
      </div>

      <Textarea
        className="w-full min-h-[400px] p-4 rounded-lg border bg-muted/20 focus:bg-background focus:ring-2 focus:ring-primary/20 resize-none outline-none transition-all font-mono text-sm leading-relaxed"
        placeholder="在此输入剧本内容..."
        value={episode.content || ''}
        onChange={(e) => updateEpisode(episode.id, { content: e.target.value })}
      />
    </div>
  );

  return (
    <div className="animate-in fade-in duration-300">
      {/* Header Controls */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-4">
          <span className="text-sm font-medium text-muted-foreground">选择剧集：</span>
          <Select value={selectedEpisodeId} onValueChange={onEpisodeChange}>
            <SelectTrigger className="w-[200px] h-9 rounded-full border-border/50 bg-muted/30">
              <SelectValue placeholder="选择剧集" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部剧集</SelectItem>
              {episodes.map(ep => (
                <SelectItem key={ep.id} value={ep.id}>
                  第 {ep.order} 集: {ep.title}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div className="flex items-center gap-2">
          <Button size="sm" variant="outline" className="rounded-full gap-2 text-primary hover:text-primary hover:bg-primary/10 border-primary/20">
            <RefreshCw className="w-4 h-4" />
            重新解析
          </Button>
        </div>
      </div>

      {/* Content */}
       {selectedEpisodeId === 'all' ? (
         <div className="space-y-6">
            {episodes.map(episode => renderEpisodeEditor(episode))}
            {episodes.length === 0 && (
              <EmptyState 
                icon={BookOpen}
                title="暂无剧集"
                description="创建剧集后可以在此编辑剧本内容"
                className="py-20"
              />
            )}
         </div>
       ) : (
         <div className="space-y-6">
            {episodes.filter(e => e.id === selectedEpisodeId).map(episode => renderEpisodeEditor(episode))}
         </div>
       )}
    </div>
  );
};
