import { useCallback, useEffect, useState } from "react";
import { Pencil, Plus, Trash2 } from "lucide-react";

import OmsorgButton from "../../components/ui/OmsorgButton";
import { useAuth } from "../../app/AuthContext";
import CreateFacilityContactDialog from "./CreateFacilityContactDialog";
import EditFacilityContactDialog from "./EditFacilityContactDialog";

export default function FacilityContactsList({ facilityId }) {
  const { hasPermission } = useAuth();
  const canCreate = hasPermission("Facilities", "Create");
  const canEdit = hasPermission("Facilities", "Edit");
  const canDelete = hasPermission("Facilities", "Delete");

  const [contacts, setContacts] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingContact, setEditingContact] = useState(null);
  const [deletingContactId, setDeletingContactId] = useState(null);

  const loadContacts = useCallback(async () => {
    setIsLoading(true);
    setError(null);

    const result = await window.omsorg.facilityContacts.list(facilityId);

    if (result.ok) {
      setContacts(result.data ?? []);
    } else {
      setError("Ansprechpartner konnten nicht geladen werden.");
    }

    setIsLoading(false);
  }, [facilityId]);

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

  function handleCreated() {
    setIsDialogOpen(false);
    loadContacts();
  }

  function handleUpdated() {
    setEditingContact(null);
    loadContacts();
  }

  async function handleDelete(contact) {
    if (!window.confirm(`${contact.name} wirklich löschen?`)) {
      return;
    }

    setDeletingContactId(contact.id);
    const result = await window.omsorg.facilityContacts.delete(facilityId, contact.id);
    setDeletingContactId(null);

    if (result.ok) {
      loadContacts();
    }
  }

  return (
    <div className="employee-tab-content">
      <div className="page-heading">
        <h3>Ansprechpartner</h3>

        {canCreate && (
          <OmsorgButton icon={Plus} variant="secondary" onClick={() => setIsDialogOpen(true)}>
            Neuer Ansprechpartner
          </OmsorgButton>
        )}
      </div>

      {error && <p className="login-error">{error}</p>}
      {isLoading && <p>Lädt...</p>}

      {!isLoading && contacts.length === 0 && <p>Noch kein Ansprechpartner erfasst.</p>}

      {!isLoading && contacts.length > 0 && (
        <div className="facility-contacts-list">
          {contacts.map((contact) => (
            <div key={contact.id} className="facility-contact-row">
              <div>
                <strong>{contact.name}</strong>
                {contact.role && <span> — {contact.role}</span>}
                {contact.department && <span> ({contact.department})</span>}
                <p>
                  {[contact.phoneNumber, contact.email].filter(Boolean).join(" · ") || "—"}
                </p>
                {contact.notes && <p>{contact.notes}</p>}
              </div>

              {canEdit && (
                <OmsorgButton
                  variant="secondary"
                  icon={Pencil}
                  onClick={() => setEditingContact(contact)}
                >
                  Bearbeiten
                </OmsorgButton>
              )}

              {canDelete && (
                <OmsorgButton
                  variant="secondary"
                  icon={Trash2}
                  onClick={() => handleDelete(contact)}
                  disabled={deletingContactId === contact.id}
                >
                  Löschen
                </OmsorgButton>
              )}
            </div>
          ))}
        </div>
      )}

      {isDialogOpen && (
        <CreateFacilityContactDialog
          facilityId={facilityId}
          onClose={() => setIsDialogOpen(false)}
          onCreated={handleCreated}
        />
      )}

      {editingContact && (
        <EditFacilityContactDialog
          facilityId={facilityId}
          contact={editingContact}
          onClose={() => setEditingContact(null)}
          onUpdated={handleUpdated}
        />
      )}
    </div>
  );
}
