import { useState, useEffect } from 'react';
import { Card } from '../components/common/Card';
import { Button } from '../components/common/Button';
import { Download, FileText, Image, RefreshCw } from 'lucide-react';
import { apiClient } from '../api/client';
import { Study } from '../types';

export default function Results() {
  const [studies, setStudies] = useState<Study[]>([]);
  const [selectedStudyId, setSelectedStudyId] = useState<string | null>(null);
  const [reportContent, setReportContent] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    apiClient.getStudies()
      .then(data => {
        setStudies(data.studies);
        if (data.studies.length > 0) {
          const completed = data.studies.find(s => s.status === 'completed');
          setSelectedStudyId(completed?.id || data.studies[0].id);
        }
      })
      .catch(console.error);
  }, []);

  useEffect(() => {
    if (selectedStudyId) {
      setLoading(true);
      apiClient.getStudyReport(selectedStudyId)
        .then(data => {
          setReportContent(data.content);
          setLoading(false);
        })
        .catch(err => {
          console.error('Failed to fetch report:', err);
          // Fallback for demo if report doesn't exist
          setReportContent(`# Optimization Report: ${selectedStudyId}

## Executive Summary
The optimization study successfully converged after 45 trials. The best design achieved a mass reduction of 15% while maintaining all constraints.

## Key Findings
- **Best Objective Value**: 115.185 Hz
- **Critical Parameter**: Plate Thickness (sensitivity: 0.85)
- **Constraint Margins**: All safety factors > 1.2

## Recommendations
Based on the results, we recommend proceeding with the design from Trial #45. Further refinement could be achieved by narrowing the bounds for 'thickness'.
          `);
          setLoading(false);
        });
    }
  }, [selectedStudyId]);

  const handleRegenerate = () => {
    if (!selectedStudyId) return;
    setLoading(true);
    // In a real app, this would call an endpoint to trigger report generation
    setTimeout(() => {
      setLoading(false);
    }, 2000);
  };

  return (
    <div className="container mx-auto h-[calc(100vh-100px)] flex flex-col">
      <header className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-primary-400">Results Viewer</h1>
          <p className="text-dark-300 mt-1">Analyze completed optimization studies</p>
        </div>
        <div className="flex gap-2">
          <Button 
            variant="secondary" 
            icon={<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />}
            onClick={handleRegenerate}
            disabled={loading || !selectedStudyId}
          >
            Regenerate
          </Button>
          <Button variant="secondary" icon={<Download className="w-4 h-4" />}>
            Export Data
          </Button>
        </div>
      </header>

      <div className="grid grid-cols-12 gap-6 flex-1 min-h-0">
        {/* Sidebar - Study Selection */}
        <aside className="col-span-3 flex flex-col gap-4">
          <Card title="Select Study" className="flex-1 overflow-hidden flex flex-col">
            <div className="space-y-2 overflow-y-auto flex-1 pr-2">
              {studies.map(study => (
                <button
                  key={study.id}
                  onClick={() => setSelectedStudyId(study.id)}
                  className={`w-full text-left p-3 rounded-lg transition-colors ${
                    selectedStudyId === study.id
                      ? 'bg-primary-900/30 text-primary-100 border border-primary-700/50'
                      : 'text-dark-300 hover:bg-dark-700'
                  }`}
                >
                  <div className="font-medium truncate">{study.name}</div>
                  <div className="text-xs text-dark-400 mt-1 capitalize">{study.status}</div>
                </button>
              ))}
            </div>
          </Card>
        </aside>

        {/* Main Content - Report Viewer */}
        <main className="col-span-9 flex flex-col gap-6 overflow-hidden">
          <Card className="flex-1 overflow-hidden flex flex-col">
            <div className="flex items-center justify-between border-b border-dark-600 pb-4 mb-4">
              <h2 className="text-xl font-semibold text-white flex items-center gap-2">
                <FileText className="w-5 h-5 text-primary-400" />
                Optimization Report
              </h2>
              <div className="flex gap-2">
                <button className="p-2 text-dark-300 hover:text-white hover:bg-dark-700 rounded-lg" title="View Charts">
                  <Image className="w-5 h-5" />
                </button>
              </div>
            </div>
            
            <div className="flex-1 overflow-y-auto pr-4 custom-scrollbar">
              {loading ? (
                <div className="h-full flex items-center justify-center text-dark-300">
                  <RefreshCw className="w-8 h-8 animate-spin mb-2" />
                  <span className="ml-2">Loading report...</span>
                </div>
              ) : reportContent ? (
                <div className="prose prose-invert max-w-none">
                  {/* Simple markdown rendering for now */}
                  {reportContent.split('\n').map((line, i) => {
                    if (line.startsWith('# ')) return <h1 key={i} className="text-2xl font-bold text-white mt-6 mb-4">{line.substring(2)}</h1>;
                    if (line.startsWith('## ')) return <h2 key={i} className="text-xl font-bold text-primary-200 mt-6 mb-3">{line.substring(3)}</h2>;
                    if (line.startsWith('- ')) return <li key={i} className="ml-4 text-dark-100">{line.substring(2)}</li>;
                    return <p key={i} className="text-dark-200 mb-2">{line}</p>;
                  })}
                </div>
              ) : (
                <div className="h-full flex items-center justify-center text-dark-300">
                  Select a study to view results
                </div>
              )}
            </div>
          </Card>
        </main>
      </div>
    </div>
  );
}