"use client";

import { useState, useEffect, useCallback } from "react";
import { useStorage } from "@/core/storage";
import { v4 as uuid } from "uuid";
import type { InventoryItem, InventoryItemStatus } from "../types";

const PREFIX = "item:";

export interface InventoryFilters {
  search: string;
  type: string;
  status: InventoryItemStatus | "all";
  company: string;
}

export function useInventory() {
  const storage = useStorage("it-inventory");
  const [items, setItems] = useState<InventoryItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [filters, setFilters] = useState<InventoryFilters>({
    search: "",
    type: "all",
    status: "all",
    company: "all",
  });

  const refresh = useCallback(async () => {
    setLoading(true);
    const all = await storage.exportAll();
    const results: InventoryItem[] = [];
    for (const [key, value] of Object.entries(all)) {
      if (key.startsWith(PREFIX) && value) {
        results.push(value as InventoryItem);
      }
    }
    results.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
    setItems(results);
    setLoading(false);
  }, [storage]);

  // eslint-disable-next-line react-hooks/set-state-in-effect
  useEffect(() => {
    refresh();
  }, [refresh]);

  const addItem = useCallback(
    async (data: Omit<InventoryItem, "id" | "createdAt" | "updatedAt">) => {
      const now = new Date().toISOString();
      const item: InventoryItem = {
        ...data,
        id: uuid(),
        createdAt: now,
        updatedAt: now,
      };
      await storage.set(`${PREFIX}${item.id}`, item);
      await refresh();
      return item;
    },
    [storage, refresh],
  );

  const updateItem = useCallback(
    async (id: string, updates: Partial<InventoryItem>) => {
      const existing = items.find((i) => i.id === id);
      if (!existing) return;
      const updated: InventoryItem = {
        ...existing,
        ...updates,
        id: existing.id,
        createdAt: existing.createdAt,
        updatedAt: new Date().toISOString(),
      };
      await storage.set(`${PREFIX}${id}`, updated);
      await refresh();
    },
    [storage, refresh, items],
  );

  const removeItem = useCallback(
    async (id: string) => {
      await storage.delete(`${PREFIX}${id}`);
      await refresh();
    },
    [storage, refresh],
  );

  const updateFilter = useCallback(
    <K extends keyof InventoryFilters>(key: K, value: InventoryFilters[K]) => {
      setFilters((prev) => ({ ...prev, [key]: value }));
    },
    [],
  );

  const filteredItems = items.filter((item) => {
    if (filters.type !== "all" && item.type !== filters.type) return false;
    if (filters.status !== "all" && item.status !== filters.status)
      return false;
    if (filters.company !== "all" && item.company !== filters.company)
      return false;
    if (filters.search) {
      const q = filters.search.toLowerCase();
      return (
        item.name.toLowerCase().includes(q) ||
        item.serialNumber.toLowerCase().includes(q) ||
        item.ipAddress.toLowerCase().includes(q) ||
        item.vendor.toLowerCase().includes(q) ||
        item.model.toLowerCase().includes(q) ||
        item.location.toLowerCase().includes(q) ||
        item.rackLocation.toLowerCase().includes(q)
      );
    }
    return true;
  });

  return {
    items: filteredItems,
    allItems: items,
    loading,
    filters,
    updateFilter,
    addItem,
    updateItem,
    removeItem,
    refresh,
  };
}
