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 CreateContractDialog from "./CreateContractDialog";
import EditContractDialog from "./EditContractDialog";

function formatDate(value) {
  if (!value) return "—";
  return new Date(value).toLocaleDateString("de-DE");
}

function formatPeriod(contract) {
  return `${formatDate(contract.startDate)} – ${contract.endDate ? formatDate(contract.endDate) : "unbefristet"}`;
}

export default function ContractsList({ employeeId }) {
  const { hasPermission } = useAuth();
  const canCreate = hasPermission("Contracts", "Create");
  const canEdit = hasPermission("Contracts", "Edit");
  const canDelete = hasPermission("Contracts", "Delete");

  const [contracts, setContracts] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingContract, setEditingContract] = useState(null);
  const [deletingContractId, setDeletingContractId] = useState(null);

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

    const result = await window.omsorg.contracts.list({ employeeId, pageSize: 100 });

    if (result.ok) {
      setContracts(result.data?.items ?? []);
    } else {
      setError("Verträge konnten nicht geladen werden.");
    }

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

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

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

  function handleUpdated() {
    setEditingContract(null);
    loadContracts();
  }

  async function handleDelete(contract) {
    if (!window.confirm(`Vertrag "${contract.contractType}" wirklich löschen?`)) {
      return;
    }

    setDeletingContractId(contract.id);
    const result = await window.omsorg.contracts.delete(contract.id);
    setDeletingContractId(null);

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

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

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

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

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

      {!isLoading && contracts.length > 0 && (
        <div className="facility-contacts-list">
          {contracts.map((contract) => (
            <div key={contract.id} className="facility-contact-row">
              <div>
                <strong>{contract.contractType}</strong>
                <span className="omsorg-badge omsorg-badge--neutral"> {contract.status}</span>
                <p>{formatPeriod(contract)}</p>
                <p>
                  {[
                    contract.weeklyHours != null ? `${contract.weeklyHours} Std./Woche` : null,
                    contract.hourlyWage != null ? `${contract.hourlyWage} €/Std.` : null,
                  ]
                    .filter(Boolean)
                    .join(" · ") || "—"}
                </p>
              </div>

              <div>
                {canEdit && (
                  <OmsorgButton
                    variant="secondary"
                    icon={Pencil}
                    onClick={() => setEditingContract(contract)}
                  >
                    Bearbeiten
                  </OmsorgButton>
                )}

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

      {isDialogOpen && (
        <CreateContractDialog
          employeeId={employeeId}
          onClose={() => setIsDialogOpen(false)}
          onCreated={handleCreated}
        />
      )}

      {editingContract && (
        <EditContractDialog
          employeeId={employeeId}
          contract={editingContract}
          onClose={() => setEditingContract(null)}
          onUpdated={handleUpdated}
        />
      )}
    </div>
  );
}
