'use client';

import { zodResolver } from "@hookform/resolvers/zod"
import { useFieldArray, useForm } from "react-hook-form"
import { z } from "zod"
import { useEffect } from "react";

import { Button } from "@/components/ui/button"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { toast } from "@/hooks/use-toast"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui/card"
import { getMockServices, setMockServices } from "@/lib/data";

const servicesFormSchema = z.object({
  services: z.array(
    z.object({
      id: z.string(), // Keep an ID for stable rendering
      name: z.string().min(1, "Name is required."),
      description: z.string().optional(),
      price: z.coerce.number().min(0, "Price must be a positive number."),
    })
  ),
})

type ServicesFormValues = z.infer<typeof servicesFormSchema>

export function ServicesForm() {
  const form = useForm<ServicesFormValues>({
    resolver: zodResolver(servicesFormSchema),
    defaultValues: {
      services: getMockServices(),
    },
    mode: "onChange",
  })
  
  useEffect(() => {
    form.reset({ services: getMockServices() });
  }, [form]);


  const { fields, append, remove } = useFieldArray({
    name: "services",
    control: form.control,
  })

  function onSubmit(data: ServicesFormValues) {
    setMockServices(data.services);
    toast({
      title: "Services updated!",
      description: "Your list of services has been successfully saved.",
    })
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Manage Services</CardTitle>
        <CardDescription>
          Add, edit, or remove the services you offer.
        </CardDescription>
      </CardHeader>
      <CardContent>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
            <div className="space-y-4">
              {fields.map((field, index) => (
                <div key={field.id} className="p-4 border rounded-md space-y-4 relative">
                    <Button
                        type="button"
                        variant="destructive"
                        size="sm"
                        className="absolute top-2 right-2"
                        onClick={() => remove(index)}
                    >
                        Remove
                    </Button>
                  <FormField
                    control={form.control}
                    name={`services.${index}.name`}
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Service Name</FormLabel>
                        <FormControl>
                          <Input {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name={`services.${index}.price`}
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Price</FormLabel>
                        <FormControl>
                          <Input type="number" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name={`services.${index}.description`}
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Description</FormLabel>
                        <FormControl>
                          <Textarea
                            placeholder="Describe the service"
                            className="resize-none"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              ))}
            </div>

            <Button
              type="button"
              variant="outline"
              size="sm"
              className="mt-2"
              onClick={() => append({ id: `service-${Date.now()}`, name: "", price: 0, description: "" })}
            >
              Add Service
            </Button>
            
            <div className="mt-8">
                <Button type="submit">Update Services</Button>
            </div>
          </form>
        </Form>
      </CardContent>
    </Card>
  )
}
