import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useForm } from "@tanstack/react-form";
import { useMutation } from "@tanstack/react-query";
import { ArrowLeft, Sparkles } from "lucide-react";
import { toast } from "sonner";
import { z } from "zod";

import type { User } from "@rubis/shared";
import { api } from "@/lib/api";
import { authStore, useAuth } from "@/lib/auth";
import { Button } from "@/components/ui/Button";
import { Textarea } from "@/components/ui/Textarea";
import { Field } from "@/components/ui/Field";
import { Card } from "@/components/ui/Card";
import { Eyebrow } from "@/components/ui/Eyebrow";

const signatureSchema = z.object({
  signature: z.string().max(500, "500 caractères maximum"),
});

type SignatureInput = z.infer<typeof signatureSchema>;

const DEFAULT_SIGNATURE = (fullName: string): string =>
  `Cordialement,\n${fullName}\n— Envoyé via Rubis`;

export const Route = createFileRoute("/onboarding/signature")({
  component: OnboardingSignature,
});

function OnboardingSignature() {
  const navigate = useNavigate();
  const { user } = useAuth();

  const updateProfile = useMutation({
    mutationFn: async (input: SignatureInput) =>
      api.patch<User>("/api/v1/account/profile", input),
    onSuccess: (updatedUser) => {
      const token = authStore.token;
      if (token) authStore.setSession(token, updatedUser);
      toast.success("Tout est prêt. Bienvenue chez Rubis.");
      // Pas de dashboard encore — /  sera le bon endroit une fois le
      // layout _app et la route _app/index construits.
      void navigate({ to: "/" });
    },
    onError: () => {
      toast.error("On n'a pas pu enregistrer. Réessayez dans un instant.");
    },
  });

  const form = useForm({
    defaultValues: {
      signature:
        user?.signature ?? DEFAULT_SIGNATURE(user?.fullName ?? "Votre nom"),
    } satisfies SignatureInput,
    validators: { onChange: signatureSchema },
    onSubmit: async ({ value }) => {
      await updateProfile.mutateAsync(value);
    },
  });

  return (
    <div>
      <Eyebrow>Étape 3</Eyebrow>
      <h1 className="mt-3 font-display text-[34px] font-bold leading-[1.1] tracking-[-0.022em] text-ink">
        Votre <em>signature</em>.
      </h1>
      <p className="mt-3 max-w-md text-[15px] leading-relaxed text-ink-2">
        Apposée à la fin de chaque relance envoyée par Rubis. On a pré-rempli
        un standard sobre — vous pouvez l&apos;ajuster.
      </p>

      <form
        noValidate
        onSubmit={(e) => {
          e.preventDefault();
          void form.handleSubmit();
        }}
        className="mt-10 flex flex-col gap-6"
      >
        <form.Field name="signature">
          {(field) => (
            <>
              <Field
                label="Signature email"
                htmlFor={field.name}
                hint="Markdown léger non interprété. Pas de HTML."
                error={field.state.meta.errors[0]?.message}
              >
                <Textarea
                  id={field.name}
                  name={field.name}
                  rows={6}
                  value={field.state.value}
                  onBlur={field.handleBlur}
                  onChange={(e) => field.handleChange(e.target.value)}
                  aria-invalid={field.state.meta.errors.length > 0}
                />
              </Field>

              <Card variant="flat" padding="md" className="mt-2">
                <p className="flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.12em] text-ink-3">
                  <Sparkles size={12} aria-hidden="true" /> Aperçu dans un email
                </p>
                <pre className="mt-3 whitespace-pre-wrap font-sans text-[14px] leading-relaxed text-ink-2">
                  {field.state.value || "(signature vide)"}
                </pre>
              </Card>
            </>
          )}
        </form.Field>

        <div className="mt-3 flex items-center justify-between">
          <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={() => navigate({ to: "/onboarding/entreprise" })}
          >
            <ArrowLeft size={15} aria-hidden="true" /> Retour
          </Button>
          <Button type="submit" loading={updateProfile.isPending}>
            Terminer
          </Button>
        </div>
      </form>
    </div>
  );
}
