import {useState} from 'react'
import {useForm} from 'react-hook-form'
import {useQuery, useQueryClient} from '@tanstack/react-query'
import {UserClient} from '../../generated/ManagingApi'
import Modal from '../../components/mollecules/Modal/Modal'
import useApiUrlStore from '../../app/store/apiStore'
import {Toast} from '../../components/mollecules'
import useCookie from '../../hooks/useCookie'

type UpdateAgentNameForm = {
  agentName: string
}

type UpdateAvatarForm = {
  avatarUrl: string
}

type UpdateTelegramChannelForm = {
  telegramChannel: string
}

function UserInfoSettings() {
  const [showUpdateModal, setShowUpdateModal] = useState(false)
  const [showAvatarModal, setShowAvatarModal] = useState(false)
  const [showTelegramModal, setShowTelegramModal] = useState(false)
  const queryClient = useQueryClient()
  const { apiUrl } = useApiUrlStore()
  const api = new UserClient({}, apiUrl)
  const { getCookie } = useCookie()
  
  // Get JWT token from cookies
  const jwtToken = getCookie('token')

  const { data: user } = useQuery({
    queryKey: ['user'],
    queryFn: () => api.user_GetCurrentUser(),
    enabled: !!jwtToken, // Only fetch when JWT token exists
  })

  const {
    register: registerAgentName,
    handleSubmit: handleSubmitAgentName,
    formState: { errors: agentNameErrors },
  } = useForm<UpdateAgentNameForm>()

  const {
    register: registerAvatar,
    handleSubmit: handleSubmitAvatar,
    formState: { errors: avatarErrors },
  } = useForm<UpdateAvatarForm>()

  const {
    register: registerTelegram,
    handleSubmit: handleSubmitTelegram,
    formState: { errors: telegramErrors },
  } = useForm<UpdateTelegramChannelForm>()

  const onSubmitAgentName = async (data: UpdateAgentNameForm) => {
    const toast = new Toast('Updating agent name')
    try {
      await api.user_UpdateAgentName(data.agentName)
      queryClient.invalidateQueries({ queryKey: ['user'] })
      setShowUpdateModal(false)
      toast.update('success', 'Agent name updated successfully')
    } catch (error) {
      console.error('Error updating agent name:', error)
      toast.update('error', 'Failed to update agent name')
    }
  }

  const onSubmitAvatar = async (data: UpdateAvatarForm) => {
    const toast = new Toast('Updating avatar')
    try {
      await api.user_UpdateAvatarUrl(data.avatarUrl)
      queryClient.invalidateQueries({ queryKey: ['user'] })
      setShowAvatarModal(false)
      toast.update('success', 'Avatar updated successfully')
    } catch (error) {
      console.error('Error updating avatar:', error)
      toast.update('error', 'Failed to update avatar')
    }
  }

  const onSubmitTelegram = async (data: UpdateTelegramChannelForm) => {
    const toast = new Toast('Updating telegram channel')
    try {
      await api.user_UpdateTelegramChannel(data.telegramChannel)
      queryClient.invalidateQueries({ queryKey: ['user'] })
      setShowTelegramModal(false)
      toast.update('success', 'Telegram channel updated successfully')
    } catch (error) {
      console.error('Error updating telegram channel:', error)
      toast.update('error', 'Failed to update telegram channel')
    }
  }

  const testTelegramChannel = async () => {
    if (!user?.telegramChannel) {
      const toast = new Toast('No telegram channel configured')
      toast.update('error', 'Please configure a telegram channel first')
      return
    }

    const toast = new Toast('Testing telegram channel...')
    try {
      const response = await api.user_TestTelegramChannel()
      toast.update('success', 'Test message sent! Check your Telegram.')
    } catch (error: any) {
      console.error('Error testing telegram channel:', error)
      const errorMessage = error.response?.data || error.message || 'Failed to send test message'
      toast.update('error', errorMessage)
    }
  }

  return (
    <div className="container mx-auto p-4">
      <div className="bg-base-200 rounded-lg p-6 shadow-lg">
        <h2 className="text-2xl font-bold mb-4">User Information</h2>
        
        <div className="space-y-4">
          <div>
            <label className="font-semibold">Name:</label>
            <p>{user?.name}</p>
          </div>
          
          <div>
            <label className="font-semibold">Agent Name:</label>
            <p>{user?.agentName || 'Not set'}</p>
            <button
              className="btn btn-primary mt-2"
              onClick={() => setShowUpdateModal(true)}
            >
              Update Agent Name
            </button>
          </div>

          <div>
            <label className="font-semibold">Avatar:</label>
            <div className="mt-2 flex items-center space-x-4">
              {user?.avatarUrl ? (
                <img 
                  src={user.avatarUrl} 
                  alt="User avatar" 
                  className="w-16 h-16 rounded-full object-cover"
                />
              ) : (
                <div className="w-16 h-16 rounded-full bg-base-300 flex items-center justify-center">
                  <span className="text-2xl">{user?.name?.[0]?.toUpperCase() || '?'}</span>
                </div>
              )}
              <button
                className="btn btn-primary"
                onClick={() => setShowAvatarModal(true)}
              >
                Update Avatar
              </button>
            </div>
          </div>

          <div>
            <label className="font-semibold">Telegram Channel:</label>
            <p>{user?.telegramChannel || 'Not set'}</p>
            <div className="flex gap-2 mt-2">
              <button
                className="btn btn-primary"
                onClick={() => setShowTelegramModal(true)}
              >
                Update Telegram Channel
              </button>
              {user?.telegramChannel && (
                <button
                  className="btn btn-secondary"
                  onClick={testTelegramChannel}
                >
                  Test Channel
                </button>
              )}
            </div>
          </div>
        </div>
      </div>

      <Modal
        showModal={showUpdateModal}
        onClose={() => setShowUpdateModal(false)}
        onSubmit={handleSubmitAgentName(onSubmitAgentName)}
        titleHeader="Update Agent Name"
      >
        <div className="form-control w-full">
          <label className="label">
            <span className="label-text">Agent Name</span>
          </label>
          <input
            type="text"
            className="input input-bordered w-full"
            {...registerAgentName('agentName', { required: 'Agent name is required' })}
            defaultValue={user?.agentName || ''}
          />
          {agentNameErrors.agentName && (
            <label className="label">
              <span className="label-text-alt text-error">
                {agentNameErrors.agentName.message}
              </span>
            </label>
          )}
        </div>
        <div className="modal-action">
          <button type="submit" className="btn">
            Update
          </button>
        </div>
      </Modal>

      <Modal
        showModal={showAvatarModal}
        onClose={() => setShowAvatarModal(false)}
        onSubmit={handleSubmitAvatar(onSubmitAvatar)}
        titleHeader="Update Avatar"
      >
        <div className="form-control w-full">
          <label className="label">
            <span className="label-text">Avatar URL (JPEG or PNG)</span>
          </label>
          <input
            type="url"
            className="input input-bordered w-full"
            {...registerAvatar('avatarUrl', { 
              required: 'Avatar URL is required',
              pattern: {
                value: /^https?:\/\/.+\.(jpeg|jpg|png)$/i,
                message: 'URL must be a valid image URL ending in .jpeg, .jpg, or .png'
              }
            })}
            defaultValue={user?.avatarUrl || ''}
          />
          {avatarErrors.avatarUrl && (
            <label className="label">
              <span className="label-text-alt text-error">
                {avatarErrors.avatarUrl.message}
              </span>
            </label>
          )}
        </div>
        <div className="modal-action">
          <button type="submit" className="btn">
            Update
          </button>
        </div>
      </Modal>

      <Modal
        showModal={showTelegramModal}
        onClose={() => setShowTelegramModal(false)}
        onSubmit={handleSubmitTelegram(onSubmitTelegram)}
        titleHeader="Update Telegram Channel"
      >
        <div className="form-control w-full">
          <label className="label">
            <span className="label-text">Telegram Channel</span>
          </label>
          <input
            type="text"
            className="input input-bordered w-full"
            {...registerTelegram('telegramChannel', { 
              required: 'Telegram channel is required',
              pattern: {
                value: /^[0-9]{5,15}$/,
                message: 'Enter numeric channel ID (5-15 digits)'
              }
            })}
            defaultValue={user?.telegramChannel || ''}
            placeholder="2828543022"
          />
          {telegramErrors.telegramChannel && (
            <label className="label">
              <span className="label-text-alt text-error">
                {telegramErrors.telegramChannel.message}
              </span>
            </label>
          )}
        </div>
        <div className="modal-action">
          <button type="submit" className="btn">
            Update
          </button>
        </div>
      </Modal>
    </div>
  )
}

export default UserInfoSettings 