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 TimeEntryDetailPanel from "./TimeEntryDetailPanel";

const PAGE_SIZE = 20;

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

export default function TimeEntriesPage() {
  const { hasPermission } = useAuth();
  const { items: statusOptions } = useValueListItems("TimeEntryStatus");

  const [timeEntries, setTimeEntries] = useState([]);
  const [totalCount, setTotalCount] = useState(0);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [selectedTimeEntryId, setSelectedTimeEntryId] = useState(null);
  const [statusFilter, setStatusFilter] = useState("");
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [page, setPage] = useState(1);

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

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

    const result = await window.omsorg.timeEntries.list({
      statusId: statusFilter || undefined,
      page,
      pageSize: PAGE_SIZE,
    });

    if (result.ok) {
      const data = result.data ?? { items: [], totalCount: 0 };
      setTimeEntries(data.items ?? []);
      setTotalCount(data.totalCount ?? 0);
      setSelectedTimeEntryId((current) =>
        (data.items ?? []).some((entry) => entry.id === current) ? current : data.items?.[0]?.id ?? null
      );
    } else {
      setError("Zeiterfassungen konnten nicht geladen werden.");
    }

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

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

  const selectedTimeEntry = timeEntries.find((entry) => entry.id === selectedTimeEntryId) ?? null;
  const totalPages = Math.max(1, Math.ceil(totalCount / PAGE_SIZE));

  function handleChanged() {
    loadTimeEntries();
  }

  if (!hasPermission("TimeEntries", "View")) {
    return (
      <OmsorgCard title="Zeiterfassung">
        <p>Keine Berechtigung, Zeiterfassungen einzusehen.</p>
      </OmsorgCard>
    );
  }

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

          <h1>Zeiterfassung</h1>

          <p className="page-description">
            Erfasste Schichten des Außendienstes prüfen und durch die Statuspipeline freigeben.
          </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.id}>
                    {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">
            {timeEntries.map((entry) => {
              const isSelected = entry.id === selectedTimeEntryId;

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

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

            {timeEntries.length === 0 && (
              <OmsorgCard>
                <div className="employees-empty-state">
                  <strong>Keine Zeiterfassung gefunden</strong>

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

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

          <TimeEntryDetailPanel timeEntry={selectedTimeEntry} onChanged={handleChanged} />
        </div>
      )}
    </div>
  );
}
