import { useState, useEffect } from "react";
import { AlertTriangle } from "lucide-react";
import { useUsers } from "../lib/useUsers";
import { SearchFilterBar } from "./components/SearchFilterBar";
import { UserTable } from "./components/UserTable";
import { UserPagination } from "./components/UserPagination";
import { UserDetailPanel } from "./components/UserDetailPanel";

// ---------------------------------------------------------------------------
// Main Users Component
// ---------------------------------------------------------------------------

export default function Users() {
  const {
    users,
    total,
    currentPage,
    limit,
    setLimit,
    filters,
    setFilters,
    setSearchDebounced,
    setPage,
    selectedUser,
    selectUser,
    closeDetail,
    userDraft,
    updateDraft,
    saveDraft,
    discardDraft,
    isDirty,
    inventoryDraft,
    addInventoryItem,
    removeInventoryItem,
    classes,
    items,
    loading,
    saving,
    error,
  } = useUsers();

  const [saveSuccess, setSaveSuccess] = useState(false);
  const [searchInput, setSearchInput] = useState(filters.search);

  // Sync searchInput with filters.search when it changes externally
  useEffect(() => {
    setSearchInput(filters.search);
  }, [filters.search]);

  // Keyboard shortcuts
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape" && selectedUser) {
        if (isDirty) {
          const confirm = window.confirm(
            "You have unsaved changes. Are you sure you want to close?"
          );
          if (confirm) closeDetail();
        } else {
          closeDetail();
        }
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [selectedUser, isDirty, closeDetail]);

  const handleSave = async () => {
    const success = await saveDraft();
    if (success) {
      setSaveSuccess(true);
      setTimeout(() => setSaveSuccess(false), 2000);
    }
  };

  const handleClearFilters = () => {
    setSearchInput("");
    setFilters({
      search: "",
      classId: null,
      isActive: null,
      sortBy: "balance",
      sortOrder: "desc",
    });
  };

  const handleSearchChange = (value: string) => {
    setSearchInput(value);
    setSearchDebounced(value);
  };

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <header className="border-b border-border p-6 space-y-4">
        <h1 className="text-2xl font-bold text-foreground">Users</h1>
        <SearchFilterBar
          search={searchInput}
          onSearchChange={handleSearchChange}
          classId={filters.classId}
          onClassChange={(v) => setFilters({ classId: v })}
          isActive={filters.isActive}
          onActiveChange={(v) => setFilters({ isActive: v })}
          sortBy={filters.sortBy}
          onSortByChange={(v) => setFilters({ sortBy: v as any })}
          sortOrder={filters.sortOrder}
          onSortOrderChange={(v) => setFilters({ sortOrder: v as any })}
          onClear={handleClearFilters}
          classes={classes}
        />
      </header>

      {/* Error banner */}
      {error && (
        <div className="mx-6 mt-4 bg-destructive/10 border border-destructive/30 rounded-lg p-4 flex items-start gap-3">
          <AlertTriangle className="w-5 h-5 text-destructive flex-shrink-0 mt-0.5" />
          <div className="flex-1">
            <p className="text-sm font-semibold text-destructive">Error</p>
            <p className="text-sm text-destructive/90">{error}</p>
          </div>
        </div>
      )}

      {/* Content area */}
      <div className="flex-1 flex overflow-hidden">
        {/* Main content */}
        <div className="flex-1 overflow-auto p-6">
          <UserTable users={users} loading={loading} onSelectUser={selectUser} />
          <UserPagination
            currentPage={currentPage}
            totalPages={Math.ceil(total / limit)}
            limit={limit}
            total={total}
            onPageChange={setPage}
            onLimitChange={setLimit}
          />
        </div>

        {/* Detail panel */}
        {selectedUser && userDraft && (
          <UserDetailPanel
            user={selectedUser}
            userDraft={userDraft}
            onClose={closeDetail}
            onUpdateDraft={updateDraft}
            onSave={handleSave}
            onDiscard={discardDraft}
            isDirty={isDirty}
            saving={saving}
            saveSuccess={saveSuccess}
            classes={classes}
            inventoryDraft={inventoryDraft}
            items={items}
            onAddItem={(itemId, quantity) =>
              addInventoryItem(selectedUser.id, itemId, quantity)
            }
            onRemoveItem={(itemId) => removeInventoryItem(selectedUser.id, itemId)}
          />
        )}
      </div>
    </div>
  );
}
