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

import OmsorgCard from "../../components/OmsorgCard";
import OmsorgButton from "../../components/ui/OmsorgButton";
import { useAuth } from "../../app/AuthContext";
import EditOrderDialog from "./EditOrderDialog";
import AssignmentsList from "./AssignmentsList";

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

export default function OrderDetailPanel({ order, facilityName, facilities, onUpdated }) {
  const { hasPermission } = useAuth();
  const canEdit = hasPermission("Orders", "Edit");
  const canDelete = hasPermission("Orders", "Delete");
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  async function handleDelete() {
    if (!window.confirm("Diesen Auftrag wirklich löschen?")) {
      return;
    }

    setIsDeleting(true);
    const result = await window.omsorg.orders.delete(order.id);
    setIsDeleting(false);

    if (result.ok) {
      onUpdated?.(null);
    }
  }

  if (!order) {
    return (
      <OmsorgCard>
        <div className="employee-detail-empty">
          <h2>Kein Auftrag ausgewählt</h2>
          <p>Wähle links einen Auftrag aus.</p>
        </div>
      </OmsorgCard>
    );
  }

  return (
    <OmsorgCard>
      <div className="employee-detail">
        <div className="employee-detail-header">
          <div>
            <h2>{facilityName ?? "—"}</h2>
            <span className="omsorg-badge omsorg-badge--neutral">{order.statusName}</span>
          </div>

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

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

        <div className="employee-detail-grid">
          <div>
            <strong>Zeitraum</strong>
            <p>
              {formatDate(order.startDate)} – {order.endDate ? formatDate(order.endDate) : "offen"}
            </p>
          </div>

          <div>
            <strong>Benötigte Qualifikation</strong>
            <p>{order.requiredQualification ?? "—"}</p>
          </div>

          <div>
            <strong>Schichtart</strong>
            <p>{order.shiftType ?? "—"}</p>
          </div>

          <div>
            <strong>Anzahl benötigter Mitarbeiter</strong>
            <p>{order.requiredHeadcount}</p>
          </div>

          <div>
            <strong>Priorität</strong>
            <p>{order.priority}</p>
          </div>

          <div>
            <strong>Konditionen</strong>
            <p>{order.conditions ?? "—"}</p>
          </div>
        </div>

        <AssignmentsList orderId={order.id} order={order} requiredHeadcount={order.requiredHeadcount} />
      </div>

      {isEditDialogOpen && (
        <EditOrderDialog
          order={order}
          facilities={facilities}
          onClose={() => setIsEditDialogOpen(false)}
          onUpdated={(updatedOrder) => {
            setIsEditDialogOpen(false);
            onUpdated?.(updatedOrder);
          }}
        />
      )}
    </OmsorgCard>
  );
}
