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

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

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

const TABS = [
  {
    key: "employees",
    label: "Mitarbeiter",
    module: "Employees",
    list: (search) => window.omsorg.trash.listEmployees(search),
    restore: (id) => window.omsorg.trash.restoreEmployee(id),
    displayName: (item) => `${item.firstName} ${item.lastName}`.trim(),
  },
  {
    key: "facilities",
    label: "Einrichtungen",
    module: "Facilities",
    list: (search) => window.omsorg.trash.listFacilities(search),
    restore: (id) => window.omsorg.trash.restoreFacility(id),
    displayName: (item) => item.name,
  },
  {
    key: "contracts",
    label: "Verträge",
    module: "Contracts",
    list: (search) => window.omsorg.trash.listContracts(search),
    restore: (id) => window.omsorg.trash.restoreContract(id),
    displayName: (item) => item.contractType,
  },
  {
    key: "orders",
    label: "Aufträge",
    module: "Orders",
    list: (search) => window.omsorg.trash.listOrders(search),
    restore: (id) => window.omsorg.trash.restoreOrder(id),
    displayName: (item) => item.requiredQualification ?? "Auftrag",
  },
  {
    key: "facilityContacts",
    label: "Ansprechpartner",
    module: "Facilities",
    list: (search) => window.omsorg.trash.listFacilityContacts(search),
    restore: (id) => window.omsorg.trash.restoreFacilityContact(id),
    displayName: (item) => item.name,
  },
  {
    key: "facilityQualificationRates",
    label: "Qualifikationspreise",
    module: "Facilities",
    list: (search) => window.omsorg.trash.listFacilityQualificationRates(search),
    restore: (id) => window.omsorg.trash.restoreFacilityQualificationRate(id),
    displayName: (item) => item.qualification,
  },
  {
    key: "employeeFacilityDistances",
    label: "Entfernungen",
    module: "Facilities",
    list: (search) => window.omsorg.trash.listEmployeeFacilityDistances(search),
    restore: (id) => window.omsorg.trash.restoreEmployeeFacilityDistance(id),
    displayName: (item) => `${item.distanceKm} km`,
  },
  {
    key: "absences",
    label: "Abwesenheiten",
    module: "Absences",
    list: (search) => window.omsorg.trash.listAbsences(search),
    restore: (id) => window.omsorg.trash.restoreAbsence(id),
    displayName: (item) => item.type,
  },
  {
    key: "timeEntries",
    label: "Zeiterfassung",
    module: "TimeEntries",
    list: (search) => window.omsorg.trash.listTimeEntries(search),
    restore: (id) => window.omsorg.trash.restoreTimeEntry(id),
    displayName: (item) => new Date(item.date).toLocaleDateString("de-DE"),
  },
  {
    key: "assignments",
    label: "Zuweisungen",
    module: "Assignments",
    list: (search) => window.omsorg.trash.listAssignments(search),
    restore: (id) => window.omsorg.trash.restoreAssignment(id),
    displayName: (item) => `${item.employeeFirstName} ${item.employeeLastName}`.trim(),
  },
];

export default function TrashPage() {
  const { hasPermission } = useAuth();

  const visibleTabs = useMemo(() => TABS.filter((tab) => hasPermission(tab.module, "Recover")), [hasPermission]);

  const [activeKey, setActiveKey] = useState(visibleTabs[0]?.key ?? null);
  const [items, setItems] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState("");
  const [restoringId, setRestoringId] = useState(null);

  const activeTab = visibleTabs.find((tab) => tab.key === activeKey) ?? visibleTabs[0] ?? null;

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

  const loadItems = useCallback(async () => {
    if (!activeTab) return;

    setIsLoading(true);
    setError(null);

    const result = await activeTab.list(debouncedSearch || undefined);

    if (result.ok) {
      setItems(result.data ?? []);
    } else {
      setError("Papierkorb konnte nicht geladen werden.");
    }

    setIsLoading(false);
  }, [activeTab, debouncedSearch]);

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

  async function handleRestore(id) {
    if (!activeTab) return;

    setRestoringId(id);
    const result = await activeTab.restore(id);
    setRestoringId(null);

    if (result.ok) {
      loadItems();
    }
  }

  if (visibleTabs.length === 0) {
    return (
      <OmsorgCard title="Papierkorb">
        <p>Keine Berechtigung, gelöschte Datensätze wiederherzustellen.</p>
      </OmsorgCard>
    );
  }

  return (
    <OmsorgCard title="Papierkorb">
      <p>Gelöschte Datensätze können hier wiederhergestellt werden.</p>

      <div className="employees-toolbar">
        {visibleTabs.map((tab) => (
          <OmsorgButton
            key={tab.key}
            variant={tab.key === activeTab?.key ? "primary" : "secondary"}
            onClick={() => setActiveKey(tab.key)}
          >
            {tab.label}
          </OmsorgButton>
        ))}
      </div>

      <div className="employees-search">
        <Search size={18} />
        <input
          type="search"
          value={searchTerm}
          onChange={(event) => setSearchTerm(event.target.value)}
          placeholder="Suchen..."
          aria-label="Papierkorb durchsuchen"
        />
      </div>

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

      {!isLoading && !error && items.length === 0 && <p>Keine gelöschten Einträge.</p>}

      {items.length > 0 && (
        <ul className="debug-sessions-list">
          {items.map((item) => (
            <li key={item.id} className="debug-sessions-row">
              <div>
                <strong>{activeTab.displayName(item) || "—"}</strong>
                <p className="debug-sessions-meta">Gelöscht am {formatDate(item.deletedAt)}</p>
              </div>

              <OmsorgButton
                variant="secondary"
                onClick={() => handleRestore(item.id)}
                disabled={restoringId === item.id}
              >
                Wiederherstellen
              </OmsorgButton>
            </li>
          ))}
        </ul>
      )}
    </OmsorgCard>
  );
}
