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

interface Person {
  id: number;
  name: string;
  email: string[];
  phone: string[];
  org_name?: string;
  owner_name?: string;
  open_deals_count: number;
  closed_deals_count: number;
  won_deals_count: number;
  lost_deals_count: number;
  activities_count: number;
  add_time: string;
}

function App() {
  const [personId, setPersonId] = useState<number>(new URLSearchParams(window.location.search).get('id') ? parseInt(new URLSearchParams(window.location.search).get('id')!) : 1);
  const [person, setPerson] = useState<Person | null>(null);
  const [deals, setDeals] = useState<any[]>([]);
  const [activities, setActivities] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadPerson();
  }, [personId]);

  const loadPerson = async () => {
    setLoading(true);
    try {
      const response = await fetch('/mcp/pipedrive_person_get', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: personId })
      });
      const data = await response.json();
      setPerson(data.data);

      const dealsResponse = await fetch('/mcp/pipedrive_deals_list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ person_id: personId })
      });
      const dealsData = await dealsResponse.json();
      setDeals(dealsData.data || []);

      const activitiesResponse = await fetch('/mcp/pipedrive_activities_list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ person_id: personId })
      });
      const activitiesData = await activitiesResponse.json();
      setActivities(activitiesData.data || []);
    } catch (error) {
      console.error('Failed to load person:', error);
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <div className="app">
      <header className="header">
        <div>
          <h1>👤 {person.name}</h1>
          <div className="header-meta">
            {person.org_name && <span>🏢 {person.org_name}</span>}
            {person.owner_name && <span>Owner: {person.owner_name}</span>}
          </div>
        </div>
        <button onClick={loadPerson} className="refresh-btn">↻ Refresh</button>
      </header>

      <div className="contact-card">
        <div className="contact-section">
          <h3>📧 Email</h3>
          {person.email.map((e, i) => <div key={i}><a href={`mailto:${e}`}>{e}</a></div>)}
        </div>
        <div className="contact-section">
          <h3>📞 Phone</h3>
          {person.phone.map((p, i) => <div key={i}><a href={`tel:${p}`}>{p}</a></div>)}
        </div>
      </div>

      <div className="metrics-grid">
        <div className="metric-card"><div className="label">Open Deals</div><div className="value">{person.open_deals_count}</div></div>
        <div className="metric-card"><div className="label">Won Deals</div><div className="value">{person.won_deals_count}</div></div>
        <div className="metric-card"><div className="label">Lost Deals</div><div className="value">{person.lost_deals_count}</div></div>
        <div className="metric-card"><div className="label">Activities</div><div className="value">{person.activities_count}</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 className="section">
        <h2>Activities ({activities.length})</h2>
        <div className="list">
          {activities.map(activity => (
            <div key={activity.id} className="list-item">
              <div className="item-title">{activity.subject}</div>
              <div className="item-meta">{activity.type}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

export default App;
