"use client";

import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Clock } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useI18n, useT } from "@/i18n";
import { friendlyErrorMessage } from "@/lib/errors";
import { formatDateTime } from "@/lib/format";
import { queryKeys } from "@/lib/query-keys";
import { setPickupReadyAt } from "@/services/orders";

/** An ISO instant as the `YYYY-MM-DDTHH:mm` a datetime-local input wants, in the browser's own time zone. */
function toLocalInput(iso: string | null): string {
  if (!iso) return "";
  const date = new Date(iso);
  const pad = (n: number) => String(n).padStart(2, "0");

  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
}

/**
 * When a supplier will really have the goods ready.
 *
 * A supplier that is not ready is neither a failure nor something to wait out in silence. After ringing them, the office says when: the captain
 * reads the new time on their order and the supplier-delay alert counts from it. Offered only while the stop can still change.
 */
export function ReadyTime({
  orderUuid,
  deliveryUuid,
  stopUuid,
  readyAt,
  editable,
}: {
  /** The order the stop belongs to: the collection for a wrapped order, the order itself otherwise. */
  orderUuid: string;
  /** The customer's order whose page this is, so it refreshes. */
  deliveryUuid: string;
  stopUuid: string;
  readyAt: string | null;
  editable: boolean;
}) {
  const t = useT();
  const { locale } = useI18n();
  const queryClient = useQueryClient();
  const [editing, setEditing] = useState(false);
  const [value, setValue] = useState(toLocalInput(readyAt));

  const save = useMutation({
    mutationFn: () => setPickupReadyAt(orderUuid, stopUuid, new Date(value).toISOString()),
    onSuccess: (response) => {
      toast.success(response.Message ?? t("orders.ready.saved"));
      setEditing(false);
      void queryClient.invalidateQueries({ queryKey: queryKeys.orders.detail(deliveryUuid) });
      void queryClient.invalidateQueries({ queryKey: ["orders"] });
    },
    onError: (error) => toast.error(friendlyErrorMessage(error, t)),
  });

  if (!readyAt && !editable) {
    return null;
  }

  return (
    <div className="mt-2 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
      <Clock className="h-3.5 w-3.5" aria-hidden />
      {editing ? (
        <>
          <Input
            type="datetime-local"
            value={value}
            onChange={(event) => setValue(event.target.value)}
            className="h-8 w-auto text-xs"
            aria-label={t("orders.ready.label")}
          />
          <Button type="button" size="sm" loading={save.isPending} disabled={save.isPending || value === ""} onClick={() => save.mutate()}>
            {save.isPending ? t("common.saving") : t("common.save")}
          </Button>
          <Button type="button" size="sm" variant="ghost" onClick={() => setEditing(false)}>
            {t("common.cancel")}
          </Button>
        </>
      ) : (
        <>
          <span>{readyAt ? t("orders.ready.at", { at: formatDateTime(readyAt, locale) }) : t("orders.ready.none")}</span>
          {editable ? (
            <Button type="button" size="sm" variant="ghost" className="h-6 px-2 text-xs" onClick={() => { setValue(toLocalInput(readyAt)); setEditing(true); }}>
              {t("orders.ready.change")}
            </Button>
          ) : null}
        </>
      )}
    </div>
  );
}
