const { useState, useEffect } = React;

function ContactDetail({ contactId }) {
  const [contact, setContact] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [showDraftModal, setShowDraftModal] = useState(false);
  const [draftSubject, setDraftSubject] = useState('');
  const [draftBody, setDraftBody] = useState('');
  const [fromIdentity, setFromIdentity] = useState('iain@gmail');
  const [interactionSummary, setInteractionSummary] = useState('');
  const [talkinPoints, setTalkingPoints] = useState([]);
  const [generatingPoints, setGeneratingPoints] = useState(false);

  useEffect(() => {
    if (!contactId) return;
    loadContact();
  }, [contactId]);

  const loadContact = async () => {
    try {
      const res = await fetch(`/api/contacts/${contactId}`);
      if (!res.ok) throw new Error('Contact not found');
      const data = await res.json();
      setContact(data);
      setLoading(false);
    } catch (err) {
      setError(err.message);
      setLoading(false);
    }
  };

  const generateTalkingPoints = async () => {
    if (!contactId) return;
    setGeneratingPoints(true);
    try {
      const res = await fetch(`/api/contacts/${contactId}/talking-points`, {
        method: 'POST',
      });
      const data = await res.json();
      setTalkingPoints(data.talking_points || []);
    } catch (err) {
      console.error('Error generating talking points:', err);
    } finally {
      setGeneratingPoints(false);
    }
  };

  const submitDraft = async () => {
    if (!draftSubject || !draftBody) {
      alert('Subject and body are required');
      return;
    }

    try {
      const res = await fetch('/api/email-drafts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          contact_id: contactId,
          subject: draftSubject,
          body: draftBody,
          from_identity: fromIdentity,
        }),
      });
      const data = await res.json();
      alert('Draft created: ' + data.status);
      setShowDraftModal(false);
      setDraftSubject('');
      setDraftBody('');
    } catch (err) {
      alert('Error creating draft: ' + err.message);
    }
  };

  const logInteraction = async () => {
    if (!interactionSummary) {
      alert('Please enter an interaction summary');
      return;
    }

    try {
      const res = await fetch(`/api/contacts/${contactId}/interactions`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          interaction_type: 'email',
          direction: 'outbound',
          channel: 'email',
          summary: interactionSummary,
        }),
      });
      const data = await res.json();
      alert('Interaction logged');
      setInteractionSummary('');
      loadContact();
    } catch (err) {
      alert('Error logging interaction: ' + err.message);
    }
  };

  if (loading) return <div className="card">Loading...</div>;
  if (error) return <div className="card" style={{ color: 'red' }}>Error: {error}</div>;
  if (!contact) return null;

  const c = contact.contact;
  const channels = contact.channels || [];
  const interactions = contact.interactions || [];
  const enrichments = contact.enrichments || [];
  const emails = channels.filter(ch => ch.channel_type === 'email').map(ch => ch.value);

  return (
    <div>
      {/* Header */}
      <div className="page-header">
        <div>
          <h1>{c.full_name}</h1>
          <div style={{ fontSize: '14px', color: '#666', marginTop: '5px' }}>
            {c.current_title} at {c.organisation} • {c.location}
          </div>
        </div>
        <span className={`tier-badge ${c.tier.toLowerCase()}`}>{c.tier}</span>
      </div>

      {/* Contact Info Card */}
      <div className="card">
        <div className="card-title">Contact Information</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
          <div>
            <div style={{ fontSize: '12px', color: '#999', marginBottom: '5px' }}>EMAIL</div>
            {emails.length > 0 ? (
              emails.map(email => (
                <div key={email} style={{ marginBottom: '8px' }}>
                  <a href={`mailto:${email}`}>{email}</a>
                </div>
              ))
            ) : (
              <div style={{ color: '#999' }}>No email</div>
            )}
          </div>
          <div>
            <div style={{ fontSize: '12px', color: '#999', marginBottom: '5px' }}>STATUS</div>
            <div>
              <span style={{
                display: 'inline-block',
                padding: '4px 8px',
                backgroundColor: c.warmth_status === 'warm' ? '#d4edda' : c.warmth_status === 'cooling' ? '#fff3cd' : '#f8d7da',
                color: c.warmth_status === 'warm' ? '#155724' : c.warmth_status === 'cooling' ? '#856404' : '#721c24',
                borderRadius: '4px',
                fontSize: '12px',
              }}>
                {c.warmth_status}
              </span>
            </div>
            <div style={{ marginTop: '10px', fontSize: '12px', color: '#999' }}>
              Last contacted: {c.last_contacted ? new Date(c.last_contacted).toLocaleDateString() : 'Never'}
            </div>
            <div style={{ fontSize: '12px', color: '#999' }}>
              Next due: {c.next_due_date ? new Date(c.next_due_date).toLocaleDateString() : 'None'}
            </div>
          </div>
        </div>
      </div>

      {/* Talking Points (from web/news) */}
      <div className="card">
        <div className="card-title">
          Talking Points
          <button
            onClick={generateTalkingPoints}
            disabled={generatingPoints}
            style={{ float: 'right', marginTop: '-5px' }}
            className="btn btn-secondary"
          >
            {generatingPoints ? 'Generating...' : 'Generate New'}
          </button>
        </div>
        {talkinPoints.length > 0 ? (
          talkinPoints.map((point, idx) => (
            <div key={idx} style={{ padding: '12px 0', borderBottom: '1px solid #f0f0f0' }}>
              <div style={{ fontWeight: 500, marginBottom: '4px' }}>{point.headline}</div>
              <div style={{ fontSize: '13px', color: '#666', marginBottom: '8px' }}>{point.summary}</div>
              <a href={point.source_url} target="_blank" rel="noopener noreferrer" style={{ fontSize: '12px', color: '#4d96ff' }}>
                View source →
              </a>
            </div>
          ))
        ) : (
          <p style={{ color: '#999', fontSize: '13px' }}>No talking points yet. Click "Generate New" to fetch recent news and updates.</p>
        )}
      </div>

      {/* Email Drafting */}
      <div className="card">
        <div className="card-title">Draft Email</div>
        <button onClick={() => setShowDraftModal(true)} className="btn btn-primary">
          + New Draft
        </button>
      </div>

      {/* Interactions / History */}
      <div className="card">
        <div className="card-title">Interaction History</div>
        {interactions.length === 0 ? (
          <p style={{ color: '#999', fontSize: '13px' }}>No interactions logged yet</p>
        ) : (
          interactions.map(interaction => (
            <div key={interaction.id} style={{ padding: '12px 0', borderBottom: '1px solid #f0f0f0' }}>
              <div style={{ fontWeight: 500, fontSize: '13px' }}>
                {interaction.summary}
              </div>
              <div style={{ fontSize: '12px', color: '#999', marginTop: '4px' }}>
                {interaction.interaction_type} • {new Date(interaction.date).toLocaleDateString()}
              </div>
            </div>
          ))
        )}
      </div>

      {/* Log Interaction */}
      <div className="card">
        <div className="card-title">Log New Interaction</div>
        <div className="form-group">
          <textarea
            placeholder="Summary of the interaction (email sent, call, meeting, etc.)"
            value={interactionSummary}
            onChange={(e) => setInteractionSummary(e.target.value)}
          />
        </div>
        <button onClick={logInteraction} className="btn btn-primary">Log Interaction</button>
      </div>

      {/* Draft Modal */}
      {showDraftModal && (
        <div className="modal active">
          <div className="modal-content">
            <div className="modal-close" onClick={() => setShowDraftModal(false)}>×</div>
            <h2>Draft Email to {c.full_name}</h2>

            {/* Suggest talking points in draft */}
            {talkinPoints.length > 0 && (
              <div style={{ backgroundColor: '#f0f4ff', padding: '10px', borderRadius: '4px', marginBottom: '15px', fontSize: '12px' }}>
                <strong>Suggested talking points:</strong>
                <ul style={{ marginTop: '5px', paddingLeft: '20px' }}>
                  {talkinPoints.slice(0, 2).map((point, idx) => (
                    <li key={idx}>{point.headline}</li>
                  ))}
                </ul>
              </div>
            )}

            <div className="form-group">
              <label>From</label>
              <select value={fromIdentity} onChange={(e) => setFromIdentity(e.target.value)}>
                <option value="iain@gmail">iain@gmail.com</option>
                <option value="iain@icra.travel">iain@icra.travel</option>
              </select>
            </div>

            <div className="form-group">
              <label>Subject</label>
              <input
                type="text"
                value={draftSubject}
                onChange={(e) => setDraftSubject(e.target.value)}
                placeholder="Email subject"
              />
            </div>

            <div className="form-group">
              <label>Body</label>
              <textarea
                value={draftBody}
                onChange={(e) => setDraftBody(e.target.value)}
                placeholder="Email body"
              />
            </div>

            <div style={{ display: 'flex', gap: '10px' }}>
              <button onClick={submitDraft} className="btn btn-primary">Create Draft</button>
              <button onClick={() => setShowDraftModal(false)} className="btn btn-secondary">Cancel</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

