import { useState, useEffect } from 'react';
import { Map, Loader2, Trash2 } from 'lucide-react';
import { motion } from 'framer-motion';
import { GlassCard, GlassButton } from '../components/ui';
import Modal from '../components/Modal';
import useStore from '../store/useStore';
import { generatePath } from '../services/ai';

/**
 * PathView 组件
 * 实现路径视图，基于剧本生成可执行的人生路径
 * @param {Object} props
 * @param {Function} props.onGoToScript - 跳转到剧本视图回调
 */
const PathView = ({ onGoToScript }) => {
  const { getSelectedScript, selectedPath, setPath, loadPath, deletePath, selectedScriptId } = useStore();
  const [isLoading, setIsLoading] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);

  const selectedScript = getSelectedScript();

  // 加载已有路径
  useEffect(() => {
    if (selectedScriptId) {
      loadPath(selectedScriptId).catch(() => {
        // 后端不可用时忽略错误
      });
    }
  }, [selectedScriptId, loadPath]);

  /**
   * 处理路径生成
   */
  const handleGenerate = async () => {
    if (!selectedScript) return;

    setIsLoading(true);
    
    try {
      const path = await generatePath(selectedScript.content);
      await setPath(path, selectedScriptId);
    } catch (error) {
      console.error('Failed to generate path:', error);
    } finally {
      setIsLoading(false);
    }
  };

  /**
   * 处理删除路径
   */
  const handleDelete = async () => {
    try {
      await deletePath(selectedScriptId);
      setShowDeleteConfirm(false);
    } catch (error) {
      console.error('Failed to delete path:', error);
    }
  };

  /**
   * 解析路径内容为步骤数组
   */
  const parsePathSteps = (path) => {
    if (!path) return [];
    
    return path
      .split(/【/)
      .filter(s => s.trim())
      .map((s, index) => {
        const parts = s.split(/】/);
        return {
          title: parts[0] || '',
          content: parts[1] || '',
          index: index + 1
        };
      });
  };

  const pathSteps = parsePathSteps(selectedPath);

  // 无剧本时显示提示
  if (!selectedScript) {
    return (
      <div className="flex flex-col items-center justify-center py-32 opacity-30 text-center">
        <Map className="w-16 h-16 mb-4" />
        <p className="font-serif italic text-xl">先生成剧本，方能洞察路径。</p>
        <GlassButton
          onClick={onGoToScript}
          className="mt-6 px-6 py-2 rounded-full text-xs"
        >
          去生成剧本
        </GlassButton>
      </div>
    );
  }

  return (
    <>
      <div className="max-w-3xl mx-auto space-y-12 pb-20">
        {/* 标题区域 */}
        <div className="flex justify-between items-end">
          <div>
            <h3 className="text-4xl font-serif">实现路径</h3>
            <p className="text-sm text-white/30 mt-2">
              基于《{selectedScript.theme}》，拆解达成目标的每一步。
            </p>
          </div>
          <div className="flex gap-3">
            {selectedPath && (
              <GlassButton
                onClick={() => setShowDeleteConfirm(true)}
                className="px-4 py-3 rounded-full text-sm bg-red-400/5 text-red-300 border-red-400/20 hover:bg-red-400/10"
                title="删除路径"
              >
                <Trash2 className="w-4 h-4" />
              </GlassButton>
            )}
            <GlassButton
              onClick={handleGenerate}
              disabled={isLoading}
              className="px-8 py-3 rounded-full text-sm font-bold bg-blue-400/5 text-blue-300 border-blue-400/20"
            >
              {isLoading ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  规划中...
                </>
              ) : (
                selectedPath ? '重新推演' : '开启人生导航'
              )}
            </GlassButton>
          </div>
        </div>

        {/* 路径步骤展示 */}
        <div className="space-y-6">
          {pathSteps.length > 0 ? (
            pathSteps.map((step, index) => (
              <motion.div
                key={index}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: index * 0.1, duration: 0.5 }}
              >
                <GlassCard className="border-l-4 border-l-blue-400/40 bg-blue-400/[0.01]" padding="lg">
                  <h5 className="text-blue-200 font-bold mb-4 flex items-center gap-3">
                    <span className="w-6 h-6 rounded-full bg-blue-400/20 text-[10px] flex items-center justify-center">
                      {step.index}
                    </span>
                    {step.title}
                  </h5>
                  <div className="text-white/60 text-sm leading-relaxed whitespace-pre-wrap">
                    {step.content}
                  </div>
                </GlassCard>
              </motion.div>
            ))
          ) : (
            <div className="py-20 text-center text-white/20 italic font-serif">
              等待开启人生导航...
            </div>
          )}
        </div>
      </div>

      {/* 删除确认模态框 */}
      <Modal isOpen={showDeleteConfirm} onClose={() => setShowDeleteConfirm(false)} title="确认删除" maxWidth="sm">
        <div className="space-y-6">
          <p className="text-white/70 text-sm">
            确定要删除当前的实现路径吗？此操作不可恢复。
          </p>
          <div className="flex gap-4">
            <GlassButton
              onClick={() => setShowDeleteConfirm(false)}
              className="flex-1"
            >
              取消
            </GlassButton>
            <GlassButton
              variant="primary"
              onClick={handleDelete}
              className="flex-1 bg-red-500/10 text-red-400 border-red-400/20 hover:bg-red-500/20"
            >
              确认删除
            </GlassButton>
          </div>
        </div>
      </Modal>
    </>
  );
};

export default PathView;
