import React, { useRef, useEffect, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Send, Plus, Paperclip, Mic, FileText, Radio, Search, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '../../ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '../../ui/popover';
import { toast } from 'sonner';

/**
 * Supported special action types for the chat input.
 * - 'document': Triggers document generation workflow.
 * - 'podcast': Triggers audio podcast generation.
 * - 'search': Triggers a knowledge base search.
 */
export type ActionType = 'document' | 'podcast' | 'search' | null;

/**
 * Props for the ModernChatInput component.
 */
interface ModernChatInputProps {
  /** Current input text value */
  value: string;
  /** Callback fired on every keystroke */
  onChange: (value: string) => void;
  /** Callback fired when the user submits (via Enter or click) */
  onSubmit: (action?: ActionType) => void;
  /** Input placeholder text */
  placeholder?: string;
  /** Whether the input is disabled */
  disabled?: boolean;
  /** Callback for file attachment button */
  onFileUpload?: () => void;
  /** Callback for audio upload button */
  onAudioUpload?: () => void;
  /** Callback fired when a voice recording is finished and transcribed */
  onVoiceRecording?: (transcript: string) => void;
  /** Whether the input is being used in a full-page view (affects layout) */
  isFullPage?: boolean;
  /** Whether to show audio input (voice recording). @default true */
  enableAudioInput?: boolean;
  /** Whether to show the file attachment button. @default true */
  enableFileAttachment?: boolean;
  /** Whether to show the "Create document" action. @default true */
  enableDocumentCreation?: boolean;
  /** Whether to show the "Generate podcast" action. @default true */
  enablePodcastGeneration?: boolean;
  /** Whether to show the "Search" action. @default true */
  enableSearch?: boolean;
}

/**
 * Modern floating chat input with rich actions and voice recording.
 *
 * @description
 * An advanced text input that supports multi-line typing, quick action chips
 * (Document, Podcast, Search), file attachments, and simulated voice-to-text recording.
 *
 * @ai-rules
 * 1. Use the `onSubmit` callback to handle both text messages and special actions.
 * 2. This component manages its own height dynamically based on content (up to 100px).
 * 3. Voice recording is simulated — it returns a random string to the `onVoiceRecording` callback.
 */
export function ModernChatInput({
  value,
  onChange,
  onSubmit,
  placeholder,
  disabled = false,
  onFileUpload,
  onAudioUpload,
  onVoiceRecording,
  isFullPage = false,
  enableAudioInput = true,
  enableFileAttachment = true,
  enableDocumentCreation = true,
  enablePodcastGeneration = true,
  enableSearch = true,
}: ModernChatInputProps) {
  const { t } = useTranslation();
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const [isFocused, setIsFocused] = useState(false);
  const [textareaHeight, setTextareaHeight] = useState(20);
  const [selectedAction, setSelectedAction] = useState<ActionType>(null);
  const [isPopoverOpen, setIsPopoverOpen] = useState(false);
  const [isRecording, setIsRecording] = useState(false);
  const [recordingTime, setRecordingTime] = useState(0);
  const recordingIntervalRef = useRef<NodeJS.Timeout | null>(null);

  // Resolve placeholder: caller prop takes precedence, then i18n key
  const resolvedPlaceholder = placeholder ?? t('assistant.inputPlaceholder');

  const adjustHeight = () => {
    const textarea = textareaRef.current;
    if (textarea) {
      // Reset to minimum height first
      textarea.style.height = '20px';

      // Calculate new height based on content
      const scrollHeight = textarea.scrollHeight;
      const newHeight = Math.min(Math.max(scrollHeight, 20), 100);

      // Apply the new height smoothly
      setTextareaHeight(newHeight);
      textarea.style.height = newHeight + 'px';
    }
  };

  // Initialize with proper height on mount
  useEffect(() => {
    const textarea = textareaRef.current;
    if (textarea) {
      // Force initial height without content check
      textarea.style.height = '20px';
      setTextareaHeight(20);

      // If there's initial content, adjust immediately
      if (value) {
        setTimeout(adjustHeight, 0);
      }
    }
  }, []); // Empty dependency array - only runs on mount

  // Adjust height when value changes
  useEffect(() => {
    if (value === '') {
      // Reset to minimum when empty
      const textarea = textareaRef.current;
      if (textarea) {
        textarea.style.height = '20px';
        setTextareaHeight(20);
      }
    } else {
      // Adjust for content
      const timeoutId = setTimeout(adjustHeight, 0);
      return () => clearTimeout(timeoutId);
    }
  }, [value]);

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      if (value.trim() && !disabled) {
        onSubmit(selectedAction);
        setSelectedAction(null);
      }
    }
  };

  const handleActionSelect = (action: ActionType) => {
    setSelectedAction(action);
    setIsPopoverOpen(false);
  };

  const handleRemoveAction = () => {
    setSelectedAction(null);
  };

  const handleVoiceRecording = () => {
    if (isRecording) {
      // Stop recording
      if (recordingIntervalRef.current) {
        clearInterval(recordingIntervalRef.current);
        recordingIntervalRef.current = null;
      }

      // Simulate audio transcription — demo strings keyed by i18n
      const transcricoes = [
        t('assistant.voiceTranscriptions.salesData'),
        t('assistant.voiceTranscriptions.performanceReport'),
        t('assistant.voiceTranscriptions.marketTrends'),
        t('assistant.voiceTranscriptions.customerSatisfaction'),
        t('assistant.voiceTranscriptions.teamProductivity'),
        t('assistant.voiceTranscriptions.keyMetrics'),
        t('assistant.voiceTranscriptions.digitalMarketing'),
        t('assistant.voiceTranscriptions.socialEngagement'),
      ];

      const transcricaoAleatoria = transcricoes[Math.floor(Math.random() * transcricoes.length)];

      // Call the callback with the transcription
      if (onVoiceRecording) {
        onVoiceRecording(transcricaoAleatoria);
      }

      setIsRecording(false);
      setRecordingTime(0);
    } else {
      // Start recording
      setIsRecording(true);
      setRecordingTime(0);

      toast.info(t('assistant.recordingStarted'), {
        description: t('assistant.recordingDescriptionFull'),
        duration: 3000,
      });

      recordingIntervalRef.current = setInterval(() => {
        setRecordingTime(prev => prev + 1);
      }, 1000);
    }
  };

  // Automatically stop recording after 60 seconds
  useEffect(() => {
    if (recordingTime >= 60 && isRecording) {
      handleVoiceRecording();
    }
  }, [recordingTime, isRecording]);

  // Clear interval on unmount
  useEffect(() => {
    return () => {
      if (recordingIntervalRef.current) {
        clearInterval(recordingIntervalRef.current);
      }
    };
  }, []);

  const getActionInfo = (action: ActionType) => {
    switch (action) {
      case 'document':
        return {
          label: t('assistant.actions.createDocument'),
          icon: FileText,
          color: 'bg-[var(--chart-4)]',
        };
      case 'podcast':
        return {
          label: t('assistant.actions.generatePodcast'),
          icon: Radio,
          color: 'bg-[var(--chart-1)]',
        };
      case 'search':
        return { label: t('assistant.actions.search'), icon: Search, color: 'bg-[var(--chart-2)]' };
      default:
        return null;
    }
  };

  const handleFocus = () => setIsFocused(true);
  const handleBlur = () => setIsFocused(false);

  const hasContent = value.trim().length > 0;

  return (
    <div className={`p-4 ${isFullPage ? 'mx-auto w-full max-w-6xl' : ''}`}>
      {/* Recording Indicator */}
      <AnimatePresence>
        {isRecording && (
          <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 10 }}
            className="mb-3 p-4 bg-destructive/10 border border-destructive/30 rounded-[var(--radius-card)]"
          >
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                {/* Pulsing Dot */}
                <motion.div
                  animate={{
                    scale: [1, 1.2, 1],
                    opacity: [1, 0.7, 1],
                  }}
                  transition={{
                    duration: 1.5,
                    repeat: Infinity,
                    ease: 'easeInOut',
                  }}
                  className="w-3 h-3 bg-destructive rounded-full"
                />

                {/* Audio Waves Animation */}
                <div className="flex items-center gap-1">
                  {[0, 1, 2, 3, 4].map(i => (
                    <motion.div
                      key={i}
                      animate={{
                        height: ['8px', '20px', '8px'],
                      }}
                      transition={{
                        duration: 0.8,
                        repeat: Infinity,
                        ease: 'easeInOut',
                        delay: i * 0.1,
                      }}
                      className="w-1 bg-destructive rounded-full h-2"
                    />
                  ))}
                </div>

                <span className="text-sm font-medium text-destructive">
                  {t('assistant.recordingAudio')}
                </span>
              </div>

              <div className="flex items-center gap-3">
                <div className="text-sm text-destructive font-mono tabular-nums">
                  {Math.floor(recordingTime / 60)}:
                  {(recordingTime % 60).toString().padStart(2, '0')}
                </div>
                <Button
                  onClick={handleVoiceRecording}
                  size="sm"
                  variant="outline"
                  className="h-7 px-3 text-xs border-destructive/30 text-destructive hover:bg-destructive/10 rounded-[var(--radius-button)]"
                >
                  {t('assistant.stopRecording')}
                </Button>
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Modern Input Container */}
      <motion.div
        className={`relative bg-card rounded-[var(--radius)] border shadow-sm transition-all duration-300 ${
          isFocused || hasContent ? 'border-primary shadow-lg shadow-primary/10' : 'border-border'
        }`}
        initial={false}
        animate={{
          scale: isFocused ? 1.01 : 1,
        }}
        transition={{ duration: 0.2, ease: 'easeOut' }}
      >
        <div className="px-3 py-2 pt-[14px] pr-[10px] pb-[8px] pl-[10px] rounded-[var(--radius)]">
          {/* Action Chip */}
          <AnimatePresence>
            {selectedAction && (
              <motion.div
                initial={{ opacity: 0, y: -10, height: 0 }}
                animate={{ opacity: 1, y: 0, height: 'auto' }}
                exit={{ opacity: 0, y: -10, height: 0 }}
                transition={{ duration: 0.2 }}
                className="mb-2"
              >
                {(() => {
                  const actionInfo = getActionInfo(selectedAction);
                  if (!actionInfo) return null;
                  const Icon = actionInfo.icon;
                  return (
                    <div
                      className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-full ${actionInfo.color} text-white text-xs font-medium shadow-sm`}
                    >
                      <Icon className="w-3.5 h-3.5" />
                      <span>{actionInfo.label}</span>
                      <button
                        onClick={handleRemoveAction}
                        className="ml-1 hover:bg-white/20 rounded-full p-0.5 transition-colors"
                        aria-label={t('assistant.removeAction')}
                      >
                        <X className="w-3 h-3" />
                      </button>
                    </div>
                  );
                })()}
              </motion.div>
            )}
          </AnimatePresence>

          {/* Text Input - Full Width */}
          <div className="mb-2">
            <textarea
              ref={textareaRef}
              value={value}
              onChange={e => onChange(e.target.value)}
              onKeyDown={handleKeyDown}
              onFocus={handleFocus}
              onBlur={handleBlur}
              placeholder={resolvedPlaceholder}
              aria-label={resolvedPlaceholder}
              disabled={disabled}
              className="w-full bg-transparent border-0 outline-none resize-none text-foreground placeholder-muted-foreground text-sm leading-5 min-h-[20px] max-h-[100px] overflow-y-auto scrollbar-thin scrollbar-thumb-border scrollbar-track-transparent"
              style={{
                height: `${textareaHeight}px`,
                minHeight: '20px',
                maxHeight: '100px',
              }}
              rows={1}
            />
          </div>

          {/* Actions Row - Bottom */}
          <div className="flex items-center justify-between">
            {/* Left Actions */}
            <div className="flex items-center gap-1">
              {(enableDocumentCreation || enablePodcastGeneration || enableSearch) && (
                <Popover open={isPopoverOpen} onOpenChange={setIsPopoverOpen}>
                  <PopoverTrigger asChild>
                    <Button
                      variant="ghost"
                      size="sm"
                      className="h-8 w-8 p-0 rounded-full text-muted-foreground hover:bg-accent hover:text-foreground transition-all duration-200"
                      aria-label={t('assistant.viewActions')}
                    >
                      <motion.div
                        whileHover={{ scale: 1.05 }}
                        whileTap={{ scale: 0.95 }}
                        className="flex items-center justify-center w-full h-full"
                      >
                        <Plus className="w-4 h-4" />
                      </motion.div>
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-56 p-2" align="start" side="top">
                    <div className="space-y-1">
                      {enableDocumentCreation && (
                        <button
                          onClick={() => handleActionSelect('document')}
                          className="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg hover:bg-accent transition-colors text-left group"
                        >
                          <div className="w-8 h-8 rounded-full bg-[var(--chart-4)]/20 flex items-center justify-center group-hover:bg-[var(--chart-4)] transition-colors">
                            <FileText className="w-4 h-4 text-[var(--chart-4)] group-hover:text-white" />
                          </div>
                          <div className="flex-1">
                            <div>{t('assistant.actions.createDocument')}</div>
                            <div className="text-xs text-muted-foreground">
                              {t('assistant.actions.createDocumentDesc')}
                            </div>
                          </div>
                        </button>
                      )}

                      {enablePodcastGeneration && (
                        <button
                          onClick={() => handleActionSelect('podcast')}
                          className="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg hover:bg-accent transition-colors text-left group"
                        >
                          <div className="w-8 h-8 rounded-full bg-[var(--chart-1)]/20 flex items-center justify-center group-hover:bg-[var(--chart-1)] transition-colors">
                            <Radio className="w-4 h-4 text-[var(--chart-1)] group-hover:text-white" />
                          </div>
                          <div className="flex-1">
                            <div>{t('assistant.actions.generatePodcast')}</div>
                            <div className="text-xs text-muted-foreground">
                              {t('assistant.actions.generatePodcastDesc')}
                            </div>
                          </div>
                        </button>
                      )}

                      {enableSearch && (
                        <button
                          onClick={() => handleActionSelect('search')}
                          className="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg hover:bg-accent transition-colors text-left group"
                        >
                          <div className="w-8 h-8 rounded-full bg-[var(--chart-2)]/20 flex items-center justify-center group-hover:bg-[var(--chart-2)] transition-colors">
                            <Search className="w-4 h-4 text-[var(--chart-2)] group-hover:text-white" />
                          </div>
                          <div className="flex-1">
                            <div>{t('assistant.actions.search')}</div>
                            <div className="text-xs text-muted-foreground">
                              {t('assistant.actions.searchDesc')}
                            </div>
                          </div>
                        </button>
                      )}
                    </div>
                  </PopoverContent>
                </Popover>
              )}

              {enableFileAttachment && (
                <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={onFileUpload}
                    className="h-8 w-8 p-0 rounded-full text-muted-foreground hover:bg-accent hover:text-foreground transition-all duration-200"
                    aria-label={t('assistant.attachFile')}
                  >
                    <Paperclip className="w-4 h-4" />
                  </Button>
                </motion.div>
              )}
            </div>

            {/* Right Actions */}
            <div className="flex items-center gap-1">
              {/* Voice Recording Button */}
              {enableAudioInput && (
                <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={handleVoiceRecording}
                    className={`h-8 w-8 p-0 rounded-full transition-all duration-200 ${
                      isRecording
                        ? 'bg-destructive hover:bg-destructive/90 text-white animate-pulse'
                        : 'text-muted-foreground hover:bg-accent hover:text-foreground'
                    }`}
                    aria-label={
                      isRecording ? t('assistant.stopRecording') : t('assistant.suggestWithVoice')
                    }
                  >
                    <Mic className="w-4 h-4" />
                  </Button>
                </motion.div>
              )}

              <AnimatePresence mode="wait">
                <motion.div
                  key={hasContent ? 'active' : 'inactive'}
                  initial={{ scale: 0.8, opacity: 0 }}
                  animate={{ scale: 1, opacity: 1 }}
                  exit={{ scale: 0.8, opacity: 0 }}
                  transition={{ duration: 0.2, ease: 'easeInOut' }}
                  whileHover={hasContent ? { scale: 1.05 } : {}}
                  whileTap={hasContent ? { scale: 0.95 } : {}}
                >
                  <Button
                    onClick={() => {
                      onSubmit(selectedAction);
                      setSelectedAction(null);
                    }}
                    size="sm"
                    disabled={!hasContent || disabled}
                    className={`h-8 w-8 p-0 rounded-full transition-all duration-300 ${
                      hasContent && !disabled
                        ? 'bg-primary hover:bg-primary/90 text-primary-foreground shadow-lg shadow-primary/30 hover:shadow-primary/40'
                        : 'bg-muted text-muted-foreground cursor-not-allowed'
                    }`}
                    aria-label={t('assistant.sendMessage')}
                  >
                    <motion.div
                      animate={{
                        rotate: hasContent ? 0 : -45,
                      }}
                      transition={{ duration: 0.2 }}
                    >
                      <Send className="w-4 h-4" />
                    </motion.div>
                  </Button>
                </motion.div>
              </AnimatePresence>
            </div>
          </div>
        </div>

        {/* Subtle glow effect when focused */}
        <AnimatePresence>
          {isFocused && (
            <motion.div
              className="absolute inset-0 rounded-[var(--radius)] bg-gradient-to-r from-primary/5 via-transparent to-primary/5 pointer-events-none"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.3 }}
            />
          )}
        </AnimatePresence>
      </motion.div>

      {/* Footer Info */}
      <motion.div
        className="mt-2 text-center"
        initial={{ opacity: 0, y: 5 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.1 }}
      >
        <p className="text-xs text-muted-foreground">{t('assistant.disclaimer')}</p>
      </motion.div>
    </div>
  );
}
