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

export default function PayrollDetail() {
  const [payRunId, setPayRunId] = useState('');
  const [payRun, setPayRun] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const loadPayRun = async () => {
    if (!payRunId) return;
    
    try {
      setLoading(true);
      setError(null);
      const response = await (window as any).mcp?.callTool('rippling_get_pay_run', { id: payRunId });
      
      if (response?.payRun) {
        setPayRun(response.payRun);
      } else {
        setPayRun(getSamplePayRun());
      }
    } catch (err) {
      console.error('Error:', err);
      setError(err instanceof Error ? err.message : 'Failed to load');
      setPayRun(getSamplePayRun());
    } finally {
      setLoading(false);
    }
  };

  const getSamplePayRun = () => ({
    id: payRunId || '1',
    period: '2024-01-15 to 2024-01-31',
    status: 'APPROVED',
    totalAmount: 250000,
    employeeCount: 45,
    type: 'REGULAR',
    payments: [
      { employeeName: 'John Doe', grossPay: 5000, netPay: 3800, deductions: 1200 },
      { employeeName: 'Jane Smith', grossPay: 6000, netPay: 4500, deductions: 1500 },
    ]
  });

  return (
    <div className="container">
      <div className="header">
        <h1>Payroll Detail</h1>
        <p className="subtitle">View pay run breakdown</p>
      </div>

      <div className="search-bar">
        <input
          type="text"
          placeholder="Enter pay run ID..."
          value={payRunId}
          onChange={(e) => setPayRunId(e.target.value)}
          onKeyPress={(e) => e.key === 'Enter' && loadPayRun()}
        />
        <button onClick={loadPayRun} disabled={loading || !payRunId}>
          {loading ? 'Loading...' : 'Load Pay Run'}
        </button>
      </div>

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

      {payRun && (
        <>
          <div className="stats-grid">
            <div className="stat-card">
              <div className="stat-label">Total Amount</div>
              <div className="stat-value">${payRun.totalAmount.toLocaleString()}</div>
            </div>
            <div className="stat-card">
              <div className="stat-label">Employees</div>
              <div className="stat-value">{payRun.employeeCount}</div>
            </div>
            <div className="stat-card">
              <div className="stat-label">Status</div>
              <div className="stat-value">{payRun.status}</div>
            </div>
          </div>

          <div className="card">
            <h2>Payment Details</h2>
            <table className="payment-table">
              <thead>
                <tr>
                  <th>Employee</th>
                  <th>Gross Pay</th>
                  <th>Deductions</th>
                  <th>Net Pay</th>
                </tr>
              </thead>
              <tbody>
                {payRun.payments?.map((payment: any, idx: number) => (
                  <tr key={idx}>
                    <td>{payment.employeeName}</td>
                    <td>${payment.grossPay.toLocaleString()}</td>
                    <td>${payment.deductions.toLocaleString()}</td>
                    <td className="net-pay">${payment.netPay.toLocaleString()}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      )}
    </div>
  );
}
