"use client";

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  FormDescription,
} from "@/components/ui/form";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import { handleUpdateSettings } from "@/lib/actions";
import { useTransition } from "react";
import { Loader2 } from "lucide-react";

const formSchema = z.object({
  approvedIpAddress: z.string().optional(),
});

type Translation = {
    approvedIpAddressLabel: string;
    approvedIpAddressDescription: string;
    useMyIpButton: string;
    saveSettingsButton: string;
}

export function UpdateSettingsForm({ t, currentIp, detectedIp }: { t: Translation, currentIp: string, detectedIp: string }) {
  const [isPending, startTransition] = useTransition();
  const { toast } = useToast();
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      approvedIpAddress: currentIp || "",
    },
  });

  async function onSubmit(values: z.infer<typeof formSchema>) {
    startTransition(async () => {
      const result = await handleUpdateSettings(values);
      if (result?.error) {
        toast({
          title: 'فشل التحديث',
          description: result.error,
          variant: 'destructive',
        });
      } else {
        toast({
          title: 'تم الحفظ',
          description: 'تم تحديث الإعدادات بنجاح.',
        });
        form.reset({ approvedIpAddress: values.approvedIpAddress });
      }
    });
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6 max-w-lg">
        <FormField
          control={form.control}
          name="approvedIpAddress"
          render={({ field }) => (
            <FormItem>
              <FormLabel>{t.approvedIpAddressLabel}</FormLabel>
              <div className="flex items-start gap-2">
                <FormControl>
                  <Textarea
                    placeholder="e.g., 192.168.1.1, 192.168.1.2"
                    className="min-h-[120px] font-mono text-sm"
                    {...field}
                  />
                </FormControl>
                <Button 
                  type="button" 
                  variant="outline"
                  className="shrink-0"
                  onClick={() => {
                    const currentVal = form.getValues("approvedIpAddress") || "";
                    const newIp = (currentVal ? `${currentVal}\n` : "") + detectedIp;
                    form.setValue("approvedIpAddress", newIp.trim());
                  }}
                >
                  {t.useMyIpButton}
                </Button>
              </div>
              <FormDescription>
                {t.approvedIpAddressDescription.replace('{ip}', detectedIp)}
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />
        <Button type="submit" disabled={isPending}>
          {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
          {t.saveSettingsButton}
        </Button>
      </form>
    </Form>
  );
}
