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 { useValueListItems } from "../../app/useValueListItems";
import OrderDetailPanel from "./OrderDetailPanel";
import CreateOrderDialog from "./CreateOrderDialog";

const PAGE_SIZE = 20;

export default function OrdersPage() {
  const { hasPermission } = useAuth();
  const canCreate = hasPermission("Orders", "Create");
  const { items: statusOptions } = useValueListItems("OrderStatus");
  const { items: priorityOptions } = useValueListItems("Priority");
  const { items: qualificationOptions } = useValueListItems("Qualification");
  const { items: shiftTypeOptions } = useValueListItems("ShiftType");

  const [orders, setOrders] = useState([]);
  const [facilities, setFacilities] = useState([]);
  const [totalCount, setTotalCount] = useState(0);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [selectedOrderId, setSelectedOrderId] = useState(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [priorityFilter, setPriorityFilter] = useState("");
  const [facilityFilter, setFacilityFilter] = useState("");
  const [qualificationFilter, setQualificationFilter] = useState("");
  const [shiftTypeFilter, setShiftTypeFilter] = useState("");
  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, statusFilter, priorityFilter, facilityFilter, qualificationFilter, shiftTypeFilter]);

  useEffect(() => {
    window.omsorg.facilities.list({ pageSize: 200 }).then((result) => {
      if (result.ok) {
        setFacilities(result.data?.items ?? []);
      }
    });
  }, []);

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

    const result = await window.omsorg.orders.list({
      search: debouncedSearch || undefined,
      statusId: statusFilter || undefined,
      priority: priorityFilter || undefined,
      facilityId: facilityFilter || undefined,
      requiredQualification: qualificationFilter || undefined,
      shiftType: shiftTypeFilter || undefined,
      page,
      pageSize: PAGE_SIZE,
    });

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

    setIsLoading(false);
  }, [debouncedSearch, statusFilter, priorityFilter, facilityFilter, qualificationFilter, shiftTypeFilter, page]);

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

  const facilityNameById = new Map(facilities.map((facility) => [facility.id, facility.name]));
  const selectedOrder = orders.find((order) => order.id === selectedOrderId) ?? null;
  const totalPages = Math.max(1, Math.ceil(totalCount / PAGE_SIZE));

  function handleCreated(createdOrder) {
    setIsDialogOpen(false);
    loadOrders();
    if (createdOrder?.id) {
      setSelectedOrderId(createdOrder.id);
    }
  }

  function handleUpdated() {
    loadOrders();
  }

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

          <h1>Aufträge</h1>

          <p className="page-description">Verwalte Aufträge und ihren Bearbeitungsstatus an einem Ort.</p>
        </div>

        {canCreate && (
          <OmsorgButton icon={Plus} onClick={() => setIsDialogOpen(true)}>
            Neuer Auftrag
          </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="Auftrag suchen..."
              aria-label="Auftrag 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>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>

            <label className="form-field">
              <span>Priorität</span>
              <select value={priorityFilter} onChange={(event) => setPriorityFilter(event.target.value)}>
                <option value="">Alle</option>
                {priorityOptions.map((option) => (
                  <option key={option.id} value={option.value}>
                    {option.value}
                  </option>
                ))}
              </select>
            </label>

            <label className="form-field">
              <span>Einrichtung</span>
              <select value={facilityFilter} onChange={(event) => setFacilityFilter(event.target.value)}>
                <option value="">Alle</option>
                {facilities.map((facility) => (
                  <option key={facility.id} value={facility.id}>
                    {facility.name}
                  </option>
                ))}
              </select>
            </label>

            <label className="form-field">
              <span>Qualifikation</span>
              <select value={qualificationFilter} onChange={(event) => setQualificationFilter(event.target.value)}>
                <option value="">Alle</option>
                {qualificationOptions.map((option) => (
                  <option key={option.id} value={option.value}>
                    {option.value}
                  </option>
                ))}
              </select>
            </label>

            <label className="form-field">
              <span>Schichtart</span>
              <select value={shiftTypeFilter} onChange={(event) => setShiftTypeFilter(event.target.value)}>
                <option value="">Alle</option>
                {shiftTypeOptions.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">
            {orders.map((order) => {
              const isSelected = order.id === selectedOrderId;

              return (
                <button
                  key={order.id}
                  type="button"
                  className={
                    isSelected ? "employee-list-button employee-list-button--active" : "employee-list-button"
                  }
                  onClick={() => setSelectedOrderId(order.id)}
                >
                  <OmsorgCard>
                    <div className="employee-row">
                      <div className="employee-main">
                        <strong>{facilityNameById.get(order.facilityId) ?? "—"}</strong>
                        {order.requiredQualification && <span> — {order.requiredQualification}</span>}
                      </div>

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

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

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

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

          <OrderDetailPanel
            order={selectedOrder}
            facilityName={selectedOrder ? facilityNameById.get(selectedOrder.facilityId) : null}
            facilities={facilities}
            onUpdated={handleUpdated}
          />
        </div>
      )}

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