import { BotContext, InputSubmitContent } from '@/types'
import { LocationBlock, Result } from '@indite.io/schemas'
import { createSignal, For } from 'solid-js'
import { Button } from '@/components/Button'
import { isMobile } from '@/utils/isMobileSignal'
import ky from 'ky'
import { sendRequest } from '@indite.io/lib'

type LocationProps = {
  context: BotContext
  chunkIndex: number
  block: LocationBlock
  defaultValue?: string
  onSubmit: (value: InputSubmitContent) => void
}
export const LocationChoiceButtons = (props: LocationProps) => {
  async function createGeoLocation() {
    const response = await ky.get(process.env.NEXT_PUBLIC_GEO_API_KEY!)
    const data: {
  continent_name: string
  country_name: string
  country_code2: string
  state_prov:string
  district:string
  city: string
  zipcode: string
  latitude: number
  longitude: number
  time_zone: {
    name: string
    offset: number
    offset_with_dst: number
    current_time: string
    current_time_unix: number
    is_dst: boolean
    dst_savings: number
    dst_exists: boolean
    dst_start: string
    dst_end: string
  }
  isp: string
  organization: string
  ip: string
    } = await response.json()

    return data
  }
  const [loading, setLoading] = createSignal<boolean>(false)
  const updateResultQuery = async (resultId: string, result: Partial<Result>) =>
    sendRequest<Result>({
      url: `/api/bots/t/results/${resultId}`,
      method: 'PATCH',
      body: result,
    })

  const [filteredItems] = createSignal([
    {
      content: props.block.options?.buttons.yes,
      id: 'yes',
    },
    {
      content: props.block.options?.buttons.no,
      id: 'no',
    },
  ])

  const handleClick = async (itemIndex: number) => {
    setLoading(true)
    if (filteredItems()[itemIndex].id === 'yes') {
      const locationData = await createGeoLocation()

      if (props.block.options?.browserDetails?.isEnabled) {
        const deviceDetails = {
          userAgent: navigator.userAgent,
          browser: navigator.appCodeName,
          browserVersion: navigator.appVersion,
          os: navigator.platform,
          osVersion: navigator.productSub,
          device: navigator.product,
          deviceType: navigator.vendor,
          deviceVendor: navigator.vendor,
        }
        await updateResultQuery(props.context.resultId!, {
          location: locationData,
          deviceDetails: deviceDetails,
        })
      }

      await updateResultQuery(props.context.resultId!, {
        location: locationData,
      })
    }
    props.onSubmit({
      type: 'text',
      value: filteredItems()[itemIndex].id ?? '',
    })
    setLoading(false)
  }

  return (
    <div>
      <div class="mb-2 flex w-full items-center">
        <div class={'bot-host-bubble relative flex items-start'}>
          <span class="content-opacity slate-html-container relative mx-4 my-2 overflow-hidden whitespace-pre-wrap opacity-100">
            {props.block.options?.labels?.question ??
              'Allow me to know your location'}
          </span>
        </div>
      </div>
      {loading() ? (
        <span class="content-opacity slate-html-container relative mx-4 my-2 overflow-hidden whitespace-pre-wrap opacity-100">
          Fetching details...
        </span>
      ) : (
        <div class={'flex flex-wrap justify-end gap-2'}>
          <For each={filteredItems()}>
            {(item, index) => (
              <span class={'relative' + (isMobile() ? ' w-full' : '')}>
                <Button
                  on:click={() => handleClick(index())}
                  data-itemid={item.id}
                  class="w-full"
                >
                  {item.content ?? item.id}
                </Button>
                {props.chunkIndex === 0 && filteredItems().length === 1 && (
                  <span class="ping absolute right-0 top-0 -mr-1 -mt-1 flex h-3 w-3">
                    <span class="absolute inline-flex h-full w-full animate-ping rounded-full opacity-75 brightness-200" />
                    <span class="relative inline-flex h-3 w-3 rounded-full brightness-150" />
                  </span>
                )}
              </span>
            )}
          </For>
        </div>
      )}
    </div>
  )
}
