"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 { createSupplier, updateSupplier } from "@/actions/catalog";
import { toast } from "sonner";

const formSchema = z.object({
  companyName: z.string().min(1, "Firmenname ist erforderlich"),
  registrationName: z.string().optional().nullable(),
  address: z.string().optional().nullable(),
  email: z.string().email("Ungültige E-Mail-Adresse"),
  phoneNumber: z.string().optional().nullable(),
  website: z.string().optional().nullable(),
});

interface SupplierFormProps {
  initialData?: any;
}

export function SupplierForm({ initialData }: SupplierFormProps) {
  const router = useRouter();

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      companyName: initialData?.companyName ?? initialData?.company_name ?? "",
      registrationName: initialData?.registrationName ?? initialData?.registration_name ?? "",
      address: initialData?.address ?? "",
      email: initialData?.email ?? "",
      phoneNumber: initialData?.phoneNumber ?? initialData?.phone_number ?? "",
      website: initialData?.website ?? "",
    },
  });

  const onSubmit = async (values: z.infer<typeof formSchema>) => {
    const data = {
      ...values,
      registrationName: values.registrationName || null,
      address: values.address || null,
      phoneNumber: values.phoneNumber || null,
      website: values.website || null,
    };

    let result;
    if (initialData?.id) {
      result = await updateSupplier({ id: initialData.id, data });
    } else {
      result = await createSupplier(data);
    }

    if (!result.success) {
      toast.error(result.error);
    } else {
      toast.success(result.message || (initialData ? "Lieferant erfolgreich aktualisiert." : "Lieferant erfolgreich erstellt."));
      router.push("/dashboard/suppliers/overview");
      router.refresh();
    }
  };

  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 ? "Lieferant bearbeiten" : "Neuer Lieferant"}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
              <FormField
                control={form.control}
                name="companyName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Firmenname</FormLabel>
                    <FormControl>
                      <Input placeholder="z.B. ABC GmbH" {...field} value={field.value || ""} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="registrationName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Registrierungsname (optional)</FormLabel>
                    <FormControl>
                      <Input placeholder="z.B. ABC GmbH & Co. KG" {...field} value={field.value || ""} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="address"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Adresse (optional)</FormLabel>
                    <FormControl>
                      <Input placeholder="z.B. Musterstraße 123, 12345 Musterstadt" {...field} value={field.value || ""} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="email"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>E-Mail</FormLabel>
                    <FormControl>
                      <Input type="email" placeholder="z.B. info@abc-gmbh.de" {...field} value={field.value || ""} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="phoneNumber"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Telefonnummer (optional)</FormLabel>
                    <FormControl>
                      <Input placeholder="z.B. +49 123 456789" {...field} value={field.value || ""} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="website"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Website (optional)</FormLabel>
                    <FormControl>
                      <Input placeholder="z.B. https://www.abc-gmbh.de" {...field} value={field.value || ""} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

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