"use client";
import React from "react";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
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 { categorySchema } from "@/lib/validation/zod/category";
import { Category } from "@/server/db/schema";
import { Textarea } from "../ui/textarea";
import { updateCategory } from "@/server/actions/category";
import { toast } from "sonner";
import ImageUploadButton from "../image-upload-form";
import Image from "next/image";
import { AspectRatio } from "../ui/aspect-ratio";

export const CATEGORY_BANNER_ASPECT_RATIO = 20 / 3;

function CategoryForm({ server_category }: { server_category: Category }) {
  const form = useForm<z.infer<typeof categorySchema>>({
    resolver: zodResolver(categorySchema),
    defaultValues: {
      name: server_category?.name ?? "",
      description: server_category?.description ?? "",
      image: server_category?.image ?? "",
    },
  });

  // 2. Define a submit handler.
  async function onSubmit(values: z.infer<typeof categorySchema>) {
    const success = await updateCategory(values, server_category.id);
    if (success) {
      toast.success("Kategorie gespeichert.");
      form.reset();
    } else toast.error("Speichern fehlgeschlagen.");
  }
  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
        <FormField
          control={form.control}
          name="name"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Name der Kategorie</FormLabel>
              <FormControl>
                <Input placeholder="Name der Kategorie" {...field} />
              </FormControl>

              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="description"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Beschreibung der Kategorie</FormLabel>
              <FormControl>
                <Textarea
                  placeholder="Das ist eine kurze beschreibung"
                  {...field}
                />
              </FormControl>

              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="image"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Kategorie Banner</FormLabel>
              <FormControl>
                <ImageUploadButton
                  onUploaded={(url) => {
                    field.onChange(url);
                    form.handleSubmit(onSubmit)();
                  }}
                />
              </FormControl>
              <FormMessage />

              {field.value?.length ? (
                <AspectRatio
                  ratio={CATEGORY_BANNER_ASPECT_RATIO}
                  className="w-full max-w-lg bg-muted"
                >
                  <Image
                    src={field.value}
                    alt="Kategorie-bild"
                    fill
                    className="h-full w-full rounded-md object-cover"
                  />
                </AspectRatio>
              ) : null}
            </FormItem>
          )}
        />
        <Button type="submit" disabled={!form.formState.isDirty}>
          Kategorie Speichern
        </Button>
      </form>
    </Form>
  );
}

export default CategoryForm;
