'use client';

import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { api } from '@/lib/api';

interface ParcelPreset {
  id: string;
  name: string;
  weight_oz: number;
  length_in: number;
  width_in: number;
  height_in: number;
  is_default: boolean;
}

interface Form {
  name: string;
  weight_oz: string;
  length_in: string;
  width_in: string;
  height_in: string;
  is_default: boolean;
}

function emptyForm(): Form {
  return { name: '', weight_oz: '', length_in: '', width_in: '', height_in: '', is_default: false };
}

function fromPreset(p: ParcelPreset): Form {
  return {
    name: p.name,
    weight_oz: String(p.weight_oz),
    length_in: String(p.length_in),
    width_in: String(p.width_in),
    height_in: String(p.height_in),
    is_default: p.is_default,
  };
}

function toPayload(f: Form) {
  return {
    name: f.name,
    weight_oz: Number(f.weight_oz),
    length_in: Number(f.length_in),
    width_in: Number(f.width_in),
    height_in: Number(f.height_in),
    is_default: f.is_default,
  };
}

export function ParcelPresetFormDialog({
  storeId,
  preset,
  trigger,
}: {
  storeId: string;
  preset?: ParcelPreset;
  trigger: React.ReactNode;
}) {
  const qc = useQueryClient();
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState<Form>(preset ? fromPreset(preset) : emptyForm());

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect -- resyncing local form state when the dialog target changes
    setForm(preset ? fromPreset(preset) : emptyForm());
  }, [preset, open]);

  const mut = useMutation({
    mutationFn: () =>
      preset
        ? api.stores.parcelPresets.update(storeId, preset.id, toPayload(form))
        : api.stores.parcelPresets.create(storeId, toPayload(form)),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['parcel-presets', storeId] });
      setOpen(false);
    },
  });

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>{trigger}</DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{preset ? 'Edit preset' : 'New parcel preset'}</DialogTitle>
        </DialogHeader>
        <div className="space-y-3">
          <Field label="Name">
            <input
              value={form.name}
              onChange={(e) => setForm({ ...form, name: e.target.value })}
              className={cls}
            />
          </Field>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Weight (oz)"><NumberInput val={form.weight_oz} onVal={(v) => setForm({ ...form, weight_oz: v })} /></Field>
            <Field label="Length (in)"><NumberInput val={form.length_in} onVal={(v) => setForm({ ...form, length_in: v })} /></Field>
            <Field label="Width (in)"><NumberInput val={form.width_in} onVal={(v) => setForm({ ...form, width_in: v })} /></Field>
            <Field label="Height (in)"><NumberInput val={form.height_in} onVal={(v) => setForm({ ...form, height_in: v })} /></Field>
          </div>
          <label className="flex items-center gap-2 text-sm">
            <input
              type="checkbox"
              checked={form.is_default}
              onChange={(e) => setForm({ ...form, is_default: e.target.checked })}
            />
            Set as default preset
          </label>
          {mut.isError && <p className="text-sm text-terracotta">Failed to save. Check values and try again.</p>}
        </div>
        <DialogFooter>
          <button onClick={() => setOpen(false)} className="rounded px-3 py-1.5 text-sm text-ink/70 hover:bg-bone">
            Cancel
          </button>
          <button
            onClick={() => mut.mutate()}
            disabled={mut.isPending || !form.name.trim()}
            className="rounded bg-forest px-3 py-1.5 text-sm font-semibold text-white hover:bg-forest/90 disabled:opacity-50"
          >
            {mut.isPending ? 'Saving…' : 'Save'}
          </button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

const cls = 'w-full rounded border border-forest/20 bg-white px-2 py-1.5 text-sm';

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <label className="flex flex-col gap-1 text-sm">
      <span className="text-xs uppercase tracking-wide text-ink/60">{label}</span>
      {children}
    </label>
  );
}

function NumberInput({ val, onVal }: { val: string; onVal: (v: string) => void }) {
  return (
    <input
      inputMode="decimal"
      value={val}
      onChange={(e) => onVal(e.target.value.replace(/[^0-9.]/g, ''))}
      className={cls}
    />
  );
}
