/**
 * useQRDecoder Hook
 * Custom React hook for decoding QR calculator data from URL parameters
 */

import { useState, useEffect } from 'react';
import { QRCalculatorData } from '../types';
import { extractQRDataFromUrl } from '../utils/qrDataEncoder';
import { validateQRData } from '../utils/qrDataValidator';

export interface QRDecoderResult {
  /**
   * Decoded and validated QR data
   */
  data: QRCalculatorData | null;

  /**
   * Whether QR data is currently being processed
   */
  isLoading: boolean;

  /**
   * Error message if decoding/validation failed
   */
  error: string | null;

  /**
   * Whether QR data was found in URL
   */
  hasQRData: boolean;
}

/**
 * Custom hook to decode and validate QR calculator data from URL parameters
 * Automatically extracts 'qr' parameter from current URL
 *
 * @example
 * ```tsx
 * function Calculator() {
 *   const { data, isLoading, error, hasQRData } = useQRDecoder();
 *
 *   if (isLoading) return <div>Loading...</div>;
 *   if (error) return <div>Error: {error}</div>;
 *   if (!hasQRData) return <div>No QR data found</div>;
 *
 *   // Use data to pre-fill calculator
 *   return <CalculatorForm initialData={data} />;
 * }
 * ```
 */
export function useQRDecoder(): QRDecoderResult {
  const [data, setData] = useState<QRCalculatorData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [hasQRData, setHasQRData] = useState(false);

  useEffect(() => {
    const decodeQRData = () => {
      try {
        // Get URL search params
        const searchParams = new URLSearchParams(window.location.search);

        // Check if QR parameter exists
        const qrParam = searchParams.get('qr');
        if (!qrParam) {
          setHasQRData(false);
          setIsLoading(false);
          return;
        }

        setHasQRData(true);

        // Extract and decode QR data
        const decodedData = extractQRDataFromUrl(searchParams);

        if (!decodedData) {
          setError('Failed to decode QR data');
          setIsLoading(false);
          return;
        }

        // Validate the decoded data
        const validationResult = validateQRData(decodedData);

        if (!validationResult.valid) {
          setError(validationResult.error || 'Invalid QR data');
          setIsLoading(false);
          return;
        }

        // Set validated data
        setData(validationResult.data || null);
        setError(null);
      } catch (err) {
        console.error('Error decoding QR data:', err);
        setError(err instanceof Error ? err.message : 'Unknown error occurred');
      } finally {
        setIsLoading(false);
      }
    };

    decodeQRData();
  }, []); // Run only once on mount

  return {
    data,
    isLoading,
    error,
    hasQRData,
  };
}

/**
 * Hook to check if current URL contains QR data parameter
 * Useful for conditional rendering without full decode
 *
 * @example
 * ```tsx
 * function App() {
 *   const hasQR = useHasQRData();
 *
 *   if (hasQR) {
 *     return <QRCalculatorLoader />;
 *   }
 *
 *   return <NormalCalculator />;
 * }
 * ```
 */
export function useHasQRData(): boolean {
  const [hasQRData, setHasQRData] = useState(false);

  useEffect(() => {
    const searchParams = new URLSearchParams(window.location.search);
    setHasQRData(searchParams.has('qr'));
  }, []);

  return hasQRData;
}

/**
 * Hook to remove QR parameter from URL without page reload
 * Useful after data has been extracted and stored in state
 *
 * @example
 * ```tsx
 * function Calculator() {
 *   const { data } = useQRDecoder();
 *   const clearQR = useClearQRParam();
 *
 *   useEffect(() => {
 *     if (data) {
 *       // Data extracted successfully, clean up URL
 *       clearQR();
 *     }
 *   }, [data]);
 * }
 * ```
 */
export function useClearQRParam(): () => void {
  return () => {
    try {
      const url = new URL(window.location.href);
      url.searchParams.delete('qr');

      // Update URL without page reload
      window.history.replaceState({}, '', url.toString());
    } catch (error) {
      console.error('Error clearing QR parameter:', error);
    }
  };
}
