import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card } from '../components/common/Card';
import { Button } from '../components/common/Button';
import {
  Download,
  FileText,
  RefreshCw,
  Sparkles,
  Loader2,
  AlertTriangle,
  CheckCircle,
  Copy
} from 'lucide-react';
import { apiClient } from '../api/client';
import { useStudy } from '../context/StudyContext';
import ReactMarkdown from 'react-markdown';

export default function Results() {
  const { selectedStudy } = useStudy();
  const navigate = useNavigate();
  const [reportContent, setReportContent] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [generating, setGenerating] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);
  const [lastGenerated, setLastGenerated] = useState<string | null>(null);

  // Redirect if no study selected
  useEffect(() => {
    if (!selectedStudy) {
      navigate('/');
    }
  }, [selectedStudy, navigate]);

  // Load report when study changes
  useEffect(() => {
    if (selectedStudy) {
      loadReport();
    }
  }, [selectedStudy]);

  const loadReport = async () => {
    if (!selectedStudy) return;

    setLoading(true);
    setError(null);

    try {
      const data = await apiClient.getStudyReport(selectedStudy.id);
      setReportContent(data.content);
      if (data.generated_at) {
        setLastGenerated(data.generated_at);
      }
    } catch (err: any) {
      // No report yet - show placeholder
      setReportContent(null);
    } finally {
      setLoading(false);
    }
  };

  const handleGenerate = async () => {
    if (!selectedStudy) return;

    setGenerating(true);
    setError(null);

    try {
      const data = await apiClient.generateReport(selectedStudy.id);
      setReportContent(data.content);
      if (data.generated_at) {
        setLastGenerated(data.generated_at);
      }
    } catch (err: any) {
      setError(err.message || 'Failed to generate report');
    } finally {
      setGenerating(false);
    }
  };

  const handleCopy = async () => {
    if (reportContent) {
      await navigator.clipboard.writeText(reportContent);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  const handleDownload = () => {
    if (!reportContent || !selectedStudy) return;

    const blob = new Blob([reportContent], { type: 'text/markdown' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${selectedStudy.id}_report.md`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  if (!selectedStudy) {
    return null;
  }

  return (
    <div className="h-full flex flex-col">
      {/* Header */}
      <header className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Optimization Report</h1>
          <p className="text-dark-400 mt-1">{selectedStudy.name}</p>
        </div>
        <div className="flex gap-2">
          <Button
            variant="primary"
            icon={generating ? <Loader2 className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4" />}
            onClick={handleGenerate}
            disabled={generating}
          >
            {generating ? 'Generating...' : reportContent ? 'Update Report' : 'Generate Report'}
          </Button>
          {reportContent && (
            <>
              <Button
                variant="secondary"
                icon={copied ? <CheckCircle className="w-4 h-4 text-green-400" /> : <Copy className="w-4 h-4" />}
                onClick={handleCopy}
              >
                {copied ? 'Copied!' : 'Copy'}
              </Button>
              <Button
                variant="secondary"
                icon={<Download className="w-4 h-4" />}
                onClick={handleDownload}
              >
                Download
              </Button>
            </>
          )}
        </div>
      </header>

      {/* Error Message */}
      {error && (
        <div className="mb-4 p-4 bg-red-900/20 border border-red-800/30 rounded-lg">
          <div className="flex items-center gap-2 text-red-400">
            <AlertTriangle className="w-5 h-5" />
            <span>{error}</span>
          </div>
        </div>
      )}

      {/* Main Content */}
      <div className="flex-1 min-h-0">
        <Card className="h-full overflow-hidden flex flex-col">
          <div className="flex items-center justify-between border-b border-dark-600 pb-4 mb-4">
            <h2 className="text-lg font-semibold text-white flex items-center gap-2">
              <FileText className="w-5 h-5 text-primary-400" />
              Report Content
            </h2>
            {lastGenerated && (
              <span className="text-xs text-dark-400">
                Last generated: {new Date(lastGenerated).toLocaleString()}
              </span>
            )}
          </div>

          <div className="flex-1 overflow-y-auto pr-4 custom-scrollbar">
            {loading ? (
              <div className="h-full flex flex-col items-center justify-center text-dark-300">
                <RefreshCw className="w-8 h-8 animate-spin mb-3" />
                <span>Loading report...</span>
              </div>
            ) : reportContent ? (
              <div className="prose prose-invert prose-sm max-w-none
                              prose-headings:text-white prose-headings:font-semibold
                              prose-p:text-dark-300 prose-strong:text-white
                              prose-code:text-primary-400 prose-code:bg-dark-700 prose-code:px-1 prose-code:rounded
                              prose-pre:bg-dark-700 prose-pre:border prose-pre:border-dark-600
                              prose-a:text-primary-400 prose-a:no-underline hover:prose-a:underline
                              prose-ul:text-dark-300 prose-ol:text-dark-300
                              prose-li:text-dark-300
                              prose-table:border-collapse prose-th:border prose-th:border-dark-600 prose-th:p-2 prose-th:bg-dark-700
                              prose-td:border prose-td:border-dark-600 prose-td:p-2
                              prose-hr:border-dark-600">
                <ReactMarkdown>{reportContent}</ReactMarkdown>
              </div>
            ) : (
              <div className="h-full flex flex-col items-center justify-center text-dark-400">
                <FileText className="w-16 h-16 mb-4 opacity-50" />
                <h3 className="text-lg font-medium text-dark-300 mb-2">No Report Generated</h3>
                <p className="text-sm text-center mb-6 max-w-md">
                  Click "Generate Report" to create an AI-generated analysis of your optimization results.
                </p>
                <Button
                  variant="primary"
                  icon={<Sparkles className="w-4 h-4" />}
                  onClick={handleGenerate}
                  disabled={generating}
                >
                  Generate Report
                </Button>
              </div>
            )}
          </div>
        </Card>
      </div>

      {/* Study Stats */}
      <div className="mt-4 grid grid-cols-4 gap-4">
        <div className="bg-dark-800 rounded-lg p-4 border border-dark-600">
          <div className="text-xs text-dark-400 uppercase mb-1">Total Trials</div>
          <div className="text-2xl font-bold text-white">{selectedStudy.progress.current}</div>
        </div>
        <div className="bg-dark-800 rounded-lg p-4 border border-dark-600">
          <div className="text-xs text-dark-400 uppercase mb-1">Best Value</div>
          <div className="text-2xl font-bold text-primary-400">
            {selectedStudy.best_value?.toFixed(4) || 'N/A'}
          </div>
        </div>
        <div className="bg-dark-800 rounded-lg p-4 border border-dark-600">
          <div className="text-xs text-dark-400 uppercase mb-1">Target</div>
          <div className="text-2xl font-bold text-dark-300">
            {selectedStudy.target?.toFixed(4) || 'N/A'}
          </div>
        </div>
        <div className="bg-dark-800 rounded-lg p-4 border border-dark-600">
          <div className="text-xs text-dark-400 uppercase mb-1">Status</div>
          <div className={`text-lg font-bold capitalize ${
            selectedStudy.status === 'completed' ? 'text-green-400' :
            selectedStudy.status === 'running' ? 'text-blue-400' : 'text-dark-400'
          }`}>
            {selectedStudy.status}
          </div>
        </div>
      </div>
    </div>
  );
}
