import { useCallback, useEffect, useState } from "react";
import { Plus, Search, 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 FacilityDetailPanel from "./FacilityDetailPanel";
import CreateFacilityDialog from "./CreateFacilityDialog";
import { useValueListItems } from "../../app/useValueListItems";

const PAGE_SIZE = 20;

export default function FacilitiesPage() {
  const { hasPermission } = useAuth();
  const canCreate = hasPermission("Facilities", "Create");
  const { items: crmStatusOptions } = useValueListItems("CrmStatus");

  const [facilities, setFacilities] = useState([]);
  const [totalCount, setTotalCount] = useState(0);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [selectedFacilityId, setSelectedFacilityId] = useState(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState("");
  const [crmStatusFilter, setCrmStatusFilter] = useState("");
  const [followUpDueOnly, setFollowUpDueOnly] = useState(false);
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [page, setPage] = useState(1);
  const [isDialogOpen, setIsDialogOpen] = useState(false);

  useEffect(() => {
    const timer = setTimeout(() => setDebouncedSearch(searchTerm.trim()), 300);
    return () => clearTimeout(timer);
  }, [searchTerm]);

  useEffect(() => {
    setPage(1);
  }, [debouncedSearch, crmStatusFilter, followUpDueOnly]);

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

    const result = await window.omsorg.facilities.list({
      search: debouncedSearch || undefined,
      crmStatus: crmStatusFilter || undefined,
      followUpDueOnly: followUpDueOnly || undefined,
      page,
      pageSize: PAGE_SIZE,
    });

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

    setIsLoading(false);
  }, [debouncedSearch, crmStatusFilter, followUpDueOnly, page]);

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

  const selectedFacility = facilities.find((facility) => facility.id === selectedFacilityId) ?? null;
  const totalPages = Math.max(1, Math.ceil(totalCount / PAGE_SIZE));

  function handleCreated(createdFacility) {
    setIsDialogOpen(false);
    loadFacilities();
    if (createdFacility?.id) {
      setSelectedFacilityId(createdFacility.id);
    }
  }

  function handleUpdated() {
    loadFacilities();
  }

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

          <h1>Kunden</h1>

          <p className="page-description">
            Verwalte Einrichtungen, Ansprechpartner und den CRM-Status an einem Ort.
          </p>
        </div>

        {canCreate && (
          <OmsorgButton icon={Plus} onClick={() => setIsDialogOpen(true)}>
            Neue Einrichtung
          </OmsorgButton>
        )}
      </div>

      <OmsorgCard>
        <div className="employees-toolbar">
          <div className="employees-search">
            <Search size={18} />

            <input
              type="search"
              value={searchTerm}
              onChange={(event) => setSearchTerm(event.target.value)}
              placeholder="Einrichtung suchen..."
              aria-label="Einrichtung suchen"
            />
          </div>

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

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

            <label className="form-field form-field--checkbox">
              <input
                type="checkbox"
                checked={followUpDueOnly}
                onChange={(event) => setFollowUpDueOnly(event.target.checked)}
              />
              <span>Nur fällige Wiedervorlagen</span>
            </label>
          </div>
        )}
      </OmsorgCard>

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

      {!isLoading && (
        <div className="employees-layout">
          <div className="employees-list">
            {facilities.map((facility) => {
              const isSelected = facility.id === selectedFacilityId;

              return (
                <button
                  key={facility.id}
                  type="button"
                  className={
                    isSelected
                      ? "employee-list-button employee-list-button--active"
                      : "employee-list-button"
                  }
                  onClick={() => setSelectedFacilityId(facility.id)}
                >
                  <OmsorgCard>
                    <div className="employee-row">
                      <div className="employee-main">
                        <strong>{facility.name}</strong>
                        {facility.facilityType && <span> — {facility.facilityType}</span>}
                      </div>

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

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

                  <span>Prüfe den eingegebenen Suchbegriff oder die Filter.</span>
                </div>
              </OmsorgCard>
            )}

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

          <FacilityDetailPanel facility={selectedFacility} onUpdated={handleUpdated} />
        </div>
      )}

      {isDialogOpen && (
        <CreateFacilityDialog onClose={() => setIsDialogOpen(false)} onCreated={handleCreated} />
      )}
    </div>
  );
}
