'use client'
import theme from "@/theme";
import { Button, ChakraProvider, Container, Flex, Heading, Image, Input, Text } from "@chakra-ui/react";
import { useState } from "react";
import { toaster } from "@/components/ui/toaster";
import { feelingFree } from "@/actions";


export default function Home() {
  const [query, setQuery] = useState<string | undefined>(undefined);
  const feelingFreedom = async () => {
    try {

      if (!query) {
        throw new Error('You must provide a search query.');
      }

      const searchParams = new URLSearchParams();
      searchParams.set('query', query)

      const result = await feelingFree(searchParams.toString());

      if (result.error) {
        throw new Error(result.payload);
      }

      toaster.create({ title: 'Redirecting...', description: 'Was that so hard?', type: 'success' })
      setTimeout(() => {
        window.location.href = result.payload;
      }, 2000)

    } catch (error) {
      if (error instanceof Error) {
        toaster.create({ type: 'error', title: 'Error', description: error.message })
        return;
      }
      return;
    }

  }
  const lmgcitfy = () => {
    if (!query) {
      toaster.create({ title: 'Error', description: 'You must enter a search query.', type: 'error' });
      return;
    }
    const searchParams = new URLSearchParams();

    searchParams.append('query', query);
    window.location.href = `https://guncadindex.com/search?${searchParams}`;
  }
  return (
    <ChakraProvider value={theme}>
      <Container backgroundColor={'#2a2a2a'} borderRadius={'lg'} boxShadow={'0 0 12px #4a4a4a'} py={4} width={{ base: '90%', md: '50%' }} overflow={'hidden'}>
        <Flex justify={'center'} align={'center'} p={2} mb={4}>
          <Image src={'/gci_logo_large.png'} height={{ base: '50px', md: '75px' }} alt="GunCAD Index logo" />
          <Flex flexDir={'column'} mx={4} >
            <Heading size={{ base: '2xl', md: '5xl' }} fontFamily={'var(--font-ibm)'} lineHeight={1}>GunCAD Index</Heading>
            <Text fontSize={{ base: 'sm', md: 'xl' }} ml={{ md: 1 }} fontFamily={'var(--font-ibm)'}>A search engine for guns.</Text>
          </Flex>
        </Flex>
        <Input variant={'outline'} borderRadius={'lg'} border={'1px solid #4a4a4a'} size={'lg'} placeholder="Enter your query here" onChange={(e) => setQuery(e.target.value)} />
        <Flex justify={'space-around'} gapY={4} flexDir={{ base: 'column', md: 'row' }} p={2} my={4}>
          <Button colorPalette={'green'} variant={'solid'} size={'lg'} onClick={() => lmgcitfy()}>Search on GCI</Button>
          <Button colorPalette={'white'} variant={'outline'} size={'lg'} border={'1px solid #4a4a4a'} color={'#FFF'} onClick={() => feelingFreedom()}>I&apos;m feeling free</Button>
        </Flex>
      </Container>
    </ChakraProvider>
  );
}
