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

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

interface EuResponsiblePersonFormProps {
  initialData?: any;
}

export function EuResponsiblePersonForm({ initialData }: EuResponsiblePersonFormProps) {
  const router = useRouter();

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

  const onSubmit = async (values: z.infer<typeof formSchema>) => {
    try {
      const data = {
        companyName: values.companyName,
        email: values.email,
        phoneNumber: values.phoneNumber || null,
        address: values.address || null,
      };
      let result;
      if (initialData) {
        result = await updateEuResponsiblePerson({ id: initialData.id, data });
      } else {
        result = await createEuResponsiblePerson(data);
      }

      if (!result.success) {
        toast.error(result.error);
        return;
      }

      toast.success(result.message || "Erfolgreich gespeichert.");
      router.push("/dashboard/eu-responsible-persons/overview");
      router.refresh();
    } catch (error) {
      toast.error("Etwas ist schief gelaufen.");
    }
  };

  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 ? "EU Verantwortliche Person bearbeiten" : "Neue EU Verantwortliche Person"}
          </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="email"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>E-Mail</FormLabel>
                    <FormControl>
                      <Input type="email" placeholder="z.B. info@abc-gmbh.de" {...field} />
                    </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="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>
                )}
              />

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