// ============================================================================
// CONCIERGES PAGE - Gestion des concierges
// ============================================================================

const ConciergesPage = () => {
  const { customer } = useAuth();
  const toast = useToast();
  const [concierges, setConcierges] = useState([]);
  const [loading, setLoading] = useState(true);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingConcierge, setEditingConcierge] = useState(null);

  // Charger les concierges
  const loadConcierges = async () => {
    try {
      setLoading(true);
      const data = await api.getConcierges(customer.id);
      setConcierges(data.concierges || []);
    } catch (error) {
      console.error('Erreur chargement concierges:', error);
      toast.error('Erreur lors du chargement des concierges');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadConcierges();
  }, []);

  // Ajouter/Modifier un concierge
  const handleSave = async (conciergeData) => {
    try {
      if (editingConcierge) {
        await api.updateConcierge({ ...conciergeData, id: editingConcierge.id });
        toast.success('Concierge mis à jour avec succès');
      } else {
        await api.createConcierge(conciergeData);
        toast.success('Concierge créé avec succès');
      }
      await loadConcierges();
      setIsModalOpen(false);
      setEditingConcierge(null);
    } catch (error) {
      console.error('Erreur sauvegarde concierge:', error);
      toast.error('Erreur lors de la sauvegarde');
    }
  };

  // Supprimer un concierge
  const handleDelete = async (id) => {
    if (!confirm('Êtes-vous sûr de vouloir supprimer ce concierge ?')) return;

    try {
      await api.deleteConcierge(id);
      toast.success('Concierge supprimé avec succès');
      await loadConcierges();
    } catch (error) {
      console.error('Erreur suppression concierge:', error);
      toast.error('Erreur lors de la suppression');
    }
  };

  // Ouvrir le formulaire d'édition
  const handleEdit = (concierge) => {
    setEditingConcierge(concierge);
    setIsModalOpen(true);
  };

  // Ouvrir le formulaire de création
  const handleNew = () => {
    setEditingConcierge(null);
    setIsModalOpen(true);
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 flex items-center gap-3">
            <i className="fas fa-key text-green-600"></i>
            Concierges
          </h1>
          <p className="text-gray-600 mt-1">
            Gérez les informations des concierges pour vos écrans
          </p>
        </div>
        <button
          onClick={handleNew}
          className="px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors flex items-center gap-2 shadow-lg"
        >
          <i className="fas fa-plus"></i>
          Nouveau concierge
        </button>
      </div>

      {/* Liste des concierges */}
      {loading ? (
        <div className="text-center py-12">
          <i className="fas fa-spinner fa-spin text-4xl text-gray-400"></i>
          <p className="text-gray-600 mt-4">Chargement...</p>
        </div>
      ) : concierges.length === 0 ? (
        <div className="bg-white rounded-lg shadow-sm p-12 text-center">
          <i className="fas fa-key text-6xl text-gray-300 mb-4"></i>
          <h3 className="text-xl font-semibold text-gray-900 mb-2">
            Aucun concierge
          </h3>
          <p className="text-gray-600 mb-6">
            Commencez par ajouter votre premier concierge
          </p>
          <button
            onClick={handleNew}
            className="px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
          >
            <i className="fas fa-plus mr-2"></i>
            Ajouter un concierge
          </button>
        </div>
      ) : (
        <div className="grid gap-4">
          {concierges.map((concierge) => (
            <div
              key={concierge.id}
              className="bg-white rounded-lg shadow-sm p-6 hover:shadow-md transition-shadow"
            >
              <div className="flex justify-between items-start">
                <div className="flex-1">
                  <div className="flex items-center gap-3 mb-2">
                    <h3 className="text-xl font-semibold text-gray-900">
                      {concierge.name}
                    </h3>
                    {concierge.is_active ? (
                      <span className="px-2 py-1 bg-green-100 text-green-800 text-xs rounded-full">
                        Actif
                      </span>
                    ) : (
                      <span className="px-2 py-1 bg-gray-100 text-gray-800 text-xs rounded-full">
                        Inactif
                      </span>
                    )}
                  </div>

                  <div className="grid md:grid-cols-2 gap-4 mt-4">
                    <div>
                      <p className="text-sm text-gray-600 mb-2">
                        <i className="fas fa-building w-5"></i>
                        <strong>Client:</strong> {concierge.customer_name || 'N/A'}
                      </p>
                      <p className="text-sm text-gray-600 mb-2">
                        <i className="fas fa-tag w-5"></i>
                        <strong>Titre:</strong> {concierge.title || 'Conciergerie'}
                      </p>
                      <p className="text-sm text-gray-600 mb-2">
                        <i className="fas fa-phone w-5"></i>
                        <strong>Téléphone:</strong> {concierge.phone}
                      </p>
                    </div>
                    <div>
                      {concierge.email && (
                        <p className="text-sm text-gray-600 mb-2">
                          <i className="fas fa-envelope w-5"></i>
                          <strong>Email:</strong> {concierge.email}
                        </p>
                      )}
                      {concierge.address && (
                        <p className="text-sm text-gray-600 mb-2">
                          <i className="fas fa-map-marker-alt w-5"></i>
                          <strong>Adresse:</strong> {concierge.address}
                        </p>
                      )}
                    </div>
                  </div>

                  {concierge.notes && (
                    <div className="mt-3 p-3 bg-gray-50 rounded">
                      <p className="text-sm text-gray-700">
                        <i className="fas fa-sticky-note mr-2"></i>
                        {concierge.notes}
                      </p>
                    </div>
                  )}
                </div>

                <div className="flex gap-2 ml-4">
                  <button
                    onClick={() => handleEdit(concierge)}
                    className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                    title="Modifier"
                  >
                    <i className="fas fa-edit"></i>
                  </button>
                  <button
                    onClick={() => handleDelete(concierge.id)}
                    className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
                    title="Supprimer"
                  >
                    <i className="fas fa-trash"></i>
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Modal d'ajout/édition */}
      {isModalOpen && (
        <ConciergeFormModal
          concierge={editingConcierge}
          customerId={customer.id}
          onClose={() => {
            setIsModalOpen(false);
            setEditingConcierge(null);
          }}
          onSave={handleSave}
        />
      )}
    </div>
  );
};

// ============================================================================
// MODAL FORMULAIRE CONCIERGE
// ============================================================================

const ConciergeFormModal = ({ concierge, customers, onClose, onSave, customerId }) => {
  const toast = useToast();
  const [formData, setFormData] = useState({
    customer_id: concierge?.customer_id || customerId,
    title: concierge?.title || 'Conciergerie',
    name: concierge?.name || '',
    email: concierge?.email || '',
    phone: concierge?.phone || '',
    is_active: concierge?.is_active ?? 1
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    
    // Validation
    if (!formData.name) {
      toast.error('Le nom est requis');
      return;
    }
    if (!formData.phone) {
      toast.error('Le téléphone est requis');
      return;
    }

    onSave(formData);
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        <div className="p-6">
          <div className="flex justify-between items-center mb-6">
            <h2 className="text-2xl font-bold text-gray-900">
              {concierge ? 'Modifier le concierge' : 'Nouveau concierge'}
            </h2>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600"
            >
              <i className="fas fa-times text-2xl"></i>
            </button>
          </div>

            <form onSubmit={handleSubmit} className="space-y-4">
            {/* Titre */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Titre
              </label>
              <input
                type="text"
                value={formData.title}
                onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                placeholder="Ex: Conciergerie, Gardiennage"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"
              />
            </div>

            {/* Nom */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Nom *
              </label>
              <input
                type="text"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                placeholder="Ex: Jean Dupont"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"
                required
              />
            </div>

            {/* Téléphone */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Téléphone *
              </label>
              <input
                type="tel"
                value={formData.phone}
                onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                placeholder="+41 79 123 45 67"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"
                required
              />
            </div>

            {/* Email */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Email
              </label>
              <input
                type="email"
                value={formData.email}
                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                placeholder="concierge@example.com"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"
              />
            </div>

            {/* Actif */}
            <div className="flex items-center">
              <input
                type="checkbox"
                id="is_active"
                checked={formData.is_active === 1}
                onChange={(e) => setFormData({ ...formData, is_active: e.target.checked ? 1 : 0 })}
                className="w-4 h-4 text-green-600 border-gray-300 rounded focus:ring-green-500"
              />
              <label htmlFor="is_active" className="ml-2 text-sm text-gray-700">
                Concierge actif
              </label>
            </div>

            {/* Boutons */}
            <div className="flex gap-3 pt-4">
              <button
                type="button"
                onClick={onClose}
                className="flex-1 px-6 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
              >
                Annuler
              </button>
              <button
                type="submit"
                className="flex-1 px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
              >
                {concierge ? 'Mettre à jour' : 'Créer'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

