"use client";

import { useMemo, useState } from "react";
import type { FormEvent } from "react";

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import type { Customer, CustomerPayload, CustomerStatus, CustomerType } from "@/types/customer";

const customerTypes: Array<{ value: CustomerType; label: string }> = [
  { value: "company", label: "Unternehmen" },
  { value: "private", label: "Privat" },
  { value: "public_sector", label: "Öffentlicher Sektor" },
  { value: "partner", label: "Partner" },
  { value: "supplier", label: "Lieferant" },
];

const statuses: Array<{ value: CustomerStatus; label: string }> = [
  { value: "lead", label: "Lead" },
  { value: "active", label: "Aktiv" },
  { value: "inactive", label: "Inaktiv" },
  { value: "blocked", label: "Gesperrt" },
  { value: "archived", label: "Archiviert" },
];

const emptyCustomer: CustomerPayload = {
  customer_number: "",
  company_name: "",
  legal_name: "",
  customer_type: "company",
  status: "lead",
  industry: "",
  website: "",
  email: "",
  phone: "",
  tax_number: "",
  vat_id: "",
  notes: "",
  addresses: [
    {
      type: "primary",
      street: "",
      postal_code: "",
      city: "",
      state: "",
      country: "Deutschland",
      is_primary: true,
    },
  ],
};

type Props = {
  open: boolean;
  customer?: Customer | null;
  pending?: boolean;
  serverError?: string;
  onOpenChange: (open: boolean) => void;
  onSubmit: (payload: CustomerPayload) => Promise<void>;
};

export default function CustomerFormDialog({
  open,
  customer,
  pending = false,
  serverError,
  onOpenChange,
  onSubmit,
}: Props) {
  const initialForm = customer
    ? {
        customer_number: customer.customer_number,
        company_name: customer.company_name,
        legal_name: customer.legal_name,
        customer_type: customer.customer_type,
        status: customer.status,
        industry: customer.industry,
        website: customer.website,
        email: customer.email,
        phone: customer.phone,
        tax_number: customer.tax_number,
        vat_id: customer.vat_id,
        notes: customer.notes,
        addresses: customer.addresses.length > 0
          ? customer.addresses.map((address) => ({
              type: address.type,
              street: address.street,
              postal_code: address.postal_code,
              city: address.city,
              state: address.state,
              country: address.country,
              is_primary: address.is_primary,
            }))
          : emptyCustomer.addresses,
      }
    : emptyCustomer;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-3xl">
        {open && (
          <CustomerForm
            key={customer?.id ?? "new"}
            initialForm={initialForm}
            pending={pending}
            serverError={serverError}
            onCancel={() => onOpenChange(false)}
            onSubmit={onSubmit}
          />
        )}
      </DialogContent>
    </Dialog>
  );
}

function CustomerForm({
  initialForm,
  pending,
  serverError,
  onCancel,
  onSubmit,
}: {
  initialForm: CustomerPayload;
  pending: boolean;
  serverError?: string;
  onCancel: () => void;
  onSubmit: (payload: CustomerPayload) => Promise<void>;
}) {
  const [form, setForm] = useState<CustomerPayload>(initialForm);

  const errors = useMemo(() => ({
    customer_number: form.customer_number.trim() ? "" : "Kundennummer erforderlich",
    company_name: form.company_name.trim() ? "" : "Firmenname erforderlich",
    email: !form.email || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)
      ? ""
      : "Gültige E-Mail erforderlich",
  }), [form.company_name, form.customer_number, form.email]);

  const valid = Object.values(errors).every((error) => !error);

  function update<K extends keyof CustomerPayload>(key: K, value: CustomerPayload[K]) {
    setForm((current) => ({ ...current, [key]: value }));
  }

  function updateAddress(index: number, key: keyof CustomerPayload["addresses"][number], value: string | boolean) {
    setForm((current) => ({
      ...current,
      addresses: current.addresses.map((address, itemIndex) => (
        itemIndex === index
          ? { ...address, [key]: value }
          : key === "is_primary" && value === true
            ? { ...address, is_primary: false }
            : address
      )),
    }));
  }

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (!valid) {
      return;
    }

    await onSubmit({
      ...form,
      website: form.website?.trim() || null,
      email: form.email?.trim() || null,
      addresses: form.addresses.map((address, index) => ({
        ...address,
        is_primary: address.is_primary || index === 0,
      })),
    });
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-5">
      <DialogHeader>
        <DialogTitle>Kunde {initialForm.customer_number ? "bearbeiten" : "erstellen"}</DialogTitle>
        <DialogDescription>
          Stammdaten und primäre Adresse des Kunden verwalten.
        </DialogDescription>
      </DialogHeader>

      <div className="grid gap-4 sm:grid-cols-2">
        <Field label="Kundennummer" error={errors.customer_number}>
          <Input value={form.customer_number} onChange={(event) => update("customer_number", event.target.value)} />
        </Field>
        <Field label="Firmenname" error={errors.company_name}>
          <Input value={form.company_name} onChange={(event) => update("company_name", event.target.value)} />
        </Field>
        <Field label="Rechtlicher Name">
          <Input value={form.legal_name} onChange={(event) => update("legal_name", event.target.value)} />
        </Field>
        <Field label="Branche">
          <Input value={form.industry} onChange={(event) => update("industry", event.target.value)} />
        </Field>
        <Field label="Typ">
          <select value={form.customer_type} onChange={(event) => update("customer_type", event.target.value as CustomerType)} className="h-8 w-full rounded-lg border border-input bg-transparent px-2.5 text-sm">
            {customerTypes.map((type) => <option key={type.value} value={type.value}>{type.label}</option>)}
          </select>
        </Field>
        <Field label="Status">
          <select value={form.status} onChange={(event) => update("status", event.target.value as CustomerStatus)} className="h-8 w-full rounded-lg border border-input bg-transparent px-2.5 text-sm">
            {statuses.map((status) => <option key={status.value} value={status.value}>{status.label}</option>)}
          </select>
        </Field>
        <Field label="E-Mail" error={errors.email}>
          <Input type="email" value={form.email ?? ""} onChange={(event) => update("email", event.target.value)} />
        </Field>
        <Field label="Telefon">
          <Input value={form.phone} onChange={(event) => update("phone", event.target.value)} />
        </Field>
        <Field label="Website">
          <Input value={form.website ?? ""} onChange={(event) => update("website", event.target.value)} />
        </Field>
        <Field label="USt-ID">
          <Input value={form.vat_id} onChange={(event) => update("vat_id", event.target.value)} />
        </Field>
      </div>

      <div className="rounded-lg border p-4">
        <h3 className="mb-4 text-sm font-semibold">Primäradresse</h3>
        {form.addresses.slice(0, 1).map((address, index) => (
          <div key={index} className="grid gap-4 sm:grid-cols-2">
            <Field label="Straße">
              <Input value={address.street} onChange={(event) => updateAddress(index, "street", event.target.value)} />
            </Field>
            <Field label="PLZ">
              <Input value={address.postal_code} onChange={(event) => updateAddress(index, "postal_code", event.target.value)} />
            </Field>
            <Field label="Ort">
              <Input value={address.city} onChange={(event) => updateAddress(index, "city", event.target.value)} />
            </Field>
            <Field label="Land">
              <Input value={address.country} onChange={(event) => updateAddress(index, "country", event.target.value)} />
            </Field>
          </div>
        ))}
      </div>

      <Field label="Notizen">
        <Input value={form.notes} onChange={(event) => update("notes", event.target.value)} />
      </Field>

      {serverError && <p className="text-sm text-red-600">{serverError}</p>}

      <DialogFooter>
        <Button type="button" variant="outline" disabled={pending} onClick={onCancel}>
          Abbrechen
        </Button>
        <Button type="submit" disabled={!valid || pending}>
          {pending ? "Speichern..." : "Speichern"}
        </Button>
      </DialogFooter>
    </form>
  );
}

function Field({
  label,
  error,
  children,
}: {
  label: string;
  error?: string;
  children: React.ReactNode;
}) {
  return (
    <div className="space-y-1.5">
      <Label>{label}</Label>
      {children}
      {error && <p className="text-xs text-red-600">{error}</p>}
    </div>
  );
}
