import { useState, useEffect, useRef, useCallback } from "react";
import { Loader2, Sparkles } from "lucide-react";
import api from "@/shared/api/axios";
import { ApiResponse, unwrap } from "@/shared/api/types";
import { AppModal, AppModalHeader } from "@/shared/ui/AppModal";

const CUSTOM_PROMPT_KEY = "vigent_rewriteCustomPrompt";

interface RewriteModalProps {
  isOpen: boolean;
  onClose: () => void;
  originalText: string;
  onApply: (text: string) => void;
}

export default function RewriteModal({
  isOpen,
  onClose,
  originalText,
  onApply,
}: RewriteModalProps) {
  const [customPrompt, setCustomPrompt] = useState(
    () => (typeof window !== "undefined" ? localStorage.getItem(CUSTOM_PROMPT_KEY) || "" : "")
  );
  const [rewrittenText, setRewrittenText] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Debounced save customPrompt to localStorage
  const debounceRef = useRef<ReturnType<typeof setTimeout>>(undefined);
  useEffect(() => {
    debounceRef.current = setTimeout(() => {
      localStorage.setItem(CUSTOM_PROMPT_KEY, customPrompt);
    }, 300);
    return () => clearTimeout(debounceRef.current);
  }, [customPrompt]);

  // Reset state when modal opens
  useEffect(() => {
    if (isOpen) {
      setRewrittenText("");
      setError(null);
      setIsLoading(false);
    }
  }, [isOpen]);

  const handleRewrite = useCallback(async () => {
    if (!originalText.trim()) return;

    setIsLoading(true);
    setError(null);

    try {
      const { data: res } = await api.post<
        ApiResponse<{ rewritten_text: string }>
      >("/api/ai/rewrite", {
        text: originalText,
        custom_prompt: customPrompt.trim() || null,
      });
      const payload = unwrap(res);
      setRewrittenText(payload.rewritten_text || "");
    } catch (err: unknown) {
      console.error("AI rewrite failed:", err);
      const axiosErr = err as {
        response?: { data?: { message?: string } };
        message?: string;
      };
      const msg =
        axiosErr.response?.data?.message || axiosErr.message || "改写失败，请重试";
      setError(msg);
    } finally {
      setIsLoading(false);
    }
  }, [originalText, customPrompt]);

  const handleApply = () => {
    onApply(rewrittenText);
    onClose();
  };

  const handleRetry = () => {
    setRewrittenText("");
    setError(null);
  };

  if (!isOpen) return null;

  return (
    <AppModal
      isOpen={isOpen}
      onClose={onClose}
      panelClassName="w-full max-w-2xl max-h-[90vh] rounded-2xl border border-white/10 bg-[#171821]/95 shadow-[0_24px_80px_rgba(0,0,0,0.55)] overflow-hidden flex flex-col"
      closeOnOverlay={false}
    >
      <AppModalHeader
        title="AI 智能改写"
        icon={<Sparkles className="h-5 w-5 text-purple-300" />}
        onClose={onClose}
      />

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6 space-y-5">
          {/* Custom Prompt */}
          <div className="space-y-2">
            <label className="text-sm text-gray-300">
              自定义提示词 (可选)
            </label>
            <textarea
              value={customPrompt}
              onChange={(e) => setCustomPrompt(e.target.value)}
              placeholder="输入改写要求..."
              rows={3}
              className="w-full bg-black/20 border border-white/10 rounded-xl px-3 py-2 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-purple-500 transition-colors resize-none"
            />
            <p className="text-xs text-gray-500">留空则使用默认提示词</p>
          </div>

          {/* Action button (before result) */}
          {!rewrittenText && (
            <button
              onClick={handleRewrite}
              disabled={isLoading || !originalText.trim()}
              className="w-full py-3 px-4 bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-500 hover:to-pink-500 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-xl transition-all font-medium shadow-lg flex items-center justify-center gap-2"
            >
              {isLoading ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  改写中...
                </>
              ) : (
                <>
                  <Sparkles className="w-5 h-5" />
                  开始改写
                </>
              )}
            </button>
          )}

          {/* Error */}
          {error && (
            <div className="bg-red-500/10 border border-red-500/30 rounded-xl p-4">
              <p className="text-red-400 text-sm">{error}</p>
            </div>
          )}

          {/* Rewritten result */}
          {rewrittenText && (
            <>
              <div className="space-y-2">
                <div className="flex justify-between items-center">
                  <h4 className="font-semibold text-purple-300 flex items-center gap-2">
                    <Sparkles className="h-4 w-4" />
                    AI 改写结果
                  </h4>
                  <button
                    onClick={handleApply}
                    className="text-xs bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-500 hover:to-pink-500 text-white px-3 py-1.5 rounded-lg transition-colors shadow-sm"
                  >
                    使用此结果
                  </button>
                </div>
                <div className="bg-purple-900/10 border border-purple-500/20 rounded-xl p-4 max-h-60 overflow-y-auto hide-scrollbar">
                  <p className="text-gray-200 text-sm leading-relaxed whitespace-pre-wrap">
                    {rewrittenText}
                  </p>
                </div>
              </div>

              <div className="space-y-2">
                <div className="flex justify-between items-center">
                  <h4 className="font-semibold text-gray-400 flex items-center gap-2">
                    📝 原文对比
                  </h4>
                  <button
                    onClick={onClose}
                    className="text-xs bg-white/10 hover:bg-white/20 text-white px-3 py-1.5 rounded-lg transition-colors"
                  >
                    保留原文
                  </button>
                </div>
                <div className="bg-white/5 border border-white/10 rounded-xl p-4 max-h-40 overflow-y-auto hide-scrollbar">
                  <p className="text-gray-400 text-sm leading-relaxed whitespace-pre-wrap">
                    {originalText}
                  </p>
                </div>
              </div>

              <button
                onClick={handleRetry}
                className="w-full py-2.5 px-4 bg-white/10 hover:bg-white/20 text-white rounded-xl transition-colors"
              >
                重新改写
              </button>
            </>
          )}
        </div>
    </AppModal>
  );
}
