import { Autocomplete, Button, Group, Select, Stack, TagsInput, Textarea } from "@mantine/core";
import { FormEvent, KeyboardEvent, useState } from "react";
import type { User } from "../types";

// CardForm: Solicitante (Autocomplete) intencionadamente NO hace submit en Enter.
// Enter dentro del Autocomplete deja que Mantine seleccione el item resaltado del
// dropdown sin cerrar el formulario. Submit solo via boton "Crear" o Ctrl+Enter
// en descripcion. Ver issue 0088.

export interface CardFormValues {
  requester: string;
  title: string;
  description: string;
  assignee_id: string | null;
  tags: string[];
}

interface Props {
  initial?: Partial<CardFormValues>;
  submitLabel?: string;
  users?: User[];
  requesterOptions?: string[];
  tagOptions?: string[];
  onSubmit: (v: CardFormValues) => Promise<void> | void;
  onCancel: () => void;
}

export function CardForm({
  initial,
  submitLabel = "Guardar",
  users = [],
  requesterOptions = [],
  tagOptions = [],
  onSubmit,
  onCancel,
}: Props) {
  const [requester, setRequester] = useState(initial?.requester ?? "");
  const [title, setTitle] = useState(initial?.title ?? "");
  const [description, setDescription] = useState(initial?.description ?? "");
  const [assigneeId, setAssigneeId] = useState<string | null>(initial?.assignee_id ?? null);
  const [tags, setTags] = useState<string[]>(initial?.tags ?? []);

  const submit = async (e?: FormEvent) => {
    e?.preventDefault();
    const t = title.trim();
    if (!t) return;
    await onSubmit({
      requester: requester.trim(),
      title: t,
      description,
      assignee_id: assigneeId,
      tags,
    });
  };

  const textareaEnter = (e: KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
      e.preventDefault();
      submit();
    }
  };

  return (
    <form onSubmit={submit}>
      <Stack gap="sm">
        <Textarea
          label="Tarea"
          value={title}
          onChange={(e) => setTitle(e.currentTarget.value)}
          tabIndex={1}
          required
          autoComplete="off"
          data-autofocus
          autosize
          minRows={1}
          maxRows={4}
          onKeyDown={(e) => {
            if (e.key === "Enter" && !e.shiftKey) {
              e.preventDefault();
              submit();
            }
          }}
        />
        <Autocomplete
          label="Solicitante"
          value={requester}
          onChange={setRequester}
          data={requesterOptions}
          tabIndex={2}
          autoComplete="off"
          data-field="requester"
          placeholder="Empieza a escribir y elige uno existente"
          limit={10}
          onKeyDown={(e) => {
            if (e.key === "Enter") e.preventDefault();
          }}
        />
        <Textarea
          label="Descripcion"
          value={description}
          onChange={(e) => setDescription(e.currentTarget.value)}
          tabIndex={3}
          autosize
          minRows={3}
          maxRows={8}
          onKeyDown={textareaEnter}
          description="Ctrl+Enter para guardar"
        />
        <Select
          label="Asignar a"
          placeholder="Sin asignar"
          value={assigneeId}
          onChange={(v) => setAssigneeId(v)}
          data={users.map((u) => ({
            value: u.id,
            label: u.display_name || u.username,
          }))}
          clearable
          searchable
          tabIndex={4}
        />
        <TagsInput
          label="Tags"
          value={tags}
          onChange={setTags}
          data={tagOptions}
          clearable
          tabIndex={5}
          placeholder="Enter para añadir; sugiere existentes"
          splitChars={[",", " "]}
        />
        <Group justify="flex-end" gap="xs" mt="xs">
          <Button variant="subtle" color="gray" tabIndex={7} type="button" onClick={onCancel}>
            Cancelar
          </Button>
          <Button tabIndex={6} type="submit" disabled={!title.trim()}>
            {submitLabel}
          </Button>
        </Group>
      </Stack>
    </form>
  );
}
