// React Imports
import { useRef, useState, type ChangeEvent, type FormEvent, type KeyboardEvent } from 'react'

// MUI Imports
import TextField from '@mui/material/TextField'
import IconButton from '@mui/material/IconButton'
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'

// Component Imports
import ImagePreview from './ImagePreview'
import FilePreview from './FilePreview'

// Type Imports
import type { ChatFile } from '@/types/apps/aiChatTypes'

type Props = {
  onSend: (message: string, images: string[], files: ChatFile[]) => void
  placeholder?: string
  disabled?: boolean
}

const ChatInput = ({ onSend, placeholder = 'پیام خود را بنویسید...', disabled = false }: Props) => {
  // States
  const [message, setMessage] = useState('')
  const [images, setImages] = useState<string[]>([])
  const [files, setFiles] = useState<ChatFile[]>([])

  // Refs
  const fileInputRef = useRef<HTMLInputElement>(null)
  const docInputRef = useRef<HTMLInputElement>(null)

  const handleImageSelect = (event: ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files
    if (!files) return

    const imageFiles = Array.from(files).filter(file => file.type.startsWith('image/'))
    const promises: Promise<string>[] = []

    imageFiles.forEach(file => {
      const promise = new Promise<string>((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = e => {
          const dataUrl = e.target?.result as string
          resolve(dataUrl)
        }
        reader.onerror = reject
        reader.readAsDataURL(file)
      })
      promises.push(promise)
    })

    Promise.all(promises)
      .then(dataUrls => {
        setImages(prev => [...prev, ...dataUrls])
      })
      .catch(error => {
        console.error('Error reading images:', error)
      })

    // Reset input
    if (fileInputRef.current) {
      fileInputRef.current.value = ''
    }
  }

  const handleFileSelect = (event: ChangeEvent<HTMLInputElement>) => {
    const selectedFiles = event.target.files
    if (!selectedFiles) return

    // Filter out images (they should use image input) and accept document files
    const docFiles = Array.from(selectedFiles).filter(file => {
      const isImage = file.type.startsWith('image/')
      const isDocument = file.type.includes('document') || 
                         file.type.includes('pdf') || 
                         file.name.match(/\.(doc|docx|pdf)$/i)
      return !isImage && isDocument
    })
    const promises: Promise<ChatFile>[] = []

    docFiles.forEach(file => {
      const promise = new Promise<ChatFile>((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = e => {
          const dataUrl = e.target?.result as string
          resolve({
            name: file.name,
            data: dataUrl,
            type: file.type || 'application/octet-stream',
            size: file.size
          })
        }
        reader.onerror = reject
        reader.readAsDataURL(file)
      })
      promises.push(promise)
    })

    Promise.all(promises)
      .then(chatFiles => {
        setFiles(prev => [...prev, ...chatFiles])
      })
      .catch(error => {
        console.error('Error reading files:', error)
      })

    // Reset input
    if (docInputRef.current) {
      docInputRef.current.value = ''
    }
  }

  const handleRemoveImage = (index: number) => {
    setImages(prev => prev.filter((_, i) => i !== index))
  }

  const handleRemoveFile = (index: number) => {
    setFiles(prev => prev.filter((_, i) => i !== index))
  }

  const handleSend = (event?: FormEvent | KeyboardEvent) => {
    if (event) {
      event.preventDefault()
    }

    const trimmedMessage = message.trim()
    if (trimmedMessage || images.length > 0 || files.length > 0) {
      onSend(trimmedMessage, images, files)
      setMessage('')
      setImages([])
      setFiles([])
    }
  }

  const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    if (event.key === 'Enter' && !event.shiftKey) {
      event.preventDefault()
      handleSend(event)
    }
  }

  const handleAiAction = (action: string) => {
    // Handle different AI actions
    const actionPrompts: { [key: string]: string } = {
      generateImage: 'لطفا یک تصویر بر اساس توضیحات من تولید کن',
      createCurriculum: 'لطفا یک برنامه درسی سفارشی برای من بساز',
      summarize: 'لطفا محتوای ارسالی را خلاصه کن',
      translate: 'لطفا این متن را ترجمه کن'
    }

    const prompt = actionPrompts[action] || ''
    if (prompt) {
      setMessage(prompt)
    }
  }

  const aiActions = [
    { id: 'generateImage', label: 'تولید عکس', icon: 'tabler-photo' },
    { id: 'createCurriculum', label: 'ساخت برنامه درسی', icon: 'tabler-school' },
    { id: 'summarize', label: 'خلاصه‌سازی', icon: 'tabler-file-text' },
    { id: 'translate', label: 'ترجمه', icon: 'tabler-language' }
  ]

  return (
    <Box className='border-t border-divider bg-backgroundPaper'>
      {/* AI Action Buttons */}
      <Box className='flex items-center gap-2 p-4 border-b border-divider flex-wrap'>
        {aiActions.map(action => (
          <Button
            key={action.id}
            variant='outlined'
            size='small'
            startIcon={<i className={action.icon} />}
            onClick={() => handleAiAction(action.id)}
            sx={{
              borderRadius: 2,
              textTransform: 'none',
              borderColor: 'var(--mui-palette-divider)',
              color: 'var(--mui-palette-text-primary)',
              '&:hover': {
                borderColor: 'var(--mui-palette-primary-main)',
                backgroundColor: 'var(--mui-palette-primary-main)',
                color: 'var(--mui-palette-primary-contrastText)'
              }
            }}
          >
            {action.label}
          </Button>
        ))}
      </Box>
      {images.length > 0 && (
        <Box className='p-4 border-b border-divider'>
          <ImagePreview images={images} onRemove={handleRemoveImage} />
        </Box>
      )}
      {files.length > 0 && (
        <Box className='p-4 border-b border-divider'>
          <FilePreview files={files} onRemove={handleRemoveFile} />
        </Box>
      )}
      <Box className='flex items-end gap-2 p-4'>
        <IconButton
          component='label'
          htmlFor='chat-image-input'
          color='secondary'
          size='medium'
          className='flex-shrink-0'
          title='افزودن تصویر'
        >
          <i className='tabler-photo text-xl' />
          <input
            ref={fileInputRef}
            hidden
            type='file'
            id='chat-image-input'
            accept='image/*'
            multiple
            onChange={handleImageSelect}
          />
        </IconButton>
        <IconButton
          component='label'
          htmlFor='chat-file-input'
          color='secondary'
          size='medium'
          className='flex-shrink-0'
          title='افزودن فایل'
        >
          <i className='tabler-file-upload text-xl' />
          <input
            ref={docInputRef}
            hidden
            type='file'
            id='chat-file-input'
            accept='.doc,.docx,.pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/pdf'
            multiple
            onChange={handleFileSelect}
          />
        </IconButton>
        <TextField
          fullWidth
          multiline
          maxRows={6}
          placeholder={placeholder}
          value={message}
          onChange={e => setMessage(e.target.value)}
          onKeyDown={handleKeyDown}
          variant='outlined'
          size='small'
          disabled={disabled}
          sx={{
            '& .MuiOutlinedInput-root': {
              backgroundColor: 'var(--mui-palette-background-default)',
              '& fieldset': {
                borderColor: 'var(--mui-palette-divider)'
              }
            }
          }}
        />
        <IconButton
          color='primary'
          onClick={handleSend}
          disabled={disabled || (!message.trim() && images.length === 0 && files.length === 0)}
          size='medium'
          className='flex-shrink-0'
          sx={{
            backgroundColor: 'var(--mui-palette-primary-main)',
            color: 'var(--mui-palette-primary-contrastText)',
            '&:hover': {
              backgroundColor: 'var(--mui-palette-primary-dark)'
            },
            '&.Mui-disabled': {
              backgroundColor: 'var(--mui-palette-action-disabledBackground)',
              color: 'var(--mui-palette-action-disabled)'
            }
          }}
        >
          <i className='tabler-send text-xl' />
        </IconButton>
      </Box>
    </Box>
  )
}

export default ChatInput

