import { useState } from "react";
import { Group } from "@mantine/core";
import { DateInput } from "@mantine/dates";

/** `YYYY-MM-DD` in local time — the API column is a DATE, so no UTC shift. */
export function toIsoDate(value: Date | null): string | null {
  if (!value) return null;
  const tz = value.getTimezoneOffset() * 60000;
  return new Date(value.getTime() - tz).toISOString().slice(0, 10);
}

export interface DoCollectionDates {
  vesselArrival: Date | null;
  doCollected: Date | null;
}

/** Both dates present and the DO not collected before the vessel docked. */
export function doDatesComplete(dates: DoCollectionDates): boolean {
  if (!dates.vesselArrival || !dates.doCollected) return false;
  return (toIsoDate(dates.doCollected) ?? "") >= (toIsoDate(dates.vesselArrival) ?? "");
}

/**
 * The two mandatory dates Djibouti GL records with a Delivery Order. Shared by
 * the DO upload modal and the inline DO step so neither surface can post an
 * upload the API will reject.
 */
export function DoCollectionDateFields({
  value,
  onChange,
}: {
  value: DoCollectionDates;
  onChange: (next: DoCollectionDates) => void;
}) {
  // Only complain once the user has actually entered the earlier date.
  const outOfOrder =
    Boolean(value.vesselArrival && value.doCollected) && !doDatesComplete(value);

  return (
    <Group grow align="flex-start" gap="sm" wrap="wrap">
      <DateInput
        label="Vessel arrival date"
        placeholder="Select date"
        value={value.vesselArrival}
        onChange={(v) =>
          onChange({ ...value, vesselArrival: v ? new Date(v) : null })
        }
        maxDate={new Date()}
        size="sm"
        required
        withAsterisk
      />
      <DateInput
        label="DO collected date"
        placeholder="Select date"
        value={value.doCollected}
        onChange={(v) =>
          onChange({ ...value, doCollected: v ? new Date(v) : null })
        }
        minDate={value.vesselArrival ?? undefined}
        maxDate={new Date()}
        size="sm"
        required
        withAsterisk
        error={outOfOrder ? "Cannot be before the vessel arrival date." : undefined}
      />
    </Group>
  );
}

/** Local state helper — both surfaces need the same seed-from-server logic. */
export function useDoCollectionDates(seed?: {
  vesselArrivalDate?: string | null;
  doCollectedDate?: string | null;
}) {
  return useState<DoCollectionDates>(() => ({
    vesselArrival: seed?.vesselArrivalDate ? new Date(seed.vesselArrivalDate) : null,
    doCollected: seed?.doCollectedDate ? new Date(seed.doCollectedDate) : null,
  }));
}
