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 CreateEmployeeFacilityDistanceDialog from "./CreateEmployeeFacilityDistanceDialog";
import EditEmployeeFacilityDistanceDialog from "./EditEmployeeFacilityDistanceDialog";

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

  const [distances, setDistances] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingDistance, setEditingDistance] = useState(null);
  const [deletingDistanceId, setDeletingDistanceId] = useState(null);

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

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

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

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

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

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

  function handleUpdated() {
    setEditingDistance(null);
    loadDistances();
  }

  async function handleDelete(distance) {
    if (!window.confirm(`Entfernung für "${distance.employeeFirstName} ${distance.employeeLastName}" wirklich löschen?`)) {
      return;
    }

    setDeletingDistanceId(distance.id);
    const result = await window.omsorg.employeeFacilityDistances.delete(facilityId, distance.id);
    setDeletingDistanceId(null);

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

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

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

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

      {!isLoading && distances.length === 0 && <p>Noch keine Entfernung erfasst.</p>}

      {!isLoading && distances.length > 0 && (
        <div className="facility-contacts-list">
          {distances.map((distance) => (
            <div key={distance.id} className="facility-contact-row">
              <div>
                <strong>
                  {distance.employeeFirstName} {distance.employeeLastName}
                </strong>
                <p>{distance.distanceKm.toFixed(1)} km</p>
              </div>

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

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

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

      {editingDistance && (
        <EditEmployeeFacilityDistanceDialog
          facilityId={facilityId}
          distance={editingDistance}
          onClose={() => setEditingDistance(null)}
          onUpdated={handleUpdated}
        />
      )}
    </div>
  );
}
