"use client"

import { useState } from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import { Settings } from "lucide-react"
import { toast } from "sonner"

import { Button } from "@/components/ui/button"
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from "@/components/ui/dialog"
import {
    Form,
    FormControl,
    FormDescription,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Checkbox } from "@/components/ui/checkbox"
import { updatePlan } from "@/app/actions/plan"

interface PlanSettingsProps {
    planId: string
    initialInstructions: string | null
    initialWebhookUrl: string | null
    initialNotifyAll: boolean
    dict: any
    lang: string
}

export function PlanSettings({
    planId,
    initialInstructions,
    initialWebhookUrl,
    initialNotifyAll,
    dict,
    lang
}: PlanSettingsProps) {
    const [open, setOpen] = useState(false)
    const [isPending, setIsPending] = useState(false)

    const formSchema = z.object({
        instructions: z.string().optional(),
        webhookUrl: z.string().url().optional().or(z.literal("")),
        notifyAll: z.boolean(),
    })

    type FormValues = z.infer<typeof formSchema>

    const form = useForm<FormValues>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            instructions: initialInstructions || "",
            webhookUrl: initialWebhookUrl || "",
            notifyAll: initialNotifyAll,
        },
    })

    async function onSubmit(data: FormValues) {
        setIsPending(true)
        try {
            await updatePlan(planId, data, lang)
            toast.success(dict.success)
            setOpen(false)
        } catch (error) {
            toast.error(dict.error)
        } finally {
            setIsPending(false)
        }
    }

    return (
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogTrigger asChild>
                <Button variant="outline" size="sm">
                    <Settings className="w-4 h-4 mr-2" />
                    {dict.title.split(" ")[1] || "Settings"}
                </Button>
            </DialogTrigger>
            <DialogContent className="sm:max-w-[425px]">
                <DialogHeader>
                    <DialogTitle>{dict.title}</DialogTitle>
                    <DialogDescription>
                        {dict.description}
                    </DialogDescription>
                </DialogHeader>
                <Form {...form}>
                    <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                        <FormField
                            control={form.control}
                            name="webhookUrl"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{dict.webhookLabel}</FormLabel>
                                    <FormControl>
                                        <Input
                                            placeholder={dict.webhookPlaceholder}
                                            {...field}
                                        />
                                    </FormControl>
                                    <FormDescription>
                                        {dict.webhookDesc}
                                    </FormDescription>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <FormField
                            control={form.control}
                            name="notifyAll"
                            render={({ field }) => (
                                <FormItem className="flex flex-row items-start space-x-3 space-y-0 rounded-md border p-4">
                                    <FormControl>
                                        <Checkbox
                                            checked={field.value}
                                            onCheckedChange={field.onChange}
                                        />
                                    </FormControl>
                                    <div className="space-y-1 leading-none">
                                        <FormLabel>
                                            {dict.notifyAllLabel}
                                        </FormLabel>
                                        <FormDescription>
                                            {dict.notifyAllDesc}
                                        </FormDescription>
                                    </div>
                                </FormItem>
                            )}
                        />
                        <FormField
                            control={form.control}
                            name="instructions"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{dict.instructionsLabel}</FormLabel>
                                    <FormControl>
                                        <Textarea
                                            placeholder={dict.instructionsPlaceholder}
                                            className="h-32"
                                            {...field}
                                        />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <DialogFooter>
                            <Button type="submit" disabled={isPending}>
                                {isPending ? dict.saving : dict.save}
                            </Button>
                        </DialogFooter>
                    </form>
                </Form>
            </DialogContent>
        </Dialog>
    )
}
