"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,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useRouter } from "next/navigation";
import { createCategory, updateCategory } from "@/actions/catalog";
import { useAction } from "@/hooks/useAction";
import { UniversalCombobox } from "@/components/dashboard/UniversalCombobox";
import { useEffect, useMemo } from "react";

const formSchema = z.object({
  name: z.string().min(1, "Name ist erforderlich"),
  parent_id: z.string().uuid().nullable().optional(),
});

interface CategoryFormProps {
  initialData?: any;
  categories: { id: string; name: string }[];
}

export function CategoryForm({ initialData, categories }: CategoryFormProps) {
  const router = useRouter();

  // Create/Update hooks
  const createAction = useAction(createCategory);
  const updateAction = useAction(updateCategory);

  const isLoading = createAction.isLoading || updateAction.isLoading;
  const validationErrors = createAction.validationErrors || updateAction.validationErrors;

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: initialData?.name || "",
      parent_id: initialData?.parent_id || null,
    },
  });

  // Sync server-side validation errors back to react-hook-form
  useEffect(() => {
    if (validationErrors) {
      Object.keys(validationErrors).forEach((key) => {
        form.setError(key as any, {
          type: "server",
          message: validationErrors[key][0],
        });
      });
    }
  }, [validationErrors, form]);

  const onSubmit = async (values: z.infer<typeof formSchema>) => {
    let response;
    if (initialData) {
      response = await updateAction.execute({
        id: initialData.id,
        data: { name: values.name, parent_id: values.parent_id }
      });
    } else {
      response = await createAction.execute({
        name: values.name,
        parent_id: values.parent_id
      });
    }

    if (response?.success) {
      router.push("/dashboard/categories/overview");
      router.refresh();
    }
  };

  const categoryOptions = useMemo(() => {
    return categories
      .filter((c) => c.id !== initialData?.id) // Prevent selecting self as parent
      .map((c) => ({
        value: c.id,
        label: c.name,
      }));
  }, [categories, initialData?.id]);

  return (
    <div className="flex justify-center">
      <Card className="w-full max-w-2xl border-border-light dark:border-border-dark shadow-sm">
        <CardHeader>
          <CardTitle className="text-xl font-semibold">
            {initialData ? "Kategorie bearbeiten" : "Neue Kategorie"}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Name</FormLabel>
                    <FormControl>
                      <Input placeholder="z.B. Elektronik" {...field} disabled={isLoading} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="parent_id"
                render={({ field }) => (
                  <FormItem className="flex flex-col">
                    <FormControl>
                      <UniversalCombobox
                        label="Übergeordnete Kategorie"
                        name="parent_id"
                        options={categoryOptions}
                        value={field.value || ""}
                        onChange={field.onChange}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <div className="flex justify-end gap-4 pt-4 border-t">
                <Button
                  type="button"
                  variant="outline"
                  disabled={isLoading}
                  onClick={() => router.push("/dashboard/categories/overview")}
                >
                  Abbrechen
                </Button>
                <Button type="submit" disabled={isLoading}>
                  {isLoading ? "Wird verarbeitet..." : (initialData ? "Aktualisieren" : "Erstellen")}
                </Button>
              </div>
            </form>
          </Form>
        </CardContent>
      </Card>
    </div>
  );
}
