"use client";

import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { FormField } from "@/components/ui/form-field";
import { Input } from "@/components/ui/input";
import { LocationPicker } from "@/features/orders/location-picker";
import { useT } from "@/i18n";
import { fieldErrorMap, friendlyErrorMessage } from "@/lib/errors";
import { queryKeys } from "@/lib/query-keys";
import { updatePortalWrapping } from "@/services/portal";
import type { PortalStore } from "@/types/portal";

const FIELDS = ["wrapping_name", "wrapping_address", "wrapping_lat", "wrapping_lng"] as const;

/** "33.5138" -> 33.5138; blank or not a number -> null. */
function toNumber(text: string): number | null {
  const trimmed = text.trim();
  if (trimmed === "") return null;
  const value = Number(trimmed);
  return Number.isFinite(value) ? value : null;
}

/**
 * Where this store's goods are wrapped before they are delivered.
 *
 * Set once here, not typed on every order: when an order needs wrapping, a captain collects the goods
 * from the supplier and leaves them at this place, and a second captain then collects the wrapped parcel
 * from here and delivers it. The place is copied onto an order when the order is created, so changing it
 * never moves orders already sent. Clearing it switches wrapping off.
 */
export function WrappingCard({ store }: { store: PortalStore }) {
  const t = useT();
  const queryClient = useQueryClient();
  const saved = store.wrapping;

  const [name, setName] = useState(saved?.name ?? "");
  const [address, setAddress] = useState(saved?.address ?? "");
  const [lat, setLat] = useState(saved?.lat != null ? String(saved.lat) : "");
  const [lng, setLng] = useState(saved?.lng != null ? String(saved.lng) : "");
  const [split, setSplit] = useState(saved?.split_collection ?? true);
  const [wrapAll, setWrapAll] = useState(saved?.wrap_all_orders ?? false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const dirty =
    name !== (saved?.name ?? "") ||
    address !== (saved?.address ?? "") ||
    lat !== (saved?.lat != null ? String(saved.lat) : "") ||
    lng !== (saved?.lng != null ? String(saved.lng) : "") ||
    split !== (saved?.split_collection ?? true) ||
    wrapAll !== (saved?.wrap_all_orders ?? false);

  const save = useMutation({
    mutationFn: () =>
      updatePortalWrapping({
        wrapping_name: name.trim() === "" ? null : name.trim(),
        wrapping_address: address.trim() === "" ? null : address.trim(),
        wrapping_lat: toNumber(lat),
        wrapping_lng: toNumber(lng),
        wrapping_split_collection: split,
        wrap_all_orders: wrapAll,
      }),
    onSuccess: () => {
      setErrors({});
      toast.success(t("portal.integration.wrappingSaved"));
      void queryClient.invalidateQueries({ queryKey: queryKeys.portal.settings });
    },
    onError: (failure) => {
      const fields = fieldErrorMap(failure, { only: [...FIELDS] });
      if (Object.keys(fields).length > 0) setErrors(fields);
      else toast.error(friendlyErrorMessage(failure, t));
    },
  });

  const touch = (setter: (value: string) => void, key: string) => (value: string) => {
    setter(value);
    setErrors((current) => ({ ...current, [key]: "" }));
  };

  return (
    <Card className="p-5 sm:p-6">
      <div className="flex items-start justify-between gap-3">
        <div>
          <h3 className="text-sm font-semibold text-foreground">{t("portal.integration.wrappingTitle")}</h3>
          <p className="mt-1 text-xs text-muted-foreground">{t("portal.integration.wrappingHint")}</p>
        </div>
        <Badge variant={saved?.configured ? "primary" : "outline"}>
          {saved?.configured ? t("portal.integration.wrappingOn") : t("portal.integration.wrappingOff")}
        </Badge>
      </div>

      <form
        onSubmit={(event) => {
          event.preventDefault();
          save.mutate();
        }}
        className="mt-4 space-y-3"
        noValidate
      >
        <FormField label={t("portal.integration.wrappingName")} htmlFor="wrapping_name" error={errors.wrapping_name || null}>
          <Input id="wrapping_name" value={name} onChange={(event) => touch(setName, "wrapping_name")(event.target.value)} />
        </FormField>
        <FormField label={t("portal.integration.wrappingAddress")} htmlFor="wrapping_address" error={errors.wrapping_address || null}>
          <Input id="wrapping_address" value={address} onChange={(event) => touch(setAddress, "wrapping_address")(event.target.value)} />
        </FormField>
        <LocationPicker
          lat={lat}
          lng={lng}
          title={t("portal.integration.wrappingTitle")}
          onChange={(nextLat, nextLng) => {
            touch(setLat, "wrapping_lat")(nextLat === null ? "" : String(nextLat));
            touch(setLng, "wrapping_lng")(nextLng === null ? "" : String(nextLng));
          }}
          fallback={
            <>
          <FormField label={t("portal.integration.wrappingLat")} htmlFor="wrapping_lat" error={errors.wrapping_lat || null}>
            <Input id="wrapping_lat" dir="ltr" inputMode="decimal" placeholder="33.5138" value={lat} onChange={(event) => touch(setLat, "wrapping_lat")(event.target.value)} />
          </FormField>
          <FormField label={t("portal.integration.wrappingLng")} htmlFor="wrapping_lng" error={errors.wrapping_lng || null}>
            <Input id="wrapping_lng" dir="ltr" inputMode="decimal" placeholder="36.2765" value={lng} onChange={(event) => touch(setLng, "wrapping_lng")(event.target.value)} />
          </FormField>
            </>
          }
        />
        {errors.wrapping_lat || errors.wrapping_lng ? <p className="text-xs text-destructive">{errors.wrapping_lat || errors.wrapping_lng}</p> : null}
        <div className="flex items-start gap-2">
          <Checkbox id="wrap_all_orders" checked={wrapAll} onCheckedChange={(value) => setWrapAll(value === true)} className="mt-0.5" />
          <label htmlFor="wrap_all_orders" className="text-sm">
            <span className="font-medium text-foreground">{t("portal.integration.wrapAllOrders")}</span>
            <span className="block text-xs text-muted-foreground">{t("portal.integration.wrapAllOrdersHint")}</span>
          </label>
        </div>
        <div className="flex items-start gap-2">
          <Checkbox id="wrapping_split_collection" checked={split} onCheckedChange={(value) => setSplit(value === true)} className="mt-0.5" />
          <label htmlFor="wrapping_split_collection" className="text-sm">
            <span className="font-medium text-foreground">{t("portal.integration.wrappingSplit")}</span>
            <span className="block text-xs text-muted-foreground">{t("portal.integration.wrappingSplitHint")}</span>
          </label>
        </div>
        <p className="text-xs text-muted-foreground">{t("portal.integration.wrappingClear")}</p>
        <Button type="submit" size="sm" loading={save.isPending} disabled={!dirty}>
          {t("common.save")}
        </Button>
      </form>
    </Card>
  );
}
