import { useState, useEffect } from 'react';
import './styles.css';

export default function AtsPipeline() {
  const [candidates, setCandidates] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  const loadCandidates = async () => {
    try {
      setLoading(true);
      const response = await (window as any).mcp?.callTool('rippling_list_candidates', { limit: 100 });
      
      if (response?.candidates) {
        setCandidates(response.candidates);
      } else {
        setCandidates(getSampleCandidates());
      }
    } catch (err) {
      console.error('Error:', err);
      setError(err instanceof Error ? err.message : 'Failed to load');
      setCandidates(getSampleCandidates());
    } finally {
      setLoading(false);
    }
  };

  const getSampleCandidates = () => [
    { id: '1', name: 'Alice Johnson', position: 'Software Engineer', stage: 'PHONE_SCREEN', email: 'alice@example.com' },
    { id: '2', name: 'Bob Smith', position: 'Product Manager', stage: 'ONSITE', email: 'bob@example.com' },
    { id: '3', name: 'Carol Davis', position: 'Designer', stage: 'OFFER', email: 'carol@example.com' },
    { id: '4', name: 'David Lee', position: 'Software Engineer', stage: 'TECHNICAL', email: 'david@example.com' },
  ];

  const stages = ['APPLIED', 'PHONE_SCREEN', 'TECHNICAL', 'ONSITE', 'OFFER', 'HIRED'];

  const getCandidatesByStage = (stage: string) => {
    return candidates.filter(c => c.stage === stage);
  };

  if (loading) {
    return <div className="container"><div className="loading">Loading pipeline...</div></div>;
  }

  return (
    <div className="container">
      <div className="header">
        <h1>ATS Pipeline</h1>
        <p className="subtitle">{candidates.length} active candidates</p>
      </div>

      {error && <div className="error">{error}</div>}

      <div className="pipeline">
        {stages.map(stage => (
          <div key={stage} className="pipeline-column">
            <div className="column-header">
              <h3>{stage.replace('_', ' ')}</h3>
              <span className="count">{getCandidatesByStage(stage).length}</span>
            </div>
            <div className="candidate-list">
              {getCandidatesByStage(stage).map(candidate => (
                <div key={candidate.id} className="candidate-card">
                  <h4>{candidate.name}</h4>
                  <p className="position">{candidate.position}</p>
                  <p className="email">{candidate.email}</p>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
