"use client";

import React, { useEffect, useMemo, useCallback } from "react";
import { 
  EntityFormWrapper,
  ServerActionForm,
  FormActions,
  TextField,
  NumberField,
  SelectField,
  TextAreaField,
  useServerActionForm
} from "../../dashboard/entity-detail/shared";
import { taxClassConfig, taxClassSchema } from "../../dashboard/entity-detail/entities/tax-class/TaxClassConfig";
import { useAction } from "@/hooks/useAction";
import { createTaxClass, updateTaxClass, deleteTaxClass } from "@/actions/catalog";
import type { z } from "zod";
import { toast } from "sonner";

type TaxClassFormData = z.infer<typeof taxClassSchema>;

interface TaxClassFormProps {
  initialData?: Partial<TaxClassFormData> & { id?: string };
  onSave?: () => void;
  onCancel?: () => void;
  onDataChange?: () => void;
}

export function TaxClassForm({ 
  initialData, 
  onSave, 
  onCancel,
  onDataChange
}: TaxClassFormProps) {
  const { execute: executeDelete, isLoading: isDeleting } = useAction(deleteTaxClass);

  const getMappedValues = useCallback((data: any) => ({
    name: data?.name || "",
    percentage: data?.percentage !== undefined ? Number(data.percentage) : 0,
    is_active: (data?.isActive ?? data?.is_active ?? true).toString() as "true" | "false",
    description: data?.description || "",
  }), []);

  const mappedValues = useMemo(() => getMappedValues(initialData), [initialData, getMappedValues]);

  const { form, onSubmit, isPending, handleSubmit, reset } = useServerActionForm({
    schema: taxClassSchema,
    defaultValues: mappedValues,
    serverAction: async (data) => {
      if (initialData?.id) {
        return await updateTaxClass({ id: initialData.id, data });
      } else {
        return await createTaxClass(data);
      }
    },
    onSuccess: () => {
      toast.success(initialData?.id ? "Steuerklasse aktualisiert" : "Steuerklasse erstellt");
      onSave?.();
      onDataChange?.();
    },
  });

  // Sync form with initialData when it changes
  useEffect(() => {
    reset(mappedValues);
  }, [mappedValues, reset]);

  const handleDelete = async () => {
    if (!initialData?.id) return;

    if (confirm(`Möchten Sie die Steuerklasse "${initialData.name}" wirklich löschen?`)) {
      const result = await executeDelete({ id: initialData.id });
      if (result?.success) {
        toast.success("Steuerklasse gelöscht");
        onSave?.();
        onDataChange?.();
      }
    }
  };

  return (
    <EntityFormWrapper
      title={initialData?.id ? "Steuerklasse bearbeiten" : "Neue Steuerklasse"}
      description={
        initialData?.id 
          ? "Aktualisieren Sie die Informationen der Steuerklasse."
          : "Erstellen Sie eine neue Steuerklasse."
      }
    >
      <ServerActionForm
        form={form}
        isPending={isPending || isDeleting}
        onSubmit={onSubmit}
        handleSubmit={handleSubmit}
      >
        {taxClassConfig.formSections?.map((section, sectionIndex) => (
          <div key={sectionIndex} className="space-y-4">
            <h3 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">
              {section.title}
            </h3>
            
            <div className="grid grid-cols-1 gap-4">
              {section.fields.map((fieldKey) => {
                const field = taxClassConfig.fields[fieldKey];
                if (!field) return null;
                
                switch (field.key) {
                  case 'name':
                    return (
                      <TextField key={field.key} form={form} name="name" label={field.label} placeholder={field.placeholder} required={field.required} />
                    );
                  case 'percentage':
                    return (
                      <NumberField key={field.key} form={form} name="percentage" label={field.label} placeholder={field.placeholder} required={field.required} min={0} max={100} step={0.01} />
                    );
                   case 'is_active':
                    return (
                      <SelectField key={field.key} form={form} name="is_active" label={field.label} options={field.options || []} />
                    );
                  case 'description':
                    return (
                      <TextAreaField key={field.key} form={form} name="description" label={field.label} placeholder={field.placeholder} rows={3} />
                    );
                  default:
                    return null;
                }
              })}
            </div>
          </div>
        ))}

        <FormActions
          isPending={isPending}
          onCancel={onCancel}
          submitLabel={initialData?.id ? "Aktualisieren" : "Erstellen"}
          showDelete={!!initialData?.id}
          onDelete={handleDelete}
        />
      </ServerActionForm>
    </EntityFormWrapper>
  );
}
