import { useCallback, useEffect, useState } from "react";
import { SlidersHorizontal } from "lucide-react";

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

const PAGE_SIZE = 20;

export default function AbsencesPage() {
  const { hasPermission } = useAuth();
  const { items: statusOptions } = useValueListItems("AbsenceStatus");
  const { items: typeOptions } = useValueListItems("AbsenceType");

  const [absences, setAbsences] = useState([]);
  const [totalCount, setTotalCount] = useState(0);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [selectedAbsenceId, setSelectedAbsenceId] = useState(null);
  const [statusFilter, setStatusFilter] = useState("");
  const [typeFilter, setTypeFilter] = useState("");
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [page, setPage] = useState(1);

  useEffect(() => {
    setPage(1);
  }, [statusFilter, typeFilter]);

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

    const result = await window.omsorg.absences.list({
      status: statusFilter || undefined,
      type: typeFilter || undefined,
      page,
      pageSize: PAGE_SIZE,
    });

    if (result.ok) {
      const data = result.data ?? { items: [], totalCount: 0 };
      setAbsences(data.items ?? []);
      setTotalCount(data.totalCount ?? 0);
      setSelectedAbsenceId((current) =>
        (data.items ?? []).some((absence) => absence.id === current) ? current : data.items?.[0]?.id ?? null
      );
    } else {
      setError("Anträge konnten nicht geladen werden.");
    }

    setIsLoading(false);
  }, [statusFilter, typeFilter, page]);

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

  const selectedAbsence = absences.find((absence) => absence.id === selectedAbsenceId) ?? null;
  const totalPages = Math.max(1, Math.ceil(totalCount / PAGE_SIZE));

  function handleDecided() {
    loadAbsences();
  }

  if (!hasPermission("Absences", "View")) {
    return (
      <OmsorgCard title="Abwesenheiten">
        <p>Keine Berechtigung, Abwesenheitsanträge einzusehen.</p>
      </OmsorgCard>
    );
  }

  return (
    <div className="employees-page">
      <div className="page-heading">
        <div>
          <p className="page-eyebrow">Personal</p>

          <h1>Abwesenheiten</h1>

          <p className="page-description">
            Urlaubs-, Krankmeldungs- und sonstige Abwesenheitsanträge des Außendienstes prüfen und entscheiden.
          </p>
        </div>
      </div>

      <OmsorgCard>
        <div className="employees-toolbar">
          <OmsorgButton
            variant="secondary"
            icon={SlidersHorizontal}
            onClick={() => setIsFilterOpen((open) => !open)}
          >
            Filter
          </OmsorgButton>
        </div>

        {isFilterOpen && (
          <div className="employees-filter-panel">
            <label className="form-field">
              <span>Status</span>
              <select value={statusFilter} onChange={(event) => setStatusFilter(event.target.value)}>
                <option value="">Alle</option>
                {statusOptions.map((option) => (
                  <option key={option.id} value={option.value}>
                    {option.value}
                  </option>
                ))}
              </select>
            </label>

            <label className="form-field">
              <span>Art</span>
              <select value={typeFilter} onChange={(event) => setTypeFilter(event.target.value)}>
                <option value="">Alle</option>
                {typeOptions.map((option) => (
                  <option key={option.id} value={option.value}>
                    {option.value}
                  </option>
                ))}
              </select>
            </label>
          </div>
        )}
      </OmsorgCard>

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

      {!isLoading && (
        <div className="employees-layout">
          <div className="employees-list">
            {absences.map((absence) => {
              const isSelected = absence.id === selectedAbsenceId;

              return (
                <button
                  key={absence.id}
                  type="button"
                  className={
                    isSelected ? "employee-list-button employee-list-button--active" : "employee-list-button"
                  }
                  onClick={() => setSelectedAbsenceId(absence.id)}
                >
                  <OmsorgCard>
                    <div className="employee-row">
                      <div className="employee-main">
                        <strong>{absence.employeeName}</strong>
                        <span> — {absence.type}</span>
                      </div>

                      <div className="employee-status">
                        <span className="omsorg-badge omsorg-badge--neutral">{absence.status}</span>
                      </div>
                    </div>
                  </OmsorgCard>
                </button>
              );
            })}

            {absences.length === 0 && (
              <OmsorgCard>
                <div className="employees-empty-state">
                  <strong>Keinen Antrag gefunden</strong>

                  <span>Prüfe die eingestellten Filter.</span>
                </div>
              </OmsorgCard>
            )}

            {absences.length > 0 && (
              <OmsorgPagination page={page} totalPages={totalPages} onPageChange={setPage} />
            )}
          </div>

          <AbsenceDetailPanel absence={selectedAbsence} onChanged={handleDecided} />
        </div>
      )}
    </div>
  );
}
