'use client';

import React, { useState } from 'react';
import { Fab, Tooltip, Snackbar, Alert } from '@mui/material';
import MicIcon from '@mui/icons-material/Mic';
import { VoiceInputButton } from './VoiceInputButton';
import { useRouter } from 'next/navigation';

/**
 * Floating voice input button
 *
 * Always visible floating action button for quick voice commands.
 * Positioned in bottom-right corner for easy thumb access.
 */
export function VoiceFloatingButton() {
  const router = useRouter();
  const [snackbar, setSnackbar] = useState<{
    open: boolean;
    message: string;
    severity: 'success' | 'info' | 'warning' | 'error';
  }>({
    open: false,
    message: '',
    severity: 'info',
  });

  const handleTranscript = (transcript: string) => {
    console.log('[Voice] Transcript:', transcript);
    setSnackbar({
      open: true,
      message: `Command received: "${transcript}"`,
      severity: 'info',
    });
  };

  const handleClassifiedIntent = (result: any) => {
    console.log('[Voice] Classification:', result);

    if (result.error) {
      setSnackbar({
        open: true,
        message: result.message,
        severity: 'error',
      });
      return;
    }

    // Show success message
    setSnackbar({
      open: true,
      message: `Understood: ${result.intent} command`,
      severity: 'success',
    });

    // Navigate to appropriate page based on intent
    // This is a placeholder - in production, you'd create the activity
    setTimeout(() => {
      if (result.intent === 'feeding') {
        router.push('/track/feeding');
      } else if (result.intent === 'sleep') {
        router.push('/track/sleep');
      } else if (result.intent === 'diaper') {
        router.push('/track/diaper');
      }
    }, 1500);
  };

  const handleCloseSnackbar = () => {
    setSnackbar(prev => ({ ...prev, open: false }));
  };

  return (
    <>
      {/* Floating button positioned in bottom-right */}
      <Tooltip title="Voice Command (Beta)" placement="left">
        <Fab
          color="primary"
          aria-label="voice input"
          sx={{
            position: 'fixed',
            bottom: 24,
            right: 24,
            zIndex: 1000,
          }}
        >
          <VoiceInputButton
            onTranscript={handleTranscript}
            onClassifiedIntent={handleClassifiedIntent}
            size="large"
            variant="fab"
          />
        </Fab>
      </Tooltip>

      {/* Snackbar for feedback */}
      <Snackbar
        open={snackbar.open}
        autoHideDuration={3000}
        onClose={handleCloseSnackbar}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert
          onClose={handleCloseSnackbar}
          severity={snackbar.severity}
          sx={{ width: '100%' }}
        >
          {snackbar.message}
        </Alert>
      </Snackbar>
    </>
  );
}
