import { zodResolver } from "@hookform/resolvers/zod";
import { Button, Field, Form, Input, useNavigate } from "@tailor-platform/app-shell";
import { Plus, X } from "lucide-react";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { useMutation } from "urql";
import { z } from "zod";
import { graphql } from "@/graphql";
import { useToast } from "@/hooks/use-toast";

const CreateAttributeMutation = graphql(`
  mutation CreateAttribute($code: String!, $name: String!, $valueLabels: [String!]) {
    createAttribute(code: $code, name: $name, valueLabels: $valueLabels) {
      id
      code
      name
    }
  }
`);

const formSchema = z.object({
  code: z.string().min(1, "Code is required"),
  name: z.string().min(1, "Name is required"),
});

type FormValues = z.infer<typeof formSchema>;

export const CreateAttributeForm = () => {
  const navigate = useNavigate();
  const toast = useToast();
  const [, createAttribute] = useMutation(CreateAttributeMutation);
  const [submitting, setSubmitting] = useState(false);
  const [valueTags, setValueTags] = useState<{ id: string; label: string }[]>([]);
  const [newLabelInput, setNewLabelInput] = useState("");

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: { code: "", name: "" },
  });

  const addLabel = () => {
    const label = newLabelInput.trim();
    if (!label) return;
    setValueTags((prev) => [...prev, { id: crypto.randomUUID(), label }]);
    setNewLabelInput("");
  };

  const removeLabel = (id: string) => {
    setValueTags((prev) => prev.filter((t) => t.id !== id));
  };

  const onSubmit = async (values: FormValues) => {
    setSubmitting(true);
    const result = await createAttribute(
      { ...values, valueLabels: valueTags.length > 0 ? valueTags.map((t) => t.label) : undefined },
      { additionalTypenames: ["ProductAttribute"] },
    );
    setSubmitting(false);

    if (result.error) {
      toast.error(result.error);
      return;
    }

    toast.success("Attribute created successfully");
    void navigate("..");
  };

  const onCancel = () => void navigate("..");

  return (
    <Form
      noValidate
      onSubmit={(e) => void form.handleSubmit(onSubmit)(e)}
      className="max-w-md space-y-4"
    >
      <Controller
        control={form.control}
        name="code"
        render={({ field, fieldState }) => (
          <Field.Root name={field.name} invalid={fieldState.invalid}>
            <Field.Label>Code</Field.Label>
            <Field.Control placeholder="Enter attribute code" {...field} />
            {fieldState.error && <Field.Error match>{fieldState.error.message}</Field.Error>}
          </Field.Root>
        )}
      />
      <Controller
        control={form.control}
        name="name"
        render={({ field, fieldState }) => (
          <Field.Root name={field.name} invalid={fieldState.invalid}>
            <Field.Label>Name</Field.Label>
            <Field.Control placeholder="Enter attribute name" {...field} />
            {fieldState.error && <Field.Error match>{fieldState.error.message}</Field.Error>}
          </Field.Root>
        )}
      />
      <div>
        <label className="mb-1 block text-sm font-medium">Values</label>
        <div className="space-y-1">
          {valueTags.map((tag) => (
            <div
              key={tag.id}
              className="flex items-center justify-between rounded border px-3 py-1.5 text-sm"
            >
              <span>{tag.label}</span>
              <button
                type="button"
                onClick={() => removeLabel(tag.id)}
                className="text-muted-foreground hover:text-destructive"
              >
                <X className="h-4 w-4" />
              </button>
            </div>
          ))}
        </div>
        <div className="mt-2 flex gap-2">
          <Input
            placeholder="New value label"
            value={newLabelInput}
            onChange={(e) => setNewLabelInput(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter") {
                e.preventDefault();
                addLabel();
              }
            }}
          />
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={addLabel}
            disabled={!newLabelInput.trim()}
          >
            <Plus className="h-4 w-4" />
          </Button>
        </div>
      </div>
      <div className="flex gap-2">
        <Button type="submit" disabled={submitting}>
          {submitting ? "Creating..." : "Create"}
        </Button>
        <Button type="button" variant="outline" onClick={onCancel}>
          Cancel
        </Button>
      </div>
    </Form>
  );
};
