const { useState } = React;

function NewContact({ onContactCreated }) {
  const [formData, setFormData] = useState({
    full_name: '',
    preferred_name: '',
    current_title: '',
    organisation: '',
    seniority_band: 'Mid',
    sector: '',
    location: '',
    country: '',
    tier: 'Prospect',
    warmth_status: 'warm',
    how_we_met: '',
    strategic_context: '',
    emails: [''],
    phones: [''],
    linkedin_url: '',
  });

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const handleChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleEmailChange = (index, value) => {
    const newEmails = [...formData.emails];
    newEmails[index] = value;
    setFormData(prev => ({ ...prev, emails: newEmails }));
  };

  const handlePhoneChange = (index, value) => {
    const newPhones = [...formData.phones];
    newPhones[index] = value;
    setFormData(prev => ({ ...prev, phones: newPhones }));
  };

  const addEmail = () => {
    setFormData(prev => ({ ...prev, emails: [...prev.emails, ''] }));
  };

  const addPhone = () => {
    setFormData(prev => ({ ...prev, phones: [...prev.phones, ''] }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!formData.full_name || !formData.organisation) {
      setError('Full name and organisation are required');
      return;
    }

    setLoading(true);
    setError(null);

    try {
      const payload = {
        ...formData,
        emails: formData.emails.filter(e => e.trim()),
        phones: formData.phones.filter(p => p.trim()),
      };

      const res = await fetch('/api/contacts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      if (!res.ok) throw new Error('Failed to create contact');

      const data = await res.json();
      alert('Contact created successfully');
      onContactCreated();
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <div className="page-header">
        <h1>Add New Contact</h1>
      </div>

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

      <form onSubmit={handleSubmit}>
        <div className="card">
          <div className="card-title">Core Information</div>

          <div className="form-group">
            <label>Full Name *</label>
            <input
              type="text"
              required
              value={formData.full_name}
              onChange={(e) => handleChange('full_name', e.target.value)}
              placeholder="e.g. John Smith"
            />
          </div>

          <div className="form-group">
            <label>Preferred Name</label>
            <input
              type="text"
              value={formData.preferred_name}
              onChange={(e) => handleChange('preferred_name', e.target.value)}
              placeholder="e.g. John"
            />
          </div>

          <div className="form-group">
            <label>Organisation *</label>
            <input
              type="text"
              required
              value={formData.organisation}
              onChange={(e) => handleChange('organisation', e.target.value)}
              placeholder="e.g. Booking Holdings"
            />
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '15px' }}>
            <div className="form-group">
              <label>Current Title</label>
              <input
                type="text"
                value={formData.current_title}
                onChange={(e) => handleChange('current_title', e.target.value)}
                placeholder="e.g. VP Commercial"
              />
            </div>

            <div className="form-group">
              <label>Seniority Band</label>
              <select value={formData.seniority_band} onChange={(e) => handleChange('seniority_band', e.target.value)}>
                <option value="Junior">Junior</option>
                <option value="Mid">Mid</option>
                <option value="Senior">Senior</option>
                <option value="Director">Director</option>
                <option value="C-Suite">C-Suite</option>
              </select>
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '15px' }}>
            <div className="form-group">
              <label>Location</label>
              <input
                type="text"
                value={formData.location}
                onChange={(e) => handleChange('location', e.target.value)}
                placeholder="e.g. London"
              />
            </div>

            <div className="form-group">
              <label>Country</label>
              <input
                type="text"
                value={formData.country}
                onChange={(e) => handleChange('country', e.target.value)}
                placeholder="e.g. UK"
              />
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-title">Contact Channels</div>

          <div>
            <label style={{ display: 'block', marginBottom: '10px', fontWeight: 500, fontSize: '13px' }}>Emails</label>
            {formData.emails.map((email, idx) => (
              <div key={idx} className="form-group">
                <input
                  type="email"
                  value={email}
                  onChange={(e) => handleEmailChange(idx, e.target.value)}
                  placeholder="name@example.com"
                />
              </div>
            ))}
            <button type="button" onClick={addEmail} className="btn btn-secondary" style={{ marginBottom: '15px' }}>
              + Add Email
            </button>
          </div>

          <div>
            <label style={{ display: 'block', marginBottom: '10px', fontWeight: 500, fontSize: '13px' }}>Phones</label>
            {formData.phones.map((phone, idx) => (
              <div key={idx} className="form-group">
                <input
                  type="tel"
                  value={phone}
                  onChange={(e) => handlePhoneChange(idx, e.target.value)}
                  placeholder="+1 555 123 4567"
                />
              </div>
            ))}
            <button type="button" onClick={addPhone} className="btn btn-secondary" style={{ marginBottom: '15px' }}>
              + Add Phone
            </button>
          </div>

          <div className="form-group">
            <label>LinkedIn Profile URL</label>
            <input
              type="url"
              value={formData.linkedin_url}
              onChange={(e) => handleChange('linkedin_url', e.target.value)}
              placeholder="https://linkedin.com/in/..."
            />
          </div>
        </div>

        <div className="card">
          <div className="card-title">Classification</div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '15px' }}>
            <div className="form-group">
              <label>Tier</label>
              <select value={formData.tier} onChange={(e) => handleChange('tier', e.target.value)}>
                <option value="VVIP">VVIP</option>
                <option value="VIP">VIP</option>
                <option value="CIP">CIP</option>
                <option value="Friend">Friend</option>
                <option value="Prospect">Prospect</option>
                <option value="Network">Network</option>
                <option value="Dormant">Dormant</option>
              </select>
            </div>

            <div className="form-group">
              <label>Warmth Status</label>
              <select value={formData.warmth_status} onChange={(e) => handleChange('warmth_status', e.target.value)}>
                <option value="warm">Warm</option>
                <option value="cooling">Cooling</option>
                <option value="cold">Cold</option>
              </select>
            </div>
          </div>

          <div className="form-group">
            <label>How We Met</label>
            <input
              type="text"
              value={formData.how_we_met}
              onChange={(e) => handleChange('how_we_met', e.target.value)}
              placeholder="e.g. EWC 2026 pre-event call"
            />
          </div>

          <div className="form-group">
            <label>Strategic Context / Tags</label>
            <input
              type="text"
              value={formData.strategic_context}
              onChange={(e) => handleChange('strategic_context', e.target.value)}
              placeholder="e.g. EWC 2026, Aviation Partnership"
            />
          </div>
        </div>

        <div className="card">
          <button type="submit" disabled={loading} className="btn btn-primary">
            {loading ? 'Creating...' : 'Create Contact'}
          </button>
        </div>
      </form>
    </div>
  );
}

