"use client"

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

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"

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

type FormValues = z.infer<typeof formSchema>

type PlanSettingsProps = {
    planId: string
    initialWebhookUrl?: string | null
    initialInstructions?: string | null
    initialNotifyAll?: boolean
}

export function PlanSettings({ planId, initialWebhookUrl, initialInstructions, initialNotifyAll = true }: PlanSettingsProps) {
    const [open, setOpen] = useState(false)
    const router = useRouter()

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

    async function onSubmit(values: FormValues) {
        try {
            await updatePlan(planId, {
                webhookUrl: values.webhookUrl || "",
                instructions: values.instructions || "",
                notifyAll: values.notifyAll,
            })
            toast.success("Settings updated")
            setOpen(false)
            router.refresh()
        } catch {
            toast.error("Failed to update settings")
        }
    }

    return (
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogTrigger asChild>
                <Button variant="outline" size="sm">
                    <Settings className="w-4 h-4 mr-2" />
                    Settings
                </Button>
            </DialogTrigger>
            <DialogContent className="sm:max-w-[425px]">
                <DialogHeader>
                    <DialogTitle>Plan Settings</DialogTitle>
                    <DialogDescription>
                        Configure notification webhooks and cat care instructions.
                    </DialogDescription>
                </DialogHeader>
                <Form {...form}>
                    <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                        <FormField
                            control={form.control}
                            name="instructions"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Cat Instructions</FormLabel>
                                    <FormControl>
                                        <Textarea
                                            placeholder="Feeding times, vet contact, special needs..."
                                            className="min-h-[100px]"
                                            {...field}
                                        />
                                    </FormControl>
                                    <FormDescription>
                                        Visible to all sitters.
                                    </FormDescription>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <FormField
                            control={form.control}
                            name="webhookUrl"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Notification Webhook</FormLabel>
                                    <FormControl>
                                        <Input placeholder="https://discord.com/api/webhooks/..." {...field} />
                                    </FormControl>
                                    <FormDescription>
                                        Telegram or Discord webhook URL.
                                    </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>
                                            Notify for all events
                                        </FormLabel>
                                        <FormDescription>
                                            If disabled, only cancellations will be notified.
                                        </FormDescription>
                                    </div>
                                </FormItem>
                            )}
                        />
                        <DialogFooter>
                            <Button type="submit">Save changes</Button>
                        </DialogFooter>
                    </form>
                </Form>
            </DialogContent>
        </Dialog>
    )
}
