import { useSearchParams } from 'react-router-dom'
import './EmailNotificationTemplate.css'
import { Button, Card, ConfigProvider, Flex, theme, Typography } from 'antd'
import FarmControlLogo from '../Logos/FarmControlLogo'
import Notification from '../Dashboard/common/Notification'
import { useThemeContext } from '../Dashboard/context/ThemeContext'
import { getModelByName } from '../../database/ObjectModels'

const { Text } = Typography

/**
 * Email notification template - renders notification data for server-side HTML capture.
 * Used by the API's sendEmailNotification with Puppeteer.
 * Params: title, message, type, metadata (JSON string)
 */
const EmailNotificationTemplate = () => {
  const { themeConfig } = useThemeContext()
  const [searchParams] = useSearchParams()
  const title = searchParams.get('title') || 'Notification'
  const message = searchParams.get('message') || ''
  const type = searchParams.get('type') || 'info'
  const read = searchParams.get('read') || false
  const email = searchParams.get('email') || ''
  const createdAt = searchParams.get('createdAt') || new Date()
  const updatedAt = searchParams.get('updatedAt') || new Date()
  const origin = window.location.origin

  let metadata = {}
  try {
    const metaStr = searchParams.get('metadata')
    if (metaStr) metadata = JSON.parse(metaStr)
  } catch {
    // ignore parse errors
  }

  const lightThemeConfig = {
    ...themeConfig,
    algorithm: theme.defaultAlgorithm,
    components: {
      ...themeConfig.components,
      Layout: { headerBg: '#ffffff' }
    }
  }

  const getNotifictionActions = () => {
    switch (type) {
      case 'editObject': {
        const model = getModelByName(metadata?.objectType)
        const infoAction = model.actions?.find(
          (action) => action.name === 'info'
        )
        const url = infoAction ? infoAction.url(metadata?.object?._id) : '#'
        return (
          <Button href={`${origin}${url}`} type='primary'>
            View in Dashboard
          </Button>
        )
      }
      case 'newNote': {
        const model = getModelByName(metadata?.note?.parentType)
        const infoAction =
          model.actions?.find((action) => action.name === 'info') ?? null
        const url = infoAction
          ? infoAction.url(metadata?.note?.parent?._id)
          : null
        return url ? (
          <Button href={`${origin}${url}`} type='primary'>
            View in Dashboard
          </Button>
        ) : null
      }
    }
    return null
  }

  return (
    <ConfigProvider theme={lightThemeConfig}>
      <div id='email-notification-root' data-rendered='true'>
        <FarmControlLogo
          style={{
            fontSize: '500px',
            height: '40px',
            display: 'flex',
            justifyContent: 'center',
            margin: '0 auto 60px 0'
          }}
        />
        <Card className='email-notification-card'>
          <Notification
            showCard={false}
            showDelete={false}
            inlineIcon={false}
            largeSpacing={true}
            showSince={false}
            notification={{
              title: title,
              message: message,
              type: type,
              metadata: metadata,
              read: read,
              createdAt: createdAt,
              updatedAt: updatedAt
            }}
          />
        </Card>

        <Flex justify='center' className='email-notification-card-actions'>
          {getNotifictionActions()}
        </Flex>
        {email && (
          <Flex
            align='center'
            className='email-notification-card-footer'
            vertical
          >
            <Text
              type='secondary'
              style={{
                fontSize: '12px',
                maxWidth: '300px',
                textAlign: 'center'
              }}
            >
              This email was sent to {email}. Please do not reply to this email.
            </Text>
          </Flex>
        )}
      </div>
    </ConfigProvider>
  )
}

export default EmailNotificationTemplate
