"use client";

import React, { useEffect, useMemo, useCallback } from "react";
import { MapPin } from "lucide-react";
import { 
  EntityFormWrapper,
  ServerActionForm,
  FormActions,
  TextField,
  EmailField,
  SelectField,
  useServerActionForm
} from "../../dashboard/entity-detail/shared";
import { customerConfig, customerSchema } from "../../dashboard/entity-detail/entities/customer/CustomerConfig";
import { useAction } from "@/hooks/useAction";
import { createCustomer, updateCustomer, deleteCustomer } from "@/actions/customers";
import type { z } from "zod";
import { toast } from "sonner";

type CustomerFormData = z.infer<typeof customerSchema>;

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

export function CustomerForm({ 
  initialData, 
  onSave, 
  onCancel,
  onDataChange
}: CustomerFormProps) {
  const { execute: executeDelete, isLoading: isDeleting } = useAction(deleteCustomer);

  const getMappedValues = useCallback((data: any) => ({
    salutation: data?.salutation || "herr",
    first_name: data?.first_name || data?.firstName || "",
    last_name: data?.last_name || data?.lastName || "",
    company: data?.company || "",
    customer_number: data?.customer_number || data?.customerNumber || "",
    email: data?.email || "",
    phone_number: data?.phone_number || data?.phoneNumber || "",
    mobile_phone: data?.mobile_phone || data?.mobilePhone || "",
    is_active: (data?.isActive ?? data?.is_active ?? true).toString() as "true" | "false",
    address: (data?.address && typeof data.address === 'object') ? data.address : {
      street: typeof data?.address === 'string' ? data.address : "",
      city: "",
      postal_code: "",
      country: "Deutschland"
    },
  }), []);

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

  const { form, onSubmit, isPending, handleSubmit, reset } = useServerActionForm({
    schema: customerSchema,
    defaultValues: mappedValues,
    serverAction: async (data) => {
      const name = data.company || `${data.first_name} ${data.last_name}`.trim();
      const addressString = data.address ? `${data.address.street}, ${data.address.postal_code} ${data.address.city}, ${data.address.country}` : "";
      
      const actionData = {
        name,
        email: data.email || "",
        phone_number: data.phone_number || null,
        address: addressString || null,
      };

      if (initialData?.id) {
        return await updateCustomer({ id: initialData.id, data: actionData });
      } else {
        return await createCustomer(actionData);
      }
    },
    onSuccess: () => {
      toast.success(initialData?.id ? "Kunde aktualisiert" : "Kunde erstellt");
      onSave?.();
      onDataChange?.();
    },
  });

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

  const handleDelete = async () => {
    if (!initialData?.id) return;
    
    const customerName = initialData.company || `${initialData.first_name || ""} ${initialData.last_name || ""}`.trim() || initialData.email;
    if (confirm(`Möchten Sie den Kunden "${customerName}" wirklich löschen?`)) {
      const result = await executeDelete({ id: initialData.id });
      if (result?.success) {
        toast.success("Kunde gelöscht");
        onSave?.();
        onDataChange?.();
      }
    }
  };

  const getAddressString = () => {
    const address = form.watch('address');
    if (!address) return "";
    const parts = [address.street, address.city, address.postal_code, address.country].filter(Boolean);
    return parts.join(", ");
  };

  return (
    <EntityFormWrapper
      title={initialData?.id ? "Kunde bearbeiten" : "Neuer Kunde"}
      description={initialData?.id ? "Aktualisieren Sie die Informationen des Kunden." : "Erstellen Sie einen neuen Kunden."}
    >
      <ServerActionForm
        form={form}
        isPending={isPending || isDeleting}
        onSubmit={onSubmit}
        handleSubmit={handleSubmit}
      >
        {customerConfig.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 md:grid-cols-2 gap-4">
              {section.fields.map((fieldKey) => {
                const field = customerConfig.fields[fieldKey];
                if (!field) return null;
                
                switch (field.key) {
                  case 'salutation':
                    return (
                      <SelectField key={field.key} form={form} name="salutation" label={field.label} options={field.options || []} />
                    );
                  case 'first_name':
                  case 'last_name':
                  case 'company':
                  case 'customer_number':
                  case 'phone_number':
                  case 'mobile_phone':
                    return (
                      <TextField key={field.key} form={form} name={field.key} label={field.label} placeholder={field.placeholder} required={field.required} />
                    );
                  case 'email':
                    return (
                      <EmailField key={field.key} form={form} name="email" label={field.label} placeholder={field.placeholder} required={field.required} />
                    );
                  case 'address.street':
                  case 'address.city':
                  case 'address.postal_code':
                  case 'address.country':
                    return (
                      <TextField key={field.key} form={form} name={field.key} label={field.label} placeholder={field.placeholder} required={field.required} />
                    );
                  case 'is_active':
                    return (
                      <SelectField key={field.key} form={form} name="is_active" label={field.label} options={field.options || []} />
                    );
                  default:
                    return null;
                }
              })}
            </div>
            {section.title === 'Adresse' && getAddressString() && (
              <button
                type="button"
                onClick={() => window.open(`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(getAddressString())}`, '_blank')}
                className="text-xs text-primary hover:text-primary/80 flex items-center gap-1"
              >
                <MapPin className="h-3 w-3" /> Auf Google Maps anzeigen
              </button>
            )}
          </div>
        ))}

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