"use client";

import { useForm } from "@tanstack/react-form";
import { z } from "zod";
import { Textarea } from "@/components/ui/textarea";

interface ShellCommandFormProps {
  command: string;
  onCommandChange: (value: string) => void;
  disabled?: boolean;
}

export function ShellCommandForm({
  command,
  onCommandChange,
  disabled,
}: ShellCommandFormProps) {
  const form = useForm({
    defaultValues: { command },
    onSubmit: () => {},
  });

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        form.handleSubmit();
      }}
      className="space-y-5"
    >
      <form.Field
        name="command"
        validators={{
          onChange: ({ value }: { value: string }) => {
            const schema = z
              .string()
              .min(1, "Nhập command để thực thi")
              .max(500, "Command quá dài");
            const result = schema.safeParse(value);
            if (!result.success) {
              return result.error.issues.map((i) => i.message);
            }
            return [];
          },
        }}
        children={(field) => (
          <div className="w-full px-0">
            <Textarea
              className="w-full h-[25vh]"
              placeholder="Nhập lệnh..."
              value={field.state.value}
              onChange={(e) => {
                field.handleChange(e.target.value);
                onCommandChange(e.target.value);
              }}
              disabled={disabled}
            />
            {field.state.meta.errors?.length > 0 && (
              <p className="text-sm text-red-500">
                {String(field.state.meta.errors[0])}
              </p>
            )}
          </div>
        )}
      />
    </form>
  );
}
