/**
 * Printer Selection Component
 * Allows users to select a label printer from available printers
 * Uses real-time printer detection from print service (no localStorage caching)
 */

'use client';

import { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { getAvailablePrinters, checkPrintServiceHealth } from '@/lib/utils/printerClient';
import { Select, LoadingSpinner } from '@/components/ui';
import { Printer, RefreshCw, AlertCircle } from 'lucide-react';
import toast from 'react-hot-toast';

export default function PrinterSelect({
  value,
  onChange,
  label = 'Select Printer',
  showRefresh = true,
  autoSelect = true
}) {
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [serviceStatus, setServiceStatus] = useState('checking');

  // Check print service health
  useEffect(() => {
    const checkHealth = async () => {
      const isHealthy = await checkPrintServiceHealth();
      setServiceStatus(isHealthy ? 'online' : 'offline');
    };
    checkHealth();
  }, []);

  // Fetch available printers (real-time from service)
  const { data: printers = [], isLoading, error, refetch } = useQuery({
    queryKey: ['available-printers'],
    queryFn: async () => {
      const printers = await getAvailablePrinters();
      return printers || [];
    },
    staleTime: 0, // Always fetch fresh - no cache
    retry: false, // Don't retry automatically if service is down
  });

  // Auto-select first printer if none selected (optional preference check)
  useEffect(() => {
    if (printers.length > 0 && !value && autoSelect) {
      const printerToSelect = printers[0].name;
      onChange?.(printerToSelect);
    }
  }, [printers, value, autoSelect, onChange]);

  const handleRefresh = async () => {
    setIsRefreshing(true);
    try {
      // Check health first
      const isHealthy = await checkPrintServiceHealth();
      setServiceStatus(isHealthy ? 'online' : 'offline');
      
      await refetch();
      toast.success('Printers refreshed');
    } catch (error) {
      const errorMessage = error?.message || 'Failed to refresh printers';
      toast.error(errorMessage);
      setServiceStatus('offline');
    } finally {
      setIsRefreshing(false);
    }
  };

  const selectedPrinter = printers.find(p => p.name === value);

  // Show loading state
  if (isLoading) {
    return (
      <div className="flex items-center gap-2">
        <LoadingSpinner size="sm" />
        <span className="text-sm text-gray-600 dark:text-gray-400">Loading printers...</span>
      </div>
    );
  }

  // Show error state
  if (error || serviceStatus === 'offline') {
    let errorMessage = error?.message || 'Print service is not available';

    if (
      errorMessage.includes('Cannot connect to print service') ||
      errorMessage.includes('Print service timeout') ||
      errorMessage.includes('Failed to fetch') ||
      errorMessage.includes('fetch')
    ) {
      errorMessage = 'Cannot reach the local print service. Ensure XYZ POS Print Service is running on 127.0.0.1:9101.';
    } else if (errorMessage.includes('Unauthorized') || errorMessage.includes('401')) {
      errorMessage = 'Print service authentication failed. Check API key configuration.';
    }
    return (
      <div className="space-y-2">
        <div className="flex items-start gap-2 p-3 bg-red-50 dark:bg-red-950 border border-red-200 dark:border-red-800 rounded-lg">
          <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400 mt-0.5 flex-shrink-0" />
          <div className="flex-1">
            <p className="text-sm font-medium text-red-900 dark:text-red-100">
              Print service unavailable
            </p>
            <p className="text-xs text-red-800 dark:text-red-200 mt-1">
              {errorMessage}
            </p>
            <p className="text-xs text-red-700 dark:text-red-300 mt-1">
              Please ensure the XYZ POS Print Service is running on 127.0.0.1:9101
            </p>
          </div>
        </div>
        {showRefresh && (
          <button
            type="button"
            onClick={handleRefresh}
            disabled={isRefreshing}
            className="flex items-center gap-2 px-3 py-1.5 text-sm text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 disabled:opacity-50"
          >
            <RefreshCw className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} />
            Retry
          </button>
        )}
      </div>
    );
  }

  // Show no printers found
  if (printers.length === 0) {
    return (
      <div className="space-y-2">
        <div className="text-sm text-gray-600 dark:text-gray-400">
          No label printers detected. Please connect a label printer and ensure it is properly installed.
        </div>
        {showRefresh && (
          <button
            type="button"
            onClick={handleRefresh}
            disabled={isRefreshing}
            className="flex items-center gap-2 px-3 py-1.5 text-sm text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 disabled:opacity-50"
          >
            <RefreshCw className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} />
            Refresh
          </button>
        )}
      </div>
    );
  }

  return (
    <div className="space-y-2">
      <div className="flex items-center gap-2">
        <Select
          value={value || ''}
          onChange={(e) => onChange?.(e.target.value)}
          className="flex-1"
        >
          <option value="">-- {label} --</option>
          {printers.map((printer) => (
            <option key={printer.name} value={printer.name}>
              {printer.name} {printer.dpi ? `(${printer.dpi} DPI)` : ''} {printer.port ? `- ${printer.port}` : ''}
            </option>
          ))}
        </Select>
        {showRefresh && (
          <button
            type="button"
            onClick={handleRefresh}
            disabled={isRefreshing}
            className="p-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 disabled:opacity-50"
            title="Refresh printers"
          >
            <RefreshCw className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} />
          </button>
        )}
      </div>
      {selectedPrinter && (
        <div className="flex items-center justify-between">
          <div className="text-xs text-gray-500 dark:text-gray-400 flex items-center gap-1">
            <Printer className="w-3 h-3" />
            <span>
              {selectedPrinter.brand} • {selectedPrinter.dpi || 203} DPI • {selectedPrinter.port || 'Unknown port'}
            </span>
          </div>
          {serviceStatus === 'online' && (
            <span className="text-xs text-green-600 dark:text-green-400 flex items-center gap-1">
              <span className="w-2 h-2 bg-green-500 rounded-full"></span>
              Service Online
            </span>
          )}
        </div>
      )}
    </div>
  );
}
