"use client"

import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import React, { useEffect } from "react"

import { Button } from "@/components/ui/button"
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { toast } from "@/hooks/use-toast"
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from "../ui/card"
import { Textarea } from "../ui/textarea"
import { getNotificationSettings, setNotificationSettings, type NotificationSettings } from "@/lib/data"
import { Switch } from "../ui/switch"
import { Separator } from "../ui/separator"
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from "../ui/select"

const notificationsFormSchema = z.object({
  smsEnabled: z.boolean(),
  smsProvider: z.enum(['twilio', 'other']),
  smsApiKey: z.string().optional(),
  smsApiSecret: z.string().optional(),
  smsSenderId: z.string().optional(),
  smsMessageTemplate: z.string().optional(),
  whatsappEnabled: z.boolean(),
  whatsappApiKey: z.string().optional(),
  whatsappSenderNumber: z.string().optional(),
  whatsappMessageTemplate: z.string().optional(),
})

type NotificationsFormValues = z.infer<typeof notificationsFormSchema>

export function NotificationsForm() {
  const form = useForm<NotificationsFormValues>({
    resolver: zodResolver(notificationsFormSchema),
    defaultValues: {
      smsEnabled: false,
      smsProvider: 'twilio',
      smsApiKey: '',
      smsApiSecret: '',
      smsSenderId: '',
      smsMessageTemplate: '',
      whatsappEnabled: false,
      whatsappApiKey: '',
      whatsappSenderNumber: '',
      whatsappMessageTemplate: '',
    },
    mode: "onChange",
  })

  useEffect(() => {
    const notificationSettings = getNotificationSettings();
    form.reset(notificationSettings);
  }, [form]);

  function onSubmit(data: NotificationsFormValues) {
    setNotificationSettings(data);
    toast({
      title: "Notification settings updated!",
      description: "Your notification preferences have been saved.",
    })
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
        <Card>
          <CardHeader>
            <CardTitle>SMS Notifications</CardTitle>
            <CardDescription>
              Configure an SMS gateway to automatically notify customers when their order is ready.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <FormField
              control={form.control}
              name="smsEnabled"
              render={({ field }) => (
                <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                  <div className="space-y-0.5">
                    <FormLabel className="text-base">
                      Enable SMS Notifications
                    </FormLabel>
                    <FormDescription>
                      Send an SMS when an order's status is changed to "Ready for Delivery".
                    </FormDescription>
                  </div>
                  <FormControl>
                    <Switch
                      checked={field.value}
                      onCheckedChange={field.onChange}
                    />
                  </FormControl>
                </FormItem>
              )}
            />
            
            <FormField
                control={form.control}
                name="smsProvider"
                render={({ field }) => (
                    <FormItem>
                    <FormLabel>SMS Provider</FormLabel>
                     <Select onValueChange={field.onChange} defaultValue={field.value} disabled={!form.watch('smsEnabled')}>
                        <FormControl>
                        <SelectTrigger>
                            <SelectValue placeholder="Select an SMS provider" />
                        </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                            <SelectItem value="twilio">Twilio</SelectItem>
                            <SelectItem value="other">Other</SelectItem>
                        </SelectContent>
                    </Select>
                    <FormMessage />
                    </FormItem>
                )}
            />
            
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <FormField
                    control={form.control}
                    name="smsApiKey"
                    render={({ field }) => (
                        <FormItem>
                        <FormLabel>API Key / Account SID</FormLabel>
                        <FormControl>
                            <Input placeholder="Your API Key or SID" {...field} disabled={!form.watch('smsEnabled')} />
                        </FormControl>
                        <FormMessage />
                        </FormItem>
                    )}
                />
                 <FormField
                    control={form.control}
                    name="smsApiSecret"
                    render={({ field }) => (
                        <FormItem>
                        <FormLabel>API Secret / Auth Token</FormLabel>
                        <FormControl>
                            <Input type="password" placeholder="Your API Secret or Token" {...field} disabled={!form.watch('smsEnabled')} />
                        </FormControl>
                        <FormMessage />
                        </FormItem>
                    )}
                />
            </div>
            <FormField
                control={form.control}
                name="smsSenderId"
                render={({ field }) => (
                    <FormItem>
                    <FormLabel>Sender ID / Phone Number</FormLabel>
                    <FormControl>
                        <Input placeholder="e.g., +15551234567" {...field} disabled={!form.watch('smsEnabled')} />
                    </FormControl>
                    <FormMessage />
                    </FormItem>
                )}
            />
            <FormField
                control={form.control}
                name="smsMessageTemplate"
                render={({ field }) => (
                    <FormItem>
                    <FormLabel>Message Template</FormLabel>
                    <FormControl>
                        <Textarea placeholder="Your SMS message template" {...field} disabled={!form.watch('smsEnabled')} />
                    </FormControl>
                    <FormDescription>
                        Use placeholders like {"{customerName}"}, {"{orderId}"}, {"{dueAmount}"}, {"{shopName}"}.
                    </FormDescription>
                    <FormMessage />
                    </FormItem>
                )}
            />
          </CardContent>
        </Card>
        
        <Card>
          <CardHeader>
            <CardTitle>WhatsApp Notifications</CardTitle>
            <CardDescription>
              Configure a WhatsApp Business API to send notifications.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
             <FormField
              control={form.control}
              name="whatsappEnabled"
              render={({ field }) => (
                <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                  <div className="space-y-0.5">
                    <FormLabel className="text-base">
                      Enable WhatsApp Notifications
                    </FormLabel>
                    <FormDescription>
                     Send a WhatsApp message when an order is ready for delivery.
                    </FormDescription>
                  </div>
                  <FormControl>
                    <Switch
                      checked={field.value}
                      onCheckedChange={field.onChange}
                    />
                  </FormControl>
                </FormItem>
              )}
            />
             <FormField
                control={form.control}
                name="whatsappApiKey"
                render={({ field }) => (
                    <FormItem>
                    <FormLabel>WhatsApp API Key</FormLabel>
                    <FormControl>
                        <Input type="password" placeholder="Your WhatsApp API Key" {...field} disabled={!form.watch('whatsappEnabled')} />
                    </FormControl>
                    <FormMessage />
                    </FormItem>
                )}
            />
            <FormField
                control={form.control}
                name="whatsappSenderNumber"
                render={({ field }) => (
                    <FormItem>
                    <FormLabel>WhatsApp Sender Number</FormLabel>
                    <FormControl>
                        <Input placeholder="e.g., +15551234567" {...field} disabled={!form.watch('whatsappEnabled')} />
                    </FormControl>
                    <FormMessage />
                    </FormItem>
                )}
            />
             <FormField
                control={form.control}
                name="whatsappMessageTemplate"
                render={({ field }) => (
                    <FormItem>
                    <FormLabel>WhatsApp Message Template</FormLabel>
                    <FormControl>
                        <Textarea placeholder="Your WhatsApp message template" {...field} disabled={!form.watch('whatsappEnabled')} />
                    </FormControl>
                    <FormDescription>
                        Use placeholders like {"{customerName}"}, {"{orderId}"}, {"{dueAmount}"}, {"{shopName}"}.
                    </FormDescription>
                    <FormMessage />
                    </FormItem>
                )}
            />
          </CardContent>
        </Card>
        
        <div className="flex justify-end">
            <Button type="submit">Save Notification Settings</Button>
        </div>
      </form>
    </Form>
  )
}
