import React, { useState, useEffect } from 'react';

function App() {
  const [orgId, setOrgId] = useState<number>(new URLSearchParams(window.location.search).get('id') ? parseInt(new URLSearchParams(window.location.search).get('id')!) : 1);
  const [org, setOrg] = useState<any>(null);
  const [people, setPeople] = useState<any[]>([]);
  const [deals, setDeals] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadOrg();
  }, [orgId]);

  const loadOrg = async () => {
    setLoading(true);
    try {
      const orgResponse = await fetch('/mcp/pipedrive_organization_get', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: orgId })
      });
      const orgData = await orgResponse.json();
      setOrg(orgData.data);

      const peopleResponse = await fetch('/mcp/pipedrive_persons_list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ org_id: orgId })
      });
      const peopleData = await peopleResponse.json();
      setPeople(peopleData.data || []);

      const dealsResponse = await fetch('/mcp/pipedrive_deals_list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ org_id: orgId })
      });
      const dealsData = await dealsResponse.json();
      setDeals(dealsData.data || []);
    } catch (error) {
      console.error('Failed to load organization:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading || !org) {
    return <div className="loading">Loading organization...</div>;
  }

  return (
    <div className="app">
      <header className="header">
        <div>
          <h1>🏢 {org.name}</h1>
          <div className="header-meta">
            {org.address && <span>📍 {org.address}</span>}
            {org.owner_name && <span>Owner: {org.owner_name}</span>}
          </div>
        </div>
        <button onClick={loadOrg} className="refresh-btn">↻ Refresh</button>
      </header>

      <div className="metrics-grid">
        <div className="metric-card"><div className="label">People</div><div className="value">{org.people_count || 0}</div></div>
        <div className="metric-card"><div className="label">Open Deals</div><div className="value">{org.open_deals_count || 0}</div></div>
        <div className="metric-card"><div className="label">Won Deals</div><div className="value">{org.won_deals_count || 0}</div></div>
        <div className="metric-card"><div className="label">Activities</div><div className="value">{org.activities_count || 0}</div></div>
      </div>

      <div className="section">
        <h2>People ({people.length})</h2>
        <div className="list">
          {people.map(person => (
            <div key={person.id} className="list-item">
              <div className="item-title">{person.name}</div>
              <div className="item-meta">{person.email?.[0] || person.phone?.[0] || '—'}</div>
            </div>
          ))}
        </div>
      </div>

      <div className="section">
        <h2>Deals ({deals.length})</h2>
        <div className="list">
          {deals.map(deal => (
            <div key={deal.id} className="list-item">
              <div className="item-title">{deal.title}</div>
              <div className={`item-status ${deal.status}`}>{deal.status}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

export default App;
