import React, { useState } from 'react';
import { updateHandlerMe } from '../../services/handler';
import './HandlerDashboard.css';

const HandlerDashboard = ({ handlerUser, onLogout }) => {
  const [userData, setUserData] = useState(handlerUser);
  const [editing, setEditing] = useState(false);
  const [formData, setFormData] = useState({
    phone: handlerUser.phone || '',
    landline: handlerUser.landline || '',
    address: handlerUser.address || '',
    available: handlerUser.available
  });
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState(null);

  const handleSave = async (e) => {
    e.preventDefault();
    setSaving(true);
    setMessage(null);
    try {
      const result = await updateHandlerMe(formData);
      if (result.success) {
        setUserData({ ...userData, ...formData });
        setEditing(false);
        setMessage({ type: 'success', text: 'Daten erfolgreich gespeichert' });
      }
    } catch (err) {
      setMessage({ type: 'error', text: err.response?.data?.message || 'Fehler beim Speichern' });
    } finally {
      setSaving(false);
    }
  };

  const handleAvailabilityToggle = async () => {
    const newVal = !userData.available;
    setSaving(true);
    setMessage(null);
    try {
      const result = await updateHandlerMe({ available: newVal });
      if (result.success) {
        setUserData({ ...userData, available: newVal });
        setFormData({ ...formData, available: newVal });
        setMessage({ type: 'success', text: newVal ? 'Sie sind jetzt als verfügbar markiert' : 'Sie sind jetzt als nicht verfügbar markiert' });
      }
    } catch (err) {
      setMessage({ type: 'error', text: 'Fehler beim Aktualisieren' });
    } finally {
      setSaving(false);
    }
  };

  const handleLogout = () => {
    localStorage.removeItem('handlerToken');
    onLogout();
  };

  return (
    <div className="handler-dashboard">
      <div className="handler-dashboard-card">
        <div className="handler-dashboard-header">
          <div>
            <h2>Mein Profil</h2>
            <p className="handler-name">{userData.name}</p>
          </div>
          <button className="btn-handler-logout" onClick={handleLogout}>Abmelden</button>
        </div>

        {message && (
          <div className={`handler-message handler-message-${message.type}`}>{message.text}</div>
        )}

        {/* Availability Toggle */}
        <div className="handler-availability-section">
          <div className="availability-label">Meine Verfügbarkeit</div>
          <button
            className={`availability-big-btn ${userData.available ? 'btn-green' : 'btn-red'}`}
            onClick={handleAvailabilityToggle}
            disabled={saving}
          >
            <span className={`status-dot-lg ${userData.available ? 'dot-green' : 'dot-red'}`} />
            {userData.available ? '✅ Verfügbar – zum Wechsel klicken' : '🔴 Nicht verfügbar – zum Wechsel klicken'}
          </button>
          <p className="availability-hint">
            Klicken Sie, um Ihre Verfügbarkeit zu ändern. Nur verfügbare Gespanne erscheinen in der öffentlichen Suchliste.
          </p>
        </div>

        {/* Contact Data */}
        <div className="handler-contact-section">
          <div className="handler-section-header">
            <h3>Kontaktdaten</h3>
            {!editing && (
              <button className="btn-handler-edit" onClick={() => setEditing(true)}>Bearbeiten</button>
            )}
          </div>

          {!editing ? (
            <div className="handler-info-list">
              <div className="handler-info-row">
                <span className="info-label">Adresse</span>
                <span>{userData.address}</span>
              </div>
              <div className="handler-info-row">
                <span className="info-label">Mobil</span>
                <a href={`tel:${userData.phone}`}>{userData.phone}</a>
              </div>
              {userData.landline && (
                <div className="handler-info-row">
                  <span className="info-label">Festnetz</span>
                  <a href={`tel:${userData.landline}`}>{userData.landline}</a>
                </div>
              )}
            </div>
          ) : (
            <form onSubmit={handleSave} className="handler-edit-form">
              <div className="form-group">
                <label>Adresse</label>
                <input type="text" value={formData.address}
                  onChange={e => setFormData({ ...formData, address: e.target.value })} required />
              </div>
              <div className="form-group">
                <label>Mobilnummer</label>
                <input type="tel" value={formData.phone}
                  onChange={e => setFormData({ ...formData, phone: e.target.value })} required />
              </div>
              <div className="form-group">
                <label>Festnetz (optional)</label>
                <input type="tel" value={formData.landline}
                  onChange={e => setFormData({ ...formData, landline: e.target.value })} />
              </div>
              <div className="handler-form-actions">
                <button type="submit" className="btn-handler-primary" disabled={saving}>
                  {saving ? 'Speichert...' : 'Speichern'}
                </button>
                <button type="button" className="btn-handler-cancel" onClick={() => setEditing(false)}>
                  Abbrechen
                </button>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
};

export default HandlerDashboard;
