import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '../services/api';
import toast from 'react-hot-toast';

/**
 * License Info Type
 */
export interface LicenseInfo {
  tier: 'free' | 'pro';
  license_key: string | null;
  expires: string | null;
  is_valid: boolean;
  features: {
    csv_export_limit: boolean;
    csv_import_limit: boolean;
    xlsx_export: boolean;
    xlsx_import: boolean;
    bulk_operations_limit: boolean;
    sku_generator: boolean;
    attribute_manager: boolean;
    performance_tools: boolean;
  };
  limits: {
    csv_export_limit: number;
    csv_import_limit: number;
    bulk_operations_limit: number;
    image_bulk_assign_limit: number;
  };
  total_variations: number;
}

/**
 * Get license info
 */
export function useLicenseInfo() {
  return useQuery<LicenseInfo>({
    queryKey: ['license', 'info'],
    queryFn: async () => {
      const response = await api.get('/license/info');
      return response.data.data;
    },
    staleTime: 60000, // 1 minute
    refetchOnWindowFocus: false,
  });
}

/**
 * Activate license
 */
export function useActivateLicense() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: async (licenseKey: string) => {
      const response = await api.post('/license/activate', {
        license_key: licenseKey,
      });
      return response.data;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['license'] });
      toast.success(data.message || 'Licenc sikeresen aktiválva!');
    },
    onError: (error: any) => {
      const message = error.response?.data?.message || 'Aktiválási hiba';
      toast.error(message);
    },
  });
}

/**
 * Deactivate license
 */
export function useDeactivateLicense() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: async () => {
      const response = await api.post('/license/deactivate');
      return response.data;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['license'] });
      toast.success(data.message || 'Licenc deaktiválva');
    },
    onError: (error: any) => {
      const message = error.response?.data?.message || 'Deaktiválási hiba';
      toast.error(message);
    },
  });
}

/**
 * Check if a feature is available
 */
export function useCheckFeature(featureName: string) {
  return useQuery<boolean>({
    queryKey: ['license', 'feature', featureName],
    queryFn: async () => {
      const response = await api.get('/license/check-feature', {
        params: { feature: featureName },
      });
      return response.data.data.available;
    },
    staleTime: 60000,
    enabled: !!featureName,
  });
}

/**
 * Check if FREE tier limit is exceeded (frontend soft warning)
 */
export function useCheckLimit(limitType: 'csv_export' | 'csv_import' | 'bulk_operations', count: number) {
  const { data: licenseInfo } = useLicenseInfo();
  
  // Safety: Return safe defaults if license info not loaded yet
  if (!licenseInfo || licenseInfo.tier !== 'free') {
    return { exceeded: false, limit: -1, message: null };
  }
  
  const limitMap = {
    csv_export: licenseInfo.limits?.csv_export_limit ?? 200,
    csv_import: licenseInfo.limits?.csv_import_limit ?? 200,
    bulk_operations: licenseInfo.limits?.bulk_operations_limit ?? 10,
  };
  
  const limit = limitMap[limitType];
  const exceeded = limit > 0 && count > limit;
  
  const messageMap = {
    csv_export: `Ingyenes verzióban max ${limit} sor exportálható. Kiválasztva: ${count}. Frissíts PRO verzióra!`,
    csv_import: `Ingyenes verzióban max ${limit} sor importálható. A fájl ${count} sort tartalmaz. Frissíts PRO verzióra!`,
    bulk_operations: `Ingyenes verzióban max ${limit} variáció módosítható egyszerre. Kijelölve: ${count}. Frissíts PRO verzióra!`,
  };
  
  return {
    exceeded,
    limit,
    message: exceeded ? messageMap[limitType] : null,
  };
}
