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 CreateFacilityQualificationRateDialog from "./CreateFacilityQualificationRateDialog";
import EditFacilityQualificationRateDialog from "./EditFacilityQualificationRateDialog";

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

  const [rates, setRates] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingRate, setEditingRate] = useState(null);
  const [deletingRateId, setDeletingRateId] = useState(null);

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

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

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

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

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

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

  function handleUpdated() {
    setEditingRate(null);
    loadRates();
  }

  async function handleDelete(rate) {
    if (!window.confirm(`Qualifikationspreis "${rate.qualification}" wirklich löschen?`)) {
      return;
    }

    setDeletingRateId(rate.id);
    const result = await window.omsorg.facilityQualificationRates.delete(facilityId, rate.id);
    setDeletingRateId(null);

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

  return (
    <div className="employee-tab-content">
      <div className="page-heading">
        <h3>Qualifikationsabhängige Preise</h3>

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

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

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

      {!isLoading && rates.length > 0 && (
        <div className="facility-contacts-list">
          {rates.map((rate) => (
            <div key={rate.id} className="facility-contact-row">
              <div>
                <strong>{rate.qualification}</strong>
                <p>{rate.rate.toFixed(2)} EUR/Std.</p>
              </div>

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

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

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

      {editingRate && (
        <EditFacilityQualificationRateDialog
          facilityId={facilityId}
          rate={editingRate}
          onClose={() => setEditingRate(null)}
          onUpdated={handleUpdated}
        />
      )}
    </div>
  );
}
