import { useState, useEffect, useMemo } from 'react';
import { SigviewRecord as Signature } from "@/lib/pbtypes";
import { Coins, Gauge, HelpCircle, Pickaxe, Shield, Zap } from 'lucide-react';

export interface SignatureCategory {
  meta: SignatureCategoryMeta;
  signatures: Signature[];
  isVisible: boolean;
}
export interface SignatureCategoryMeta {
  id: string;
  name: string;
  matcher: RegExp;
  icon: JSX.Element;
  color: string;
}

const CATEGORY_PREFERENCES_KEY = 'signature-category-preferences';

const allCategories = new Map<string, SignatureCategoryMeta>([
  ["unknown", {
    matcher: /^$/i,
    id: "unknown",
    name: 'Unknown Sites',
    icon: <HelpCircle className="h-4 w-4 text-slate-400" />,
    color: "text-slate-400 border-slate-600"
  }],
  ["combat", {
    matcher: /^(?:combat|homefront)/i,
    id: "combat",
    name: 'Combat Sites',
    icon: <Zap className="h-4 w-4 text-red-400" />,
    color: "text-red-400 border-red-600"
  }],
  ["data_relic", {
    matcher: /^(?:data|relic)/i,
    id: "data_relic",
    name: 'Data/Relic Sites',
    icon: <Shield className="h-4 w-4 text-blue-400" />,
    color: "text-blue-400 border-blue-600"
  }],
  ["gas", {
    matcher: /^gas/i,
    id: "gas",
    name: 'Gas Sites',
    icon: <Gauge className="h-4 w-4 text-emerald-400" />,
    color: "bg-emerald-900/40 text-emerald-200 border-emerald-500 shadow-[0_0_15px_rgba(16,185,129,0.5)] hover:shadow-[0_0_20px_rgba(16,185,129,0.7)] transition-all duration-300"
  }],
  ["ore", {
    matcher: /^ore/i,
    id: "ore",
    name: 'Ore Sites',
    icon: <Pickaxe className="h-4 w-4 text-yellow-400" />,
    color: "text-yellow-400 border-yellow-600"
  }],
  ["wormhole", {
    matcher: /^wormhole/i,
    id: "wormhole",
    name: 'Wormholes',
    icon: <Coins className="h-4 w-4 text-purple-400" />,
    color: "text-purple-400 border-purple-600"
  }]
]);

export const getSignatureMeta = (type: string): SignatureCategoryMeta => {
  for (const category of allCategories.values()) {
    if (category.matcher.test(type)) {
      return category;
    }
  }
  return allCategories.get("unknown")!;
};

export const getSignatureTypes = (): string[] => {
  return [
    "Combat",
    "Homefront",
    "Data",
    "Relic",
    "Gas",
    "Ore",
    "Wormhole"
  ];
};

export const categorizeSignatures = (signatures: Map<string, Signature>): Record<string, Signature[]> => {
  const categories: Record<string, Signature[]> = {
    unknown: [],
    combat: [],
    data_relic: [],
    gas: [],
    ore: [],
    wormhole: []
  };

  signatures.forEach(signature => {
    const type = signature.type?.toLowerCase() || '';
    const meta = getSignatureMeta(type);
    categories[meta.id] = categories[meta.id] || [];
    categories[meta.id].push(signature);
  });
  return categories;
};

export const useSignatureCategories = (signatures: Map<string, Signature>) => {
  const [categoryVisibility, setCategoryVisibility] = useState<Record<string, boolean>>({
    unknown: true,
    combat: true,
    data_relic: true,
    gas: true,
    ore: true,
    wormhole: true
  });

  // Load preferences from localStorage on mount
  useEffect(() => {
    const saved = localStorage.getItem(CATEGORY_PREFERENCES_KEY);
    if (saved) {
      try {
        const preferences = JSON.parse(saved);
        setCategoryVisibility(prev => ({ ...prev, ...preferences }));
      } catch (error) {
        console.error('Failed to parse category preferences:', error);
      }
    }
  }, []);

  // Save preferences to localStorage when they change
  useEffect(() => {
    localStorage.setItem(CATEGORY_PREFERENCES_KEY, JSON.stringify(categoryVisibility));
  }, [categoryVisibility]);

  const categories = useMemo(() => {
    const categorized = categorizeSignatures(signatures);
    console.log(categorized);

    return [
      {
        meta: allCategories.get("unknown"),
        signatures: categorized.unknown,
        isVisible: categoryVisibility.unknown
      },
      {
        meta: allCategories.get("combat"),
        signatures: categorized.combat,
        isVisible: categoryVisibility.combat
      },
      {
        meta: allCategories.get("data_relic"),
        signatures: categorized.data_relic,
        isVisible: categoryVisibility.data_relic
      },
      {
        meta: allCategories.get("gas"),
        signatures: categorized.gas,
        isVisible: categoryVisibility.gas
      },
      {
        meta: allCategories.get("ore"),
        signatures: categorized.ore,
        isVisible: categoryVisibility.ore
      },
      {
        meta: allCategories.get("wormhole"),
        signatures: categorized.wormhole,
        isVisible: categoryVisibility.wormhole
      }
    ].filter(category => category.signatures.length > 0);
  }, [signatures, categoryVisibility]);

  const toggleCategoryVisibility = (categoryId: string) => {
    setCategoryVisibility(prev => ({
      ...prev,
      [categoryId]: !prev[categoryId]
    }));
  };

  return {
    categories,
    toggleCategoryVisibility
  };
};
