"use client";

import React, { useMemo } from "react";
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 { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useRouter } from "next/navigation";
import { createProduct, updateProduct } from "@/actions/catalog";
import { toast } from "sonner";
import { ProductSchema } from "@/lib/db/schemas/db";
import { UniversalCombobox } from "@/components/dashboard/UniversalCombobox";
import { ProductAttributesManager } from "./ProductAttributesManager";
import { Package, Truck, Layers, Settings2, Info } from "lucide-react";

interface Option {
  id: string;
  name: string;
}

interface CompanyOption {
  id: string;
  name: string;
}

const formSchema = z.object({
  name: z.string().min(1, "Name ist erforderlich"),
  title: z.string().min(1, "Titel ist erforderlich"),
  mpn: z.string().min(1, "MPN ist erforderlich"),
  sku: z.string().min(1, "SKU ist erforderlich"),
  price: z.coerce.number().min(0, "Preis muss positiv sein"),
  inventory: z.coerce.number().int().min(0, "Bestand muss positiv sein"),
  ean: z.string().nullable().optional(),
  description: z.string().nullable().optional(),
  weight: z.preprocess((v) => (v === "" || v === null || v === undefined) ? null : Number(v), z.number().nullable().optional()),
  height: z.preprocess((v) => (v === "" || v === null || v === undefined) ? null : Number(v), z.number().nullable().optional()),
  length: z.preprocess((v) => (v === "" || v === null || v === undefined) ? null : Number(v), z.number().nullable().optional()),
  width: z.preprocess((v) => (v === "" || v === null || v === undefined) ? null : Number(v), z.number().nullable().optional()),
  manufacturer_id: z.string().uuid("Hersteller ist erforderlich"),
  supplier_id: z.string().uuid("Lieferant ist erforderlich"),
  brand_id: z.string().uuid("Marke ist erforderlich"),
  category_id: z.string().uuid("Kategorie ist erforderlich"),
  tax_class_id: z.string().uuid("Steuerklasse ist erforderlich"),
  eu_responsible_person_id: z.string().uuid("EU-Verantwortlicher ist erforderlich"),
});

interface ProductFormProps {
  initialData?: Partial<z.infer<typeof ProductSchema> & {
    image?: string;
  }>;
  categories: Option[];
  brands: Option[];
  manufacturers: CompanyOption[];
  suppliers: CompanyOption[];
  taxClasses: Option[];
  euResponsiblePersons: CompanyOption[];
}

export function ProductForm({
  initialData,
  categories,
  brands,
  manufacturers,
  suppliers,
  taxClasses,
  euResponsiblePersons,
}: ProductFormProps) {
  const router = useRouter();

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: initialData?.name || "",
      title: initialData?.title || "",
      mpn: initialData?.mpn || "",
      sku: initialData?.sku || "",
      price: initialData?.price || 0,
      inventory: initialData?.inventory || 0,
      ean: initialData?.ean || "",
      description: initialData?.description || "",
      weight: initialData?.weight || null,
      height: initialData?.height || null,
      length: initialData?.length || null,
      width: initialData?.width || null,
      manufacturer_id: initialData?.manufacturer_id || "",
      supplier_id: initialData?.supplier_id || "",
      brand_id: initialData?.brand_id || "",
      category_id: initialData?.category_id || "",
      tax_class_id: initialData?.tax_class_id || "",
      eu_responsible_person_id: initialData?.eu_responsible_person_id || "",
    },
  });

  const onSubmit = async (values: z.infer<typeof formSchema>) => {
    try {
      const data = {
        ...values,
        currency: initialData?.currency || "EUR",
        product_group_id: null,
      };

      let response;
      if (initialData && initialData.id) {
        response = await updateProduct({ id: initialData.id, data });
      } else {
        response = await createProduct(data);
      }

      if (!response.success) {
        toast.error(response.error || "Etwas ist schief gelaufen.");
        return;
      }

      toast.success("Produkt erfolgreich gespeichert.");
      router.push("/dashboard/products/overview");
      router.refresh();
    } catch (error) {
      if (error instanceof Error && error.message.includes("NEXT_REDIRECT")) {
        throw error;
      }
      toast.error("Ein unerwarteter Fehler ist aufgetreten.");
    }
  };

  const categoryOptions = useMemo(() => categories.map(i => ({ value: i.id, label: i.name })), [categories]);
  const brandOptions = useMemo(() => brands.map(i => ({ value: i.id, label: i.name })), [brands]);
  const manufacturerOptions = useMemo(() => manufacturers.map(i => ({ value: i.id, label: i.name })), [manufacturers]);
  const supplierOptions = useMemo(() => suppliers.map(i => ({ value: i.id, label: i.name })), [suppliers]);
  const taxClassOptions = useMemo(() => taxClasses.map(i => ({ value: i.id, label: i.name })), [taxClasses]);
  const euResponsiblePersonOptions = useMemo(() => euResponsiblePersons.map(i => ({ value: i.id, label: i.name })), [euResponsiblePersons]);

  return (
    <div className="w-full">
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-10">
          <Tabs defaultValue="general" className="space-y-6">
            <div className="flex items-center justify-between">
              <TabsList className="rounded-md border bg-muted/50 p-1">
                <TabsTrigger value="general" className="gap-2 rounded-sm px-4 py-1.5 text-sm">
                  <Info className="size-3.5" />
                  Allgemein
                </TabsTrigger>
                <TabsTrigger value="inventory" className="gap-2 rounded-sm px-4 py-1.5 text-sm">
                  <Package className="size-3.5" />
                  Bestand
                </TabsTrigger>
                <TabsTrigger value="organization" className="gap-2 rounded-sm px-4 py-1.5 text-sm">
                  <Settings2 className="size-3.5" />
                  Organisation
                </TabsTrigger>
                <TabsTrigger value="dimensions" className="gap-2 rounded-sm px-4 py-1.5 text-sm">
                  <Truck className="size-3.5" />
                  Logistik
                </TabsTrigger>
                <TabsTrigger value="attributes" disabled={!initialData} className="gap-2 rounded-sm px-4 py-1.5 text-sm">
                  <Layers className="size-3.5" />
                  Attribute
                </TabsTrigger>
              </TabsList>

              <div className="flex flex-wrap items-center gap-3">
                <Button 
                  type="button" 
                  variant="outline" 
                  onClick={() => router.back()}
                  className="rounded-md h-9"
                >
                  Abbrechen
                </Button>
                <Button type="submit" className="rounded-md h-9 px-6">
                  {initialData ? "Aktualisieren" : "Erstellen"}
                </Button>
              </div>
            </div>

            <TabsContent value="general" className="space-y-6 outline-none">
              <Card className="rounded-md border shadow-none">
                <CardHeader>
                  <CardTitle>Basis-Informationen</CardTitle>
                  <CardDescription>Geben Sie die wichtigsten Details Ihres Produkts ein.</CardDescription>
                </CardHeader>
                <CardContent className="space-y-6">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <FormField
                      control={form.control}
                      name="name"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel className="text-sm font-semibold">Interner Name</FormLabel>
                          <FormControl>
                            <Input placeholder="z.B. Office Chair Pro v2" className="rounded-md h-10" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="title"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel className="text-sm font-semibold">Anzeige-Titel</FormLabel>
                          <FormControl>
                            <Input placeholder="Öffentlicher Name im Shop" className="rounded-md h-10" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <FormField
                      control={form.control}
                      name="mpn"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel className="text-sm font-semibold">MPN</FormLabel>
                          <FormControl>
                            <Input placeholder="Hersteller-Teilenummer" className="rounded-md h-10" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="ean"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel className="text-sm font-semibold">EAN (GTIN)</FormLabel>
                          <FormControl>
                            <Input placeholder="Europäische Artikelnummer" className="rounded-md h-10" {...field} value={field.value || ""} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormItem>
                      <FormLabel className="text-sm font-semibold">UUID</FormLabel>
                      <FormControl>
                        <Input 
                          value={initialData?.id || "Wird generiert..."} 
                          disabled 
                          className="bg-muted/30 font-mono text-xs h-10 rounded-md"
                        />
                      </FormControl>
                    </FormItem>
                  </div>

                  <FormField
                    control={form.control}
                    name="description"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="text-sm font-semibold">Beschreibung</FormLabel>
                        <FormControl>
                          <Textarea 
                            placeholder="Detaillierte Produktbeschreibung..." 
                            className="min-h-[150px] rounded-md resize-none" 
                            {...field} 
                            value={field.value || ""}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="inventory" className="space-y-6 outline-none">
              <Card className="rounded-md border shadow-none">
                <CardHeader>
                  <CardTitle>Bestand & Preise</CardTitle>
                  <CardDescription>Verwalten Sie die Lagerbestände und den Verkaufspreis.</CardDescription>
                </CardHeader>
                <CardContent className="space-y-6">
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <FormField
                      control={form.control}
                      name="sku"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel className="text-sm font-semibold">SKU</FormLabel>
                          <FormControl>
                            <Input placeholder="Lagerhaltungsnummer" className="rounded-md h-10" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="price"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel className="text-sm font-semibold">Preis (EUR)</FormLabel>
                          <FormControl>
                            <Input type="number" step="0.01" className="rounded-md h-10" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="inventory"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel className="text-sm font-semibold">Lagerbestand</FormLabel>
                          <FormControl>
                            <Input type="number" className="rounded-md h-10" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="organization" className="space-y-6 outline-none">
              <Card className="rounded-md border shadow-none">
                <CardHeader>
                  <CardTitle>Klassifizierung & Steuern</CardTitle>
                  <CardDescription>Ordnen Sie das Produkt Herstellern und Steuerklassen zu.</CardDescription>
                </CardHeader>
                <CardContent className="space-y-6">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <FormField
                      control={form.control}
                      name="category_id"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel className="text-sm font-semibold">Kategorie</FormLabel>
                          <UniversalCombobox
                            label="Kategorie"
                            name="category_id"
                            options={categoryOptions}
                            value={field.value}
                            onChange={field.onChange}
                          />
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="brand_id"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel className="text-sm font-semibold">Marke</FormLabel>
                          <UniversalCombobox
                            label="Marke"
                            name="brand_id"
                            options={brandOptions}
                            value={field.value}
                            onChange={field.onChange}
                          />
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <FormField
                      control={form.control}
                      name="manufacturer_id"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel className="text-sm font-semibold">Hersteller</FormLabel>
                          <UniversalCombobox
                            label="Hersteller"
                            name="manufacturer_id"
                            options={manufacturerOptions}
                            value={field.value}
                            onChange={field.onChange}
                          />
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="supplier_id"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel className="text-sm font-semibold">Lieferant</FormLabel>
                          <UniversalCombobox
                            label="Lieferant"
                            name="supplier_id"
                            options={supplierOptions}
                            value={field.value}
                            onChange={field.onChange}
                          />
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <FormField
                      control={form.control}
                      name="tax_class_id"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel className="text-sm font-semibold">Steuerklasse</FormLabel>
                          <UniversalCombobox
                            label="Steuerklasse"
                            name="tax_class_id"
                            options={taxClassOptions}
                            value={field.value}
                            onChange={field.onChange}
                          />
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="eu_responsible_person_id"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel className="text-sm font-semibold">EU-Verantwortlicher</FormLabel>
                          <UniversalCombobox
                            label="Verantwortlicher"
                            name="eu_responsible_person_id"
                            options={euResponsiblePersonOptions}
                            value={field.value}
                            onChange={field.onChange}
                          />

                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="dimensions" className="space-y-6 outline-none">
              <Card className="rounded-md border shadow-none">
                <CardHeader>
                  <CardTitle>Gewicht & Abmessungen</CardTitle>
                  <CardDescription>Wichtig für Versandkostenberechnung und Logistik.</CardDescription>
                </CardHeader>
                <CardContent className="space-y-6">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <FormField
                      control={form.control}
                      name="weight"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel className="text-sm font-semibold">Gewicht (kg)</FormLabel>
                          <FormControl>
                            <Input type="number" step="0.01" className="rounded-md h-10" {...field} value={field.value || ""} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="length"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel className="text-sm font-semibold">Länge (cm)</FormLabel>
                          <FormControl>
                            <Input type="number" step="0.1" className="rounded-md h-10" {...field} value={field.value || ""} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <FormField
                      control={form.control}
                      name="width"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel className="text-sm font-semibold">Breite (cm)</FormLabel>
                          <FormControl>
                            <Input type="number" step="0.1" className="rounded-md h-10" {...field} value={field.value || ""} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="height"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel className="text-sm font-semibold">Höhe (cm)</FormLabel>
                          <FormControl>
                            <Input type="number" step="0.1" className="rounded-md h-10" {...field} value={field.value || ""} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="attributes" className="space-y-6 outline-none">
              {initialData && initialData.id && (
                <ProductAttributesManager productId={initialData.id} />
              )}
            </TabsContent>
          </Tabs>
        </form>
      </Form>
    </div>
  );
}
