'use client'

// React Imports
import { useState, useEffect } from 'react'

// MUI Imports
import Box from '@mui/material/Box'
import useMediaQuery from '@mui/material/useMediaQuery'
import type { Theme } from '@mui/material/styles'
import Select from '@mui/material/Select'
import MenuItem from '@mui/material/MenuItem'
import FormControl from '@mui/material/FormControl'
import CircularProgress from '@mui/material/CircularProgress'
import Alert from '@mui/material/Alert'

// Third-party Imports
import classnames from 'classnames'

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

// Component Imports
import ChatMessages from './ChatMessages'
import ChatInput from './ChatInput'

// Hook Imports
import { useSettings } from '@core/hooks/useSettings'

// Util Imports
import { commonLayoutClasses } from '@layouts/utils/layoutClasses'

// API Imports
import { aiChatService } from '@/libs/api'

const AiChatView = () => {
  // States
  const [messages, setMessages] = useState<ChatMessage[]>([])
  const [selectedModel, setSelectedModel] = useState<string>('gpt-4')
  const [conversationId, setConversationId] = useState<string | undefined>()
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // Available models
  const models = [
    { value: 'gpt-4', label: 'GPT-4' },
    { value: 'gpt-3.5', label: 'GPT-3.5' },
    { value: 'claude', label: 'Claude' },
    { value: 'gemini', label: 'Gemini' }
  ]

  // Hooks
  const { settings } = useSettings()
  const isBelowLgScreen = useMediaQuery((theme: Theme) => theme.breakpoints.down('lg'))

  const handleSend = async (content: string, images: string[], files: ChatFile[]) => {
    if (!content.trim() && images.length === 0 && files.length === 0) return

    setLoading(true)
    setError(null)

    try {
      // Add user message to UI immediately
      const userMessage: ChatMessage = {
        id: Date.now().toString(),
        role: 'user',
        content,
        images: images.length > 0 ? images : undefined,
        files: files.length > 0 ? files : undefined,
        timestamp: new Date()
      }
      setMessages(prev => [...prev, userMessage])

      // Send to API
      const response = await aiChatService.sendMessage({
        content,
        images: images.length > 0 ? images : undefined,
        files: files.length > 0 ? files : undefined,
        model: selectedModel as 'gpt-4' | 'gpt-3.5' | 'claude' | 'gemini',
        conversationId
      })

      // Update conversation ID if provided
      if (response.message.id && !conversationId) {
        setConversationId(response.message.id.split('-')[0]) // Extract conversation ID from message ID if needed
      }

      // Update user message with API response (in case of sensitive message)
      if (response.message.isSensitive) {
        setMessages(prev =>
          prev.map(msg =>
            msg.id === userMessage.id
              ? {
                  ...msg,
                  isSensitive: response.message.isSensitive,
                  sensitiveReason: response.message.sensitiveReason
                }
              : msg
          )
        )
      }

      // Add assistant response
      const assistantMessage: ChatMessage = {
        id: response.assistantResponse.id,
        role: 'assistant',
        content: response.assistantResponse.content,
        timestamp: new Date(response.assistantResponse.timestamp)
      }
      setMessages(prev => [...prev, assistantMessage])
    } catch (err: any) {
      setError(err.message || 'خطا در ارسال پیام')
      console.error('Error sending message:', err)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div
      className={classnames(commonLayoutClasses.contentHeightFixed, 'flex is-full overflow-hidden rounded', {
        border: settings.skin === 'bordered',
        'shadow-md': settings.skin !== 'bordered'
      })}
    >
      <Box
        className='flex flex-col bs-full is-full'
        sx={{
          width: '100%'
        }}
      >
        {/* Header */}
        <Box
          className='flex items-center justify-between border-b border-divider bg-backgroundPaper p-4'
          sx={{
            minHeight: 64
          }}
        >
          <Box className='flex items-center gap-3'>
            <Box
              sx={{
                width: 32,
                height: 32,
                borderRadius: '50%',
                backgroundColor: 'var(--mui-palette-primary-main)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: 'var(--mui-palette-primary-contrastText)'
              }}
            >
              <i className='tabler-robot text-lg' />
            </Box>
            <Box>
              <Box component='h2' className='text-lg font-semibold m-0' sx={{ color: 'var(--mui-palette-text-primary)' }}>
                دستیار هوشمند
              </Box>
              <Box component='p' className='text-xs m-0' sx={{ color: 'var(--mui-palette-text-secondary)' }}>
                چگونه می‌توانم به شما کمک کنم؟
              </Box>
            </Box>
          </Box>
          <FormControl size='small' sx={{ minWidth: 150 }}>
            <Select
              value={selectedModel}
              onChange={e => setSelectedModel(e.target.value)}
              sx={{
                backgroundColor: 'var(--mui-palette-background-default)',
                '& .MuiOutlinedInput-notchedOutline': {
                  borderColor: 'var(--mui-palette-divider)'
                },
                '&:hover .MuiOutlinedInput-notchedOutline': {
                  borderColor: 'var(--mui-palette-primary-main)'
                },
                '&.Mui-focused .MuiOutlinedInput-notchedOutline': {
                  borderColor: 'var(--mui-palette-primary-main)'
                }
              }}
            >
              {models.map(model => (
                <MenuItem key={model.value} value={model.value}>
                  {model.label}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        </Box>

        {/* Messages Area */}
        <Box className='flex-1 overflow-hidden bg-backgroundDefault'>
          {error && (
            <Alert severity='error' onClose={() => setError(null)} sx={{ m: 2 }}>
              {error}
            </Alert>
          )}
          <ChatMessages messages={messages} isBelowLgScreen={isBelowLgScreen} />
          {loading && (
            <Box className='flex items-center justify-center p-4'>
              <CircularProgress size={24} />
            </Box>
          )}
        </Box>

        {/* Input Area */}
        <Box className='flex-shrink-0 bg-backgroundPaper'>
          <ChatInput onSend={handleSend} disabled={loading} />
        </Box>
      </Box>
    </div>
  )
}

export default AiChatView

