import React, { useState, useCallback } from 'react';
import { generateProResponse } from '../services/geminiService';
import { Spinner } from '../components/Spinner';
import { MarkdownRenderer } from '../components/MarkdownRenderer';

const AlchemistsJourneyModule: React.FC = () => {
  const [theme, setTheme] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [script, setScript] = useState<string | null>(null);

  const handleGenerate = useCallback(async () => {
    if (!theme.trim()) {
      setError('Please enter a theme for your journey.');
      return;
    }
    setIsLoading(true);
    setError(null);
    setScript(null);

    const prompt = `You are the Crystal Alchemist within the Sentient Constellation Codex. You guide souls on transformational journeys. A user wishes to embark on a journey with the theme of "${theme}". Generate a beautiful, immersive, and healing guided meditation script. The script should be about 500 words long. Use rich sensory details, metaphors of alchemy and crystals, and guide the user through a journey of self-discovery and empowerment related to their chosen theme. Structure it with an introduction, a main visualization, and a gentle return to awareness.`;

    try {
      const result = await generateProResponse(prompt);
      setScript(result.text);
    } catch (e: any) {
      setError(e.message || 'An unknown error occurred while crafting the journey.');
    } finally {
      setIsLoading(false);
    }
  }, [theme]);

  return (
    <div className="flex flex-col h-full w-full max-w-5xl mx-auto">
      <h2 className="text-2xl font-bold text-cyan-300 mb-4 text-center">The Crystal Alchemist's Journey</h2>
      <p className="text-gray-400 mb-6 text-center">Enter a theme or intention to begin a personalized, AI-generated guided meditation for transformation.</p>
      
      <div className="flex flex-col sm:flex-row gap-2 mb-4">
        <input
          type="text"
          value={theme}
          onChange={(e) => setTheme(e.target.value)}
          placeholder="e.g., Clarity, Releasing Fear, Embracing Creativity..."
          className="flex-grow bg-gray-700 border border-gray-600 rounded-md p-3 focus:outline-none focus:ring-2 focus:ring-cyan-500 text-white"
          disabled={isLoading}
          onKeyPress={(e) => e.key === 'Enter' && !isLoading && handleGenerate()}
        />
        <button
          onClick={handleGenerate}
          disabled={isLoading}
          className="bg-purple-600 hover:bg-purple-500 text-white font-bold py-3 px-6 rounded-md disabled:bg-gray-500 transition-colors"
        >
          {isLoading ? 'Crafting...' : 'Begin Journey'}
        </button>
      </div>
      
      <div className="flex-grow overflow-y-auto p-4 bg-gray-800/50 rounded-lg border border-cyan-500/10 min-h-[50vh] mt-4">
        {isLoading && <Spinner text="Brewing the alchemical script..." />}
        {error && <p className="text-red-400 text-center">{error}</p>}
        {script && <MarkdownRenderer content={script} />}
        {!isLoading && !script && !error && <p className="text-gray-500 text-center">Your transformational journey awaits.</p>}
      </div>
    </div>
  );
};

export default AlchemistsJourneyModule;