'use client'

import { upsertFormSettings } from '@admin/actions/forms'
import { Button } from '@admin/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@admin/components/ui/card'
import {
  Drawer,
  DrawerClose,
  DrawerContent,
  DrawerDescription,
  DrawerFooter,
  DrawerHeader,
  DrawerTitle
} from '@admin/components/ui/drawer'
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from '@admin/components/ui/form'
import { ScrollArea } from '@admin/components/ui/scroll-area'
import { Spinner } from '@admin/components/ui/spinner'
import { Textarea } from '@admin/components/ui/textarea'
import { standardSchemaResolver } from '@hookform/resolvers/standard-schema'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import { z } from 'zod/v3'

const notificationsSchema = z.object({
  notificationEmails: z.string().trim()
})

type NotificationsFormValues = z.infer<typeof notificationsSchema>

interface FormNotificationsDrawerProps {
  formLabel: string
  settingsKey: string
  initialEmails: string
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function FormNotificationsDrawer({
  formLabel,
  settingsKey,
  initialEmails,
  open,
  onOpenChange
}: FormNotificationsDrawerProps) {
  const queryClient = useQueryClient()

  const form = useForm<NotificationsFormValues>({
    resolver: standardSchemaResolver(notificationsSchema),
    defaultValues: { notificationEmails: initialEmails }
  })

  const mutation = useMutation({
    mutationFn: async (values: NotificationsFormValues) => {
      const result = await upsertFormSettings(settingsKey, {
        notificationEmails: values.notificationEmails || null
      })
      if (!result.success) {
        throw new Error(result.error || 'Failed to save notification emails')
      }

      return result
    },
    onSuccess: async () => {
      toast.success('Notification emails saved')
      await queryClient.invalidateQueries({ queryKey: ['form-settings'] })
      onOpenChange(false)
    },
    onError: (error: Error) => {
      toast.error(error.message || 'Failed to save these notification settings')
    }
  })

  const isPending = mutation.isPending

  return (
    <Drawer swipeDirection="right" open={open} onOpenChange={onOpenChange} modal>
      <DrawerContent className="h-full max-w-xl">
        <Form {...form}>
          <form
            autoComplete="off"
            onSubmit={form.handleSubmit((values) => mutation.mutate(values))}
            className="flex min-h-0 flex-1 flex-col gap-4"
          >
            <DrawerHeader>
              <DrawerTitle>{formLabel} notifications</DrawerTitle>
              <DrawerDescription>
                Send an email to these addresses when a submission arrives. Webhooks are managed on
                the Webhooks tab.
              </DrawerDescription>
            </DrawerHeader>

            <ScrollArea className="min-h-0 flex-1 px-6">
              <Card>
                <CardHeader>
                  <CardTitle>Notifications</CardTitle>
                </CardHeader>
                <CardContent>
                  <FormField
                    control={form.control}
                    name="notificationEmails"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Notification emails</FormLabel>
                        <FormControl>
                          <Textarea
                            placeholder="sales@example.com, team@example.com"
                            disabled={isPending}
                            {...field}
                          />
                        </FormControl>
                        <FormDescription>
                          Comma-separated email addresses. Leave empty to disable notifications.
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </CardContent>
              </Card>
            </ScrollArea>

            <DrawerFooter className="flex-row justify-end">
              <DrawerClose
                render={<Button type="button" variant="outline" size="lg" disabled={isPending} />}
              >
                Cancel
              </DrawerClose>
              <Button
                type="submit"
                disabled={isPending || !form.formState.isDirty}
                aria-busy={isPending}
                size="lg"
              >
                {isPending && <Spinner />}
                {isPending ? 'Saving…' : 'Save'}
              </Button>
            </DrawerFooter>
          </form>
        </Form>
      </DrawerContent>
    </Drawer>
  )
}
