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

import OmsorgCard from "../../components/OmsorgCard";
import OmsorgButton from "../../components/ui/OmsorgButton";
import { useAuth } from "../../app/AuthContext";
import { useValueListItems } from "../../app/useValueListItems";
import EditAbsenceDialog from "./EditAbsenceDialog";

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

export default function AbsenceDetailPanel({ absence, onChanged }) {
  const { hasPermission } = useAuth();
  const canDecide = hasPermission("Absences", "Approve");
  const canEdit = hasPermission("Absences", "Edit");
  const [adminNote, setAdminNote] = useState("");
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState(null);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const { items: statusItems } = useValueListItems("AbsenceStatus");

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

  // Nicht auf den Anzeigetext "Eingereicht" hartkodieren - der ist über die Status-Verwaltung
  // umbenennbar (siehe omsorgCore/CLAUDE.md, AbsenceService.GetInitialStatusValueAsync). Solange
  // die Liste noch lädt, gilt "nicht pending" (keine Aktionen anzeigen statt falsch-positiv).
  const initialStatus = statusItems.find((item) => item.isInitial)?.value;
  const isPending = absence.status === initialStatus;

  async function handleDecision(status) {
    setIsSaving(true);
    setError(null);

    const result = await window.omsorg.absences.decide(absence.id, { status, adminNote: adminNote.trim() || null });

    setIsSaving(false);

    if (!result.ok) {
      setError(result.status === 403 ? "Keine Berechtigung, diesen Antrag zu entscheiden." : "Entscheidung konnte nicht gespeichert werden.");
      return;
    }

    setAdminNote("");
    onChanged?.(result.data);
  }

  return (
    <OmsorgCard>
      <div className="employee-detail">
        <div className="employee-detail-header">
          <div>
            <h2>{absence.employeeName}</h2>
            <span className="omsorg-badge omsorg-badge--neutral">{absence.status}</span>
          </div>

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

        <div className="employee-detail-grid">
          <div>
            <strong>Art</strong>
            <p>{absence.type}</p>
          </div>

          <div>
            <strong>Zeitraum</strong>
            <p>
              {formatDate(absence.startDate)} – {formatDate(absence.endDate)}
            </p>
          </div>

          <div>
            <strong>Grund</strong>
            <p>{absence.reason ?? "—"}</p>
          </div>

          <div>
            <strong>Vertretung</strong>
            <p>{absence.substitute ?? "—"}</p>
          </div>

          <div>
            <strong>Nachricht</strong>
            <p>{absence.note ?? "—"}</p>
          </div>

          <div>
            <strong>Kommentar</strong>
            <p>{absence.adminNote ?? "—"}</p>
          </div>
        </div>

        {canDecide && (
          <div className="form-grid">
            {!isPending && (
              <p style={{ color: "var(--omsorg-text-secondary)" }}>
                Bereits entschieden ({absence.status}) — hier lässt sich die Entscheidung bei Bedarf noch ändern.
              </p>
            )}

            <label className="form-field">
              <span>Kommentar (optional)</span>
              <textarea value={adminNote} onChange={(event) => setAdminNote(event.target.value)} maxLength={500} />
            </label>

            {error && <p className="login-error form-error">{error}</p>}

            <div className="form-actions">
              <OmsorgButton variant="secondary" icon={X} disabled={isSaving} onClick={() => handleDecision("Abgelehnt")}>
                Ablehnen
              </OmsorgButton>

              <OmsorgButton icon={Check} disabled={isSaving} onClick={() => handleDecision("Genehmigt")}>
                Genehmigen
              </OmsorgButton>
            </div>
          </div>
        )}
      </div>

      {isEditDialogOpen && (
        <EditAbsenceDialog
          absence={absence}
          onClose={() => setIsEditDialogOpen(false)}
          onUpdated={(updatedAbsence) => {
            setIsEditDialogOpen(false);
            onChanged?.(updatedAbsence);
          }}
        />
      )}
    </OmsorgCard>
  );
}
