"use client"

import React from 'react'
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"

import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form"
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { useLoading } from '@/lib/useLoading'
import { addToken } from '@/actions/ttd'
import { toast } from 'sonner'

const formSchema = z.object({
    name: z.string().min(1,"Name cannot empty."),
})

interface Props {
    onAction: () => void;
}
const AddToken = ({onAction}: Props) => {

    const {setLoading} = useLoading()
    const form = useForm({
        resolver: zodResolver(formSchema),
        defaultValues: {
            name: "",
        }
    })

    const onSubmit = async (values: z.infer<typeof formSchema>) => {
        setLoading(true)
        const response = await addToken(values)
        if(response.success){
            toast.success(response.message)
            form.reset();
            onAction()
        }else{
            toast.error(response.message)
        }
    }
    return (
        <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className='space-y-6'>
                <FormField
                    control={form.control}
                    name="name"
                    render={({ field }) => (
                        <FormItem>
                            <div className='flex items-center gap-2'>
                                <FormLabel>Token Name</FormLabel>
                            </div>
                            <FormControl>
                                <Input {...field} placeholder="Enter name"/>
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />
                <Button type="submit" variant="blue">
                    Create
                </Button>
            </form>
        </Form>
    )
}

export default AddToken