import { useEffect, useState } from "react";
import { Pencil } 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 EditTimeEntryDialog from "./EditTimeEntryDialog";

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

function formatTime(value) {
  if (!value) {
    return "—";
  }
  return value.slice(0, 5);
}

export default function TimeEntryDetailPanel({ timeEntry, onChanged }) {
  const { hasPermission } = useAuth();
  const canDecide = hasPermission("TimeEntries", "Approve");
  const canEdit = hasPermission("TimeEntries", "Edit");
  const [adminNote, setAdminNote] = useState("");
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState(null);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const { items: statusItems } = useValueListItems("TimeEntryStatus");
  const [transitions, setTransitions] = useState([]);

  useEffect(() => {
    let cancelled = false;

    window.omsorg.valueLists.listTransitions("TimeEntryStatus").then((result) => {
      if (!cancelled) {
        setTransitions(result.ok ? result.data ?? [] : []);
      }
    });

    return () => {
      cancelled = true;
    };
  }, []);

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

  // Büro-Entscheidungen sind genau die Übergänge mit requiresApproval=true ab dem aktuellen Status
  // (Selbst-Einreichung des Außendienstes läuft über einen anderen Endpoint, submit, nicht hier).
  const decisionOptions = transitions
    .filter((t) => t.fromItemId === timeEntry.statusId && t.requiresApproval)
    .map((t) => statusItems.find((item) => item.id === t.toItemId))
    .filter(Boolean);

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

    const result = await window.omsorg.timeEntries.decide(timeEntry.id, { statusId, adminNote: adminNote.trim() || null });

    setIsSaving(false);

    if (!result.ok) {
      setError(result.status === 403 ? "Keine Berechtigung, diesen Statuswechsel auszulösen." : "Statuswechsel konnte nicht gespeichert werden.");
      return;
    }

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

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

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

        <div className="employee-detail-grid">
          <div>
            <strong>Einrichtung</strong>
            <p>{timeEntry.facilityName}</p>
          </div>

          <div>
            <strong>Datum</strong>
            <p>{formatDate(timeEntry.date)}</p>
          </div>

          <div>
            <strong>Beginn – Ende</strong>
            <p>
              {formatTime(timeEntry.start)} – {formatTime(timeEntry.end)}
            </p>
          </div>

          <div>
            <strong>Nachtstunden</strong>
            <p>{timeEntry.nightHours}</p>
          </div>

          <div>
            <strong>Samstagsstunden</strong>
            <p>{timeEntry.saturdayHours}</p>
          </div>

          <div>
            <strong>Sonntagsstunden</strong>
            <p>{timeEntry.sundayHours}</p>
          </div>

          <div>
            <strong>Feiertagsstunden</strong>
            <p>{timeEntry.holidayHours}</p>
          </div>

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

        {canDecide && (
          <div className="form-grid">
            {decisionOptions.length === 0 && (
              <p style={{ color: "var(--omsorg-text-secondary)" }}>
                Aus dem aktuellen Status ({timeEntry.statusName}) ist keine Büro-Entscheidung möglich.
              </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>}

            {decisionOptions.length > 0 && (
              <div className="form-actions">
                {decisionOptions.map((option) => (
                  <OmsorgButton
                    key={option.id}
                    variant="secondary"
                    disabled={isSaving}
                    onClick={() => handleDecision(option.id)}
                  >
                    {option.value}
                  </OmsorgButton>
                ))}
              </div>
            )}
          </div>
        )}
      </div>

      {isEditDialogOpen && (
        <EditTimeEntryDialog
          timeEntry={timeEntry}
          onClose={() => setIsEditDialogOpen(false)}
          onUpdated={(updatedTimeEntry) => {
            setIsEditDialogOpen(false);
            onChanged?.(updatedTimeEntry);
          }}
        />
      )}
    </OmsorgCard>
  );
}
