"use client";

import { useState } from "react";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import type {
  InventoryCategory,
  InventoryItem,
  InventoryItemPayload,
  InventoryLocation,
  InventorySupplier,
} from "@/types/inventory";
import { centsToEuroInput, emptyItemPayload, euroToCents } from "./inventory-utils";

type Props = {
  open: boolean;
  item: InventoryItem | null;
  categories: InventoryCategory[];
  locations: InventoryLocation[];
  suppliers: InventorySupplier[];
  pending: boolean;
  serverError: string;
  onOpenChange: (open: boolean) => void;
  onSubmit: (payload: InventoryItemPayload) => void;
};

function payloadFromItem(item: InventoryItem | null): InventoryItemPayload {
  if (!item) {
    return emptyItemPayload;
  }
  return {
    sku: item.sku,
    name: item.name,
    description: item.description,
    category_id: item.category_id,
    manufacturer: item.manufacturer,
    manufacturer_part_number: item.manufacturer_part_number,
    supplier_id: item.supplier_id,
    supplier_part_number: item.supplier_part_number,
    compatible_devices: item.compatible_devices,
    location_id: item.location_id,
    quantity_on_hand: item.quantity_on_hand,
    quantity_reserved: item.quantity_reserved,
    reorder_level: item.reorder_level,
    unit: item.unit,
    purchase_price_cents: item.purchase_price_cents,
    selling_price_cents: item.selling_price_cents,
    currency: item.currency,
    tax_rate_percent: item.tax_rate_percent,
    notes: item.notes,
    is_active: item.is_active,
  };
}

export default function InventoryItemDialog({
  open,
  item,
  categories,
  locations,
  suppliers,
  pending,
  serverError,
  onOpenChange,
  onSubmit,
}: Props) {
  const initialPayload = payloadFromItem(item);
  const [payload, setPayload] = useState<InventoryItemPayload>(initialPayload);
  const [purchasePrice, setPurchasePrice] = useState(centsToEuroInput(initialPayload.purchase_price_cents));
  const [sellingPrice, setSellingPrice] = useState(centsToEuroInput(initialPayload.selling_price_cents));
  const [clientError, setClientError] = useState("");

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

  function submit() {
    const purchaseCents = euroToCents(purchasePrice);
    const sellingCents = euroToCents(sellingPrice);
    if (!payload.name.trim()) {
      setClientError("Bitte einen Artikelnamen angeben.");
      return;
    }
    if (payload.quantity_reserved > payload.quantity_on_hand) {
      setClientError("Reservierter Bestand darf den Lagerbestand nicht überschreiten.");
      return;
    }
    if ((purchasePrice.trim() && purchaseCents === null) || (sellingPrice.trim() && sellingCents === null)) {
      setClientError("Bitte Preise als Eurobetrag eingeben, z. B. 1,50.");
      return;
    }
    setClientError("");
    onSubmit({
      ...payload,
      sku: payload.sku?.trim() || null,
      name: payload.name.trim(),
      purchase_price_cents: purchaseCents,
      selling_price_cents: sellingCents,
      description: payload.description?.trim() || null,
      manufacturer: payload.manufacturer?.trim() || null,
      manufacturer_part_number: payload.manufacturer_part_number?.trim() || null,
      supplier_part_number: payload.supplier_part_number?.trim() || null,
      compatible_devices: payload.compatible_devices?.trim() || null,
      notes: payload.notes?.trim() || null,
    });
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-5xl">
        <DialogHeader>
          <DialogTitle>{item ? "Artikel bearbeiten" : "Artikel anlegen"}</DialogTitle>
          <DialogDescription>Pflege Stammdaten, Lagerbestand, Preise und Bezugsdaten.</DialogDescription>
        </DialogHeader>

        <div className="grid gap-5">
          <section className="grid gap-3">
            <h3 className="font-semibold text-slate-950">Stammdaten</h3>
            <div className="grid gap-3 md:grid-cols-3">
              <label className="grid gap-1 text-sm">SKU optional<Input value={payload.sku ?? ""} onChange={(event) => update("sku", event.target.value || null)} placeholder="ET-2026-000001" /></label>
              <label className="grid gap-1 text-sm md:col-span-2">Name<Input value={payload.name} onChange={(event) => update("name", event.target.value)} /></label>
              <label className="grid gap-1 text-sm md:col-span-3">Beschreibung<textarea className="min-h-20 rounded-lg border p-2 text-sm" value={payload.description ?? ""} onChange={(event) => update("description", event.target.value || null)} /></label>
            </div>
          </section>

          <section className="grid gap-3">
            <h3 className="font-semibold text-slate-950">Zuordnung</h3>
            <div className="grid gap-3 md:grid-cols-3">
              <label className="grid gap-1 text-sm">Kategorie<select className="h-8 rounded-lg border px-2 text-sm" value={payload.category_id ?? ""} onChange={(event) => update("category_id", event.target.value ? Number(event.target.value) : null)}>
                <option value="">Keine Kategorie</option>
                {categories.map((category) => <option key={category.id} value={category.id}>{category.name}</option>)}
              </select></label>
              <label className="grid gap-1 text-sm">Lagerort<select className="h-8 rounded-lg border px-2 text-sm" value={payload.location_id ?? ""} onChange={(event) => update("location_id", event.target.value ? Number(event.target.value) : null)}>
                <option value="">Kein Lagerort</option>
                {locations.map((location) => <option key={location.id} value={location.id}>{location.name}</option>)}
              </select></label>
              <label className="grid gap-1 text-sm">Lieferant<select className="h-8 rounded-lg border px-2 text-sm" value={payload.supplier_id ?? ""} onChange={(event) => update("supplier_id", event.target.value ? Number(event.target.value) : null)}>
                <option value="">Kein Lieferant</option>
                {suppliers.map((supplier) => <option key={supplier.id} value={supplier.id}>{supplier.name}</option>)}
              </select></label>
            </div>
          </section>

          <section className="grid gap-3">
            <h3 className="font-semibold text-slate-950">Hersteller und Kompatibilität</h3>
            <div className="grid gap-3 md:grid-cols-3">
              <label className="grid gap-1 text-sm">Hersteller<Input value={payload.manufacturer ?? ""} onChange={(event) => update("manufacturer", event.target.value || null)} /></label>
              <label className="grid gap-1 text-sm">Hersteller-Teilenummer<Input value={payload.manufacturer_part_number ?? ""} onChange={(event) => update("manufacturer_part_number", event.target.value || null)} /></label>
              <label className="grid gap-1 text-sm">Lieferanten-Teilenummer<Input value={payload.supplier_part_number ?? ""} onChange={(event) => update("supplier_part_number", event.target.value || null)} /></label>
              <label className="grid gap-1 text-sm md:col-span-3">Kompatible Geräte<textarea className="min-h-20 rounded-lg border p-2 text-sm" value={payload.compatible_devices ?? ""} onChange={(event) => update("compatible_devices", event.target.value || null)} /></label>
            </div>
          </section>

          <section className="grid gap-3">
            <h3 className="font-semibold text-slate-950">Bestand und Preise</h3>
            <div className="grid gap-3 md:grid-cols-4">
              <label className="grid gap-1 text-sm">Bestand<Input type="number" min={0} value={payload.quantity_on_hand} onChange={(event) => update("quantity_on_hand", Number(event.target.value))} /></label>
              <label className="grid gap-1 text-sm">Reserviert<Input type="number" min={0} value={payload.quantity_reserved} onChange={(event) => update("quantity_reserved", Number(event.target.value))} /></label>
              <label className="grid gap-1 text-sm">Mindestbestand<Input type="number" min={0} value={payload.reorder_level} onChange={(event) => update("reorder_level", Number(event.target.value))} /></label>
              <label className="grid gap-1 text-sm">Einheit<Input value={payload.unit} onChange={(event) => update("unit", event.target.value)} /></label>
              <label className="grid gap-1 text-sm">Einkaufspreis €<Input inputMode="decimal" value={purchasePrice} onChange={(event) => setPurchasePrice(event.target.value)} /></label>
              <label className="grid gap-1 text-sm">Verkaufspreis €<Input inputMode="decimal" value={sellingPrice} onChange={(event) => setSellingPrice(event.target.value)} /></label>
              <label className="grid gap-1 text-sm">Währung<Input value={payload.currency} onChange={(event) => update("currency", event.target.value.toUpperCase())} /></label>
              <label className="grid gap-1 text-sm">MwSt. %<Input inputMode="decimal" value={payload.tax_rate_percent} onChange={(event) => update("tax_rate_percent", event.target.value.replace(",", "."))} /></label>
            </div>
          </section>

          <section className="grid gap-3">
            <h3 className="font-semibold text-slate-950">Notizen</h3>
            <textarea className="min-h-20 rounded-lg border p-2 text-sm" value={payload.notes ?? ""} onChange={(event) => update("notes", event.target.value || null)} />
            <label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={payload.is_active} onChange={(event) => update("is_active", event.target.checked)} /> Artikel ist aktiv</label>
          </section>
        </div>

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

        <DialogFooter>
          <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={pending}>Abbrechen</Button>
          <Button type="button" onClick={submit} disabled={pending}>{pending ? "Speichert..." : "Speichern"}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
