import React, { useState, useEffect } from 'react';
import { getChallenges, Challenge } from '../api/client';
import { MarkdownView } from '../components/MarkdownView';
import { BookOpen, ArrowRight, Code, ShieldCheck, Sparkles, X, Save, Layers } from 'lucide-react';

interface DashboardProps {
  onSelectChallenge: (id: string) => void;
}

const Dashboard: React.FC<DashboardProps> = ({ onSelectChallenge }) => {
  const [challenges, setChallenges] = useState<Challenge[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Generator Modal state
  const [isGenModalOpen, setIsGenModalOpen] = useState(false);
  const [promptText, setPromptText] = useState('');
  const [genLanguage, setGenLanguage] = useState('Python');
  const [genDifficulty, setGenDifficulty] = useState('Medium');
  const [genSubject, setGenSubject] = useState('General Concepts');
  const [genMarkdown, setGenMarkdown] = useState('');
  const [genFilename, setGenFilename] = useState('');
  const [isGenerating, setIsGenerating] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [genStatusMsg, setGenStatusMsg] = useState('');

  const fetchChallengesList = () => {
    setLoading(true);
    getChallenges()
      .then(setChallenges)
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  };

  useEffect(() => {
    fetchChallengesList();
  }, []);

  const handleGenerateAI = async () => {
    if (!promptText.trim()) {
      setGenStatusMsg('Please enter a prompt for the AI generator.');
      return;
    }

    setIsGenerating(true);
    setGenStatusMsg('⏳ Generating challenge via LLM backend...');

    try {
      const apiHost = typeof window !== 'undefined' && window.location.hostname ? window.location.hostname : '127.0.0.1';
      const response = await fetch(`http://${apiHost}:8000/challenges/generate`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          prompt: promptText,
          language: genLanguage,
          difficulty: genDifficulty,
          subject: genSubject,
        }),
      });

      if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
      }

      const res = await response.json();
      if (res.status === 'success') {
        setGenMarkdown(res.markdown);
        setGenFilename(res.filename);
        setGenStatusMsg(`✓ Challenge generated: '${res.title}'`);
      } else {
        setGenStatusMsg(`✗ Failed: ${res.message}`);
      }
    } catch (err: any) {
      setGenStatusMsg(`✗ Error generating challenge: ${err.message}`);
    } finally {
      setIsGenerating(false);
    }
  };

  const handleSaveChallenge = async () => {
    if (!genFilename.trim() || !genMarkdown.trim()) {
      setGenStatusMsg('Please provide a filename and markdown content.');
      return;
    }

    setIsSaving(true);
    setGenStatusMsg('Saving challenge to disk...');

    try {
      const apiHost = typeof window !== 'undefined' && window.location.hostname ? window.location.hostname : '127.0.0.1';
      const response = await fetch(`http://${apiHost}:8000/challenges/save`, {

        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          filename: genFilename,
          markdown: genMarkdown,
        }),
      });

      if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
      }

      const res = await response.json();
      if (res.status === 'success') {
        setGenStatusMsg(`✓ Saved challenge to ${res.filename}`);
        fetchChallengesList(); // Refresh dashboard list
      } else {
        setGenStatusMsg(`✗ Save failed: ${res.message}`);
      }
    } catch (err: any) {
      setGenStatusMsg(`✗ Error saving challenge: ${err.message}`);
    } finally {
      setIsSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen bg-darkBg text-gray-300">
        <div className="flex flex-col items-center gap-3">
          <div className="w-8 h-8 border-4 border-blue-500 border-t-transparent rounded-full animate-spin" />
          <p className="font-medium text-sm">Loading TactiTerm Challenges...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-screen bg-darkBg text-red-400">
        <div className="p-6 bg-darkSurface border border-red-900/50 rounded-xl text-center max-w-md">
          <p className="font-bold mb-2">Failed to load challenges</p>
          <p className="text-xs text-gray-400 mb-4">{error}</p>
          <button
            onClick={() => window.location.reload()}
            className="px-4 py-2 bg-blue-600 text-white text-xs font-semibold rounded-lg hover:bg-blue-500"
          >
            Retry Connection
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-darkBg text-gray-100 p-8 flex flex-col justify-between">
      <div>
        <header className="max-w-6xl mx-auto mb-10 flex justify-between items-center border-b border-darkBorder pb-6">
          <div>
            <h1 className="text-3xl font-extrabold text-white tracking-tight flex items-center gap-3">
              <Code className="text-blue-500" size={32} />
              TactiTerm Workspace
            </h1>
            <p className="text-gray-400 text-sm mt-1">
              Build programming confidence from scratch with interactive AI guidance
            </p>
          </div>
          <div className="flex items-center gap-2 px-3 py-1.5 bg-darkSurface border border-darkBorder rounded-full text-xs text-gray-300">
            <ShieldCheck size={14} className="text-green-400" />
            <span>Local Engine Active (10 Languages)</span>
          </div>
        </header>

        <main className="max-w-6xl mx-auto">
          <h2 className="text-xl font-bold text-gray-200 mb-6">Select a Challenge</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {challenges.map((c) => {
              const cid = c.id || c.challenge_id;
              return (
                <div
                  key={cid}
                  onClick={() => onSelectChallenge(cid)}
                  className="group p-6 bg-darkSurface border border-darkBorder rounded-2xl hover:border-blue-500/80 hover:shadow-xl hover:shadow-blue-500/10 cursor-pointer transition-all duration-200 flex flex-col justify-between"
                >
                  <div>
                    <div className="flex justify-between items-start mb-4">
                      <div className="p-2.5 bg-blue-500/10 border border-blue-500/20 rounded-xl text-blue-400">
                        <BookOpen size={20} />
                      </div>
                      <div className="flex items-center gap-2">
                        <span className="px-2.5 py-0.5 bg-gray-800 text-gray-300 text-[10px] uppercase font-bold rounded-md tracking-wider border border-gray-700">
                          {c.language}
                        </span>
                        <span
                          className={`px-2.5 py-0.5 text-[10px] uppercase font-bold rounded-md tracking-wider border ${
                            c.difficulty.toLowerCase() === 'easy'
                              ? 'bg-green-500/10 text-green-400 border-green-500/20'
                              : c.difficulty.toLowerCase() === 'medium'
                              ? 'bg-amber-500/10 text-amber-400 border-amber-500/20'
                              : 'bg-red-500/10 text-red-400 border-red-500/20'
                          }`}
                        >
                          {c.difficulty}
                        </span>
                      </div>
                    </div>

                    <h3 className="text-lg font-bold text-white group-hover:text-blue-400 transition-colors mb-2">
                      {c.name}
                    </h3>
                    <div className="flex items-center gap-1.5 text-xs text-amber-400 font-semibold mb-2">
                      <Layers size={13} />
                      <span>{c.subject || 'General Concepts'}</span>
                    </div>
                    <p className="text-gray-400 text-xs line-clamp-3 leading-relaxed">
                      {c.description}
                    </p>
                  </div>

                  <div className="mt-6 pt-4 border-t border-darkBorder/50 flex justify-between items-center text-xs font-semibold text-blue-400 group-hover:translate-x-1 transition-transform">
                    <span>Start Challenge</span>
                    <ArrowRight size={14} />
                  </div>
                </div>
              );
            })}
          </div>
        </main>
      </div>

      {/* Footer Generator Action Section */}
      <footer className="max-w-6xl mx-auto w-full mt-12 pt-6 border-t border-darkBorder flex justify-between items-center">
        <p className="text-xs text-gray-500">TactiTerm Software Engineering Tutor</p>
        <button
          onClick={() => setIsGenModalOpen(true)}
          className="px-6 py-3 bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-400 hover:to-amber-500 text-white font-bold text-xs rounded-xl shadow-lg shadow-amber-500/20 transition-all flex items-center gap-2"
        >
          <Sparkles size={16} />
          <span>Generate New Challenge with AI</span>
        </button>
      </footer>

      {/* AI Challenge Generator Modal */}
      {isGenModalOpen && (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center p-6 z-50">
          <div className="bg-darkSurface border border-darkBorder rounded-2xl w-full max-w-5xl h-[85vh] flex flex-col overflow-hidden shadow-2xl">
            {/* Modal Header */}
            <div className="p-4 border-b border-darkBorder bg-darkBg flex justify-between items-center">
              <h2 className="text-base font-bold text-amber-400 flex items-center gap-2">
                <Sparkles size={18} /> AI Challenge Generator (GenTUI Web)
              </h2>
              <button
                onClick={() => setIsGenModalOpen(false)}
                className="p-1 hover:bg-gray-800 text-gray-400 hover:text-white rounded-lg"
              >
                <X size={20} />
              </button>
            </div>

            {/* Modal Body */}
            <div className="flex flex-1 overflow-hidden">
              {/* Controls Column */}
              <div className="w-1/3 p-5 border-r border-darkBorder bg-darkBg flex flex-col gap-4 overflow-y-auto">
                <div>
                  <label className="block text-xs font-bold text-gray-300 mb-1">AI Prompt:</label>
                  <textarea
                    value={promptText}
                    onChange={(e) => setPromptText(e.target.value)}
                    placeholder="e.g. Medium difficulty Rust challenge on Borrowing & References"
                    className="w-full h-24 bg-darkSurface border border-darkBorder rounded-xl p-3 text-xs text-gray-200 placeholder-gray-500 focus:outline-none focus:border-amber-500 resize-none font-sans"
                  />
                </div>

                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-xs font-bold text-gray-300 mb-1">Language:</label>
                    <select
                      value={genLanguage}
                      onChange={(e) => setGenLanguage(e.target.value)}
                      className="w-full bg-darkSurface border border-darkBorder text-gray-200 text-xs rounded-lg p-2 focus:outline-none focus:border-amber-500"
                    >
                      {['Python', 'C#', 'C++', 'Java', 'JavaScript', 'TypeScript', 'Rust', 'Lua', 'HTML', 'Go'].map(
                        (lang) => (
                          <option key={lang} value={lang}>
                            {lang}
                          </option>
                        )
                      )}
                    </select>
                  </div>

                  <div>
                    <label className="block text-xs font-bold text-gray-300 mb-1">Difficulty:</label>
                    <select
                      value={genDifficulty}
                      onChange={(e) => setGenDifficulty(e.target.value)}
                      className="w-full bg-darkSurface border border-darkBorder text-gray-200 text-xs rounded-lg p-2 focus:outline-none focus:border-amber-500"
                    >
                      {['Easy', 'Medium', 'Hard', 'Advanced'].map((diff) => (
                        <option key={diff} value={diff}>
                          {diff}
                        </option>
                      ))}
                    </select>
                  </div>
                </div>

                <div>
                  <label className="block text-xs font-bold text-gray-300 mb-1">Subject / Topic:</label>
                  <input
                    type="text"
                    value={genSubject}
                    onChange={(e) => setGenSubject(e.target.value)}
                    placeholder="e.g. Memory Management, Data Structures"
                    className="w-full bg-darkSurface border border-darkBorder rounded-lg p-2 text-xs text-gray-200 focus:outline-none focus:border-amber-500"
                  />
                </div>

                <button
                  onClick={handleGenerateAI}
                  disabled={isGenerating}
                  className="w-full py-2.5 bg-amber-600 hover:bg-amber-500 disabled:opacity-50 text-white font-bold text-xs rounded-xl shadow-md transition-all flex items-center justify-center gap-2 mt-2"
                >
                  {isGenerating ? (
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                  ) : (
                    <Sparkles size={16} />
                  )}
                  <span>Generate with AI</span>
                </button>

                <hr className="border-darkBorder my-1" />

                <div>
                  <label className="block text-xs font-bold text-gray-300 mb-1">Filename (.md):</label>
                  <input
                    type="text"
                    value={genFilename}
                    onChange={(e) => setGenFilename(e.target.value)}
                    placeholder="007-new-challenge.md"
                    className="w-full bg-darkSurface border border-darkBorder rounded-lg p-2 text-xs text-gray-200 focus:outline-none focus:border-amber-500"
                  />
                </div>

                <button
                  onClick={handleSaveChallenge}
                  disabled={isSaving || !genMarkdown.trim() || !genFilename.trim()}
                  className="w-full py-2.5 bg-green-600 hover:bg-green-500 disabled:opacity-50 text-white font-bold text-xs rounded-xl shadow-md transition-all flex items-center justify-center gap-2"
                >
                  {isSaving ? (
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                  ) : (
                    <Save size={16} />
                  )}
                  <span>Save Challenge to Disk</span>
                </button>

                {genStatusMsg && (
                  <p className="text-xs text-amber-300 font-mono bg-amber-950/30 p-2.5 rounded-lg border border-amber-800/40">
                    {genStatusMsg}
                  </p>
                )}
              </div>

              {/* Raw Editor & Preview Column */}
              <div className="w-2/3 flex flex-col bg-[#1e1e1e] overflow-hidden">
                <div className="grid grid-cols-2 flex-1 overflow-hidden">
                  {/* Markdown Editor */}
                  <div className="flex flex-col border-r border-darkBorder p-4 overflow-hidden">
                    <h3 className="text-xs font-bold uppercase tracking-wider text-gray-400 mb-2">Raw Markdown (.md) Editor</h3>
                    <textarea
                      value={genMarkdown}
                      onChange={(e) => setGenMarkdown(e.target.value)}
                      placeholder="# Challenge: Title..."
                      className="w-full flex-1 bg-black/50 border border-darkBorder rounded-xl p-3 text-xs text-emerald-300 font-mono focus:outline-none resize-none"
                    />
                  </div>

                  {/* Rendered Preview */}
                  <div className="flex flex-col p-4 bg-darkBg overflow-y-auto">
                    <h3 className="text-xs font-bold uppercase tracking-wider text-blue-400 mb-2">Live Rendered Preview</h3>
                    <div className="flex-1 p-3 bg-darkSurface border border-darkBorder rounded-xl">
                      <MarkdownView content={genMarkdown || '*Generated preview will appear here...*'} />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Dashboard;
