import { useState, useEffect } from 'react';
import axios from 'axios';
import { Plus, Clock, CheckCircle2, XCircle, ChevronRight, Trash2 } from 'lucide-react';

export default function Sidebar({ onSelectResult, onNewAssessment }) {
  const [history, setHistory] = useState([]);
  const [loading, setLoading] = useState(true);

  const fetchHistory = async () => {
    try {
      setLoading(true);
      const res = await axios.get('/api/history?limit=20');
      setHistory(res.data);
    } catch (error) {
      console.error("Failed to load history", error);
    } finally {
      setLoading(false);
    }
  };

  const handleClearHistory = async () => {
    if (window.confirm("Are you sure you want to clear all history? This action cannot be undone.")) {
      try {
        await axios.delete('/api/history');
        setHistory([]);
      } catch (error) {
        console.error("Failed to clear history", error);
        alert("Could not clear history");
      }
    }
  };

  useEffect(() => {
    fetchHistory();
  }, []);
  
  return (
    <div className="sidebar">
      <button 
        className="btn" 
        onClick={onNewAssessment} 
        style={{ width: '100%', marginBottom: '1.5rem', justifyContent: 'center' }}
      >
        <Plus size={18} /> New Assessment
      </button>

      <div style={{ fontSize: '0.85rem', fontWeight: '600', color: 'var(--text-muted)', marginBottom: '1rem', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
           <Clock size={14} /> RECENT ASSESSMENTS
        </div>
        {history.length > 0 && (
          <button 
             onClick={handleClearHistory} 
             style={{ background: 'none', border: 'none', color: 'var(--danger)', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '0.2rem', fontSize: '0.75rem', fontWeight: '600' }}
             title="Clear All History"
          >
             <Trash2 size={14} />
             Clear
          </button>
        )}
      </div>

      <div className="history-list">
        {loading ? (
          <div style={{ padding: '1rem', textAlign: 'center', color: 'var(--text-muted)' }}>Loading...</div>
        ) : history.length === 0 ? (
          <div style={{ padding: '1rem', textAlign: 'center', color: 'var(--text-muted)', fontSize: '0.9rem' }}>No history found.</div>
        ) : (
          history.map((item) => (
            <div 
              key={item.id} 
              className="history-item"
              onClick={() => onSelectResult(item)}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', marginBottom: '0.25rem' }}>
                {item.prediction === 'Y' ? (
                  <CheckCircle2 size={16} color="var(--success)" />
                ) : (
                  <XCircle size={16} color="var(--danger)" />
                )}
                <span style={{ fontWeight: '600', fontSize: '0.95rem' }}>
                  {item.prediction === 'Y' ? 'Approved' : 'Rejected'}
                </span>
              </div>
              <div style={{ fontSize: '0.8rem', color: 'var(--text-muted)', display: 'flex', justifyContent: 'space-between' }}>
                <span>Income: ${item.applicant_income}</span>
                <ChevronRight size={14} />
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}
