import { useState } from "react";
import { Group, TextInput, Text } from "@mantine/core";
import { useMutation } from "@tanstack/react-query";
import { api } from "@/services/api";

interface ContainerNumberInputProps {
  value: string | null;
  itemId: string;
  scheduleId: string;
  disabled: boolean;
}

export const ContainerNumberInput = ({
  value,
  itemId,
  scheduleId,
  disabled,
}: ContainerNumberInputProps) => {
  const [isEditing, setIsEditing] = useState(false);
  const [inputValue, setInputValue] = useState(value ?? "");
  const [error, setError] = useState<string | null>(null);

  const updateMutation = useMutation(
    api.trainScheduling.updateContainerItem.mutationOptions(),
  );
  const isLoading = updateMutation.isPending;

  const handleSave = async () => {
    try {
      setError(null);
      await updateMutation.mutateAsync({
        scheduleId,
        itemId,
        containerNumber: inputValue || null,
      });
      setIsEditing(false);
    } catch (err) {
      setError("Failed to save");
      setInputValue(value ?? "");
    }
  };

  const handleBlur = () => {
    if (inputValue !== value) {
      handleSave();
    } else {
      setIsEditing(false);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter") {
      handleSave();
    } else if (e.key === "Escape") {
      setInputValue(value ?? "");
      setIsEditing(false);
    }
  };

  if (disabled) {
    return <Text size="sm">{value || "TBD"}</Text>;
  }

  if (isEditing) {
    return (
      <Group gap={4}>
        <TextInput
          size="xs"
          value={inputValue}
          onChange={(e) => setInputValue(e.currentTarget.value)}
          onBlur={handleBlur}
          onKeyDown={handleKeyDown}
          autoFocus
          disabled={isLoading}
          placeholder="Container #"
          style={{ flex: 1 }}
        />
        {error && <Text size="xs" c="red">{error}</Text>}
      </Group>
    );
  }

  return (
    <Text
      size="sm"
      onClick={() => setIsEditing(true)}
      style={{ cursor: "pointer", textDecoration: "underline" }}
      title="Click to edit"
    >
      {value || "TBD"}
    </Text>
  );
};
