import { motion } from "framer-motion";
import { Send, CheckCircle, AlertCircle, Loader2 } from "lucide-react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useSendContactMessage } from "@workspace/api-client-react";


const contactSchema = z.object({
  name: z.string().min(1, "Bitte geben Sie Ihren Namen ein").max(100),
  email: z.string().email("Bitte geben Sie eine gültige E-Mail-Adresse ein").max(200),
  subject: z.string().max(200).optional(),
  message: z.string().min(1, "Bitte geben Sie eine Nachricht ein").max(5000, "Die Nachricht ist zu lang (max. 5000 Zeichen)"),
});

type ContactFormData = z.infer<typeof contactSchema>;

function ContactForm() {
  const [status, setStatus] = useState<"idle" | "success" | "error">("idle");
  const [serverMessage, setServerMessage] = useState("");

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<ContactFormData>({
    resolver: zodResolver(contactSchema),
  });

  const { mutate: sendMessage, isPending } = useSendContactMessage({
    mutation: {
      onSuccess: (data) => {
        setServerMessage(data.message);
        setStatus("success");
        reset();
      },
      onError: (err: unknown) => {
        const apiErr = err as { data?: { message?: string } };
        setServerMessage(
          apiErr?.data?.message ??
            "Die Nachricht konnte nicht gesendet werden. Bitte versuchen Sie es später erneut.",
        );
        setStatus("error");
      },
    },
  });

  const onSubmit = (data: ContactFormData) => {
    setStatus("idle");
    sendMessage({ data: { name: data.name, email: data.email, subject: data.subject, message: data.message } });
  };

  if (status === "success") {
    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="flex flex-col items-center justify-center gap-4 p-8 rounded-2xl bg-green-50 border border-green-200 text-center"
        data-testid="contact-form-success"
      >
        <CheckCircle className="w-10 h-10 text-green-500" />
        <div>
          <p className="font-semibold text-green-800 text-lg">Nachricht gesendet!</p>
          <p className="text-green-700 text-sm mt-1">{serverMessage}</p>
        </div>
        <button
          onClick={() => setStatus("idle")}
          className="mt-2 text-sm text-green-700 underline underline-offset-2 hover:text-green-900 transition-colors"
        >
          Weitere Nachricht senden
        </button>
      </motion.div>
    );
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4" noValidate data-testid="contact-form">
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div className="flex flex-col gap-1.5">
          <label htmlFor="contact-name" className="text-sm font-medium text-foreground">
            Name <span className="text-red-500">*</span>
          </label>
          <input
            id="contact-name"
            type="text"
            autoComplete="name"
            placeholder="Max Mustermann"
            className={`rounded-xl border px-4 py-2.5 text-sm bg-white text-foreground placeholder:text-muted-foreground outline-none transition-colors focus:ring-2 focus:ring-primary/30 focus:border-primary ${errors.name ? "border-red-400" : "border-border"}`}
            data-testid="input-contact-name"
            {...register("name")}
          />
          {errors.name && (
            <p className="text-xs text-red-500">{errors.name.message}</p>
          )}
        </div>
        <div className="flex flex-col gap-1.5">
          <label htmlFor="contact-email" className="text-sm font-medium text-foreground">
            E-Mail <span className="text-red-500">*</span>
          </label>
          <input
            id="contact-email"
            type="email"
            autoComplete="email"
            placeholder="max@beispiel.de"
            className={`rounded-xl border px-4 py-2.5 text-sm bg-white text-foreground placeholder:text-muted-foreground outline-none transition-colors focus:ring-2 focus:ring-primary/30 focus:border-primary ${errors.email ? "border-red-400" : "border-border"}`}
            data-testid="input-contact-email"
            {...register("email")}
          />
          {errors.email && (
            <p className="text-xs text-red-500">{errors.email.message}</p>
          )}
        </div>
      </div>

      <div className="flex flex-col gap-1.5">
        <label htmlFor="contact-subject" className="text-sm font-medium text-foreground">
          Betreff <span className="text-muted-foreground font-normal">(optional)</span>
        </label>
        <input
          id="contact-subject"
          type="text"
          placeholder="Worum geht es?"
          className="rounded-xl border border-border px-4 py-2.5 text-sm bg-white text-foreground placeholder:text-muted-foreground outline-none transition-colors focus:ring-2 focus:ring-primary/30 focus:border-primary"
          data-testid="input-contact-subject"
          {...register("subject")}
        />
      </div>

      <div className="flex flex-col gap-1.5">
        <label htmlFor="contact-message" className="text-sm font-medium text-foreground">
          Nachricht <span className="text-red-500">*</span>
        </label>
        <textarea
          id="contact-message"
          rows={5}
          placeholder="Ihre Nachricht..."
          className={`rounded-xl border px-4 py-2.5 text-sm bg-white text-foreground placeholder:text-muted-foreground outline-none transition-colors focus:ring-2 focus:ring-primary/30 focus:border-primary resize-none ${errors.message ? "border-red-400" : "border-border"}`}
          data-testid="input-contact-message"
          {...register("message")}
        />
        {errors.message && (
          <p className="text-xs text-red-500">{errors.message.message}</p>
        )}
      </div>

      {status === "error" && (
        <div className="flex items-start gap-2 p-3 rounded-xl bg-red-50 border border-red-200 text-sm text-red-700" data-testid="contact-form-error">
          <AlertCircle className="w-4 h-4 shrink-0 mt-0.5" />
          <span>{serverMessage}</span>
        </div>
      )}

      <p className="text-xs text-muted-foreground">
        Ihre Daten werden ausschließlich zur Bearbeitung Ihrer Anfrage verwendet und nicht an Dritte weitergegeben.
      </p>

      <button
        type="submit"
        disabled={isPending}
        className="flex items-center justify-center gap-2 px-6 py-3 rounded-xl bg-primary text-white font-semibold text-sm hover:bg-primary/90 disabled:opacity-60 disabled:cursor-not-allowed transition-colors"
        data-testid="button-contact-submit"
      >
        {isPending ? (
          <>
            <Loader2 className="w-4 h-4 animate-spin" />
            Wird gesendet…
          </>
        ) : (
          <>
            <Send className="w-4 h-4" />
            Nachricht senden
          </>
        )}
      </button>
    </form>
  );
}

export function Contact() {
  return (
    <div className="py-24">
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        whileInView={{ opacity: 1, y: 0 }}
        viewport={{ once: true, margin: "-80px" }}
        transition={{ duration: 0.6 }}
      >
        <div className="max-w-4xl mx-auto">
          <div className="text-center mb-12">
            <p className="section-number mb-3" data-testid="text-section-label-contact">Kontakt</p>
            <h2 className="text-3xl md:text-4xl font-bold text-foreground mb-4" data-testid="text-section-title-contact">
              Bereit für das nächste Projekt?
            </h2>
            <p className="text-muted-foreground text-lg max-w-xl mx-auto">
              Ob Infrastruktur-Modernisierung, KI-Automation oder technische Dokumentation — ich freue mich auf Ihre Anfrage.
            </p>
          </div>

          <div className="rounded-2xl bg-white border border-border p-6 md:p-8 shadow-sm">
            <h3 className="text-lg font-semibold text-foreground mb-5">Direkt schreiben</h3>
            <ContactForm />
          </div>

          <div className="mt-12 pt-8 border-t border-border text-center text-sm text-muted-foreground">
            Joachim Hummel &mdash; Senior IT-Consultant &middot; München
          </div>
        </div>
      </motion.div>
    </div>
  );
}
