"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Building2, ExternalLink, Sparkles, Send, AlertTriangle } from "lucide-react";
import { Container } from "@/components/container";
import { Button } from "@/components/ui/button";
import { FloatingInput, FloatingTextarea } from "@/components/ui/floating-field";
import {
  PhoneField,
  isValidPhoneNumber,
  formatE164,
  switchCountryValue,
  DEFAULT_COUNTRY,
  type CountryCode,
} from "@/components/ui/phone-field";
import { cn } from "@/lib/utils";

const DEPARTMENTS = [
  "Enterprise Sales",
  "Technical Support",
  "Security & Compliance",
  "Partnerships & Telecom",
] as const;

const schema = z
  .object({
    name: z.string().trim().min(2, "Please enter your full name").max(80),
    email: z.email("Please enter a valid email address"),
    company: z.string().trim().min(1, "Company name is required").max(120),
    // Plain strings (not .default()) so the zod input type === z.infer output
    // type, which is what react-hook-form's Resolver requires. Values are always
    // supplied by defaultValues + setValue.
    phoneCountry: z.string(),
    phone: z.string(),
    message: z
      .string()
      .trim()
      .min(10, "Tell us a little more — at least 10 characters")
      .max(4000, "That's a bit long — please trim it down"),
    department: z.string(),
    // Honeypot — accept any value (so an aggressive autofill can't silently
    // block a real user); the server drops submissions where it's non-empty.
    website: z.string().optional(),
  })
  .superRefine((val, ctx) => {
    if (val.phone && val.phone.trim().length > 0) {
      const valid = isValidPhoneNumber(val.phone, val.phoneCountry as CountryCode);
      if (!valid) {
        ctx.addIssue({
          code: "custom",
          path: ["phone"],
          message: "Enter a valid phone number for the selected country.",
        });
      }
    }
  });

type Values = z.infer<typeof schema>;

export function ContactView() {
  const router = useRouter();
  const [serverError, setServerError] = useState<string | null>(null);

  const {
    register,
    control,
    handleSubmit,
    watch,
    setValue,
    formState: { errors, isSubmitting },
  } = useForm<Values>({
    resolver: zodResolver(schema),
    mode: "onBlur",
    defaultValues: {
      name: "",
      email: "",
      company: "",
      phone: "",
      phoneCountry: DEFAULT_COUNTRY,
      message: "",
      department: "Enterprise Sales",
      website: "",
    },
  });

  // eslint-disable-next-line react-hooks/incompatible-library -- react-hook-form watch() is not memoizable; expected
  const department = watch("department");
  const phoneCountry = watch("phoneCountry") as CountryCode;

  async function onSubmit(values: Values) {
    setServerError(null);
    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...values,
          phone: values.phone ? formatE164(values.phone, values.phoneCountry as CountryCode) : "",
        }),
      });
      const data = (await res.json().catch(() => ({}))) as { ok?: boolean; error?: string };
      if (!res.ok || !data.ok) {
        setServerError(data.error || "Something went wrong on our side. Please try again.");
        return;
      }
      // Only navigate after a genuinely successful response.
      router.push("/thank-you?from=contact");
    } catch {
      setServerError("We couldn't reach the server. Check your connection and try again.");
    }
  }

  return (
    <div className="relative overflow-hidden page-top-space pb-24 md:pb-32">
      {/* Ambient background glow for hero — starts at top: 0 behind fixed header */}
      <div
        aria-hidden="true"
        className="pointer-events-none absolute inset-x-0 top-0 -z-10 mx-auto h-96 w-full max-w-6xl bg-gradient-to-r from-[#4FDAF1]/20 via-[#F79C09]/15 to-[#E26B0B]/20 blur-3xl"
      />

      <Container className="mx-auto w-full max-w-6xl px-5 md:px-8">
        {/* Breadcrumb */}
        <nav aria-label="Breadcrumb" className="mb-8 flex items-center gap-2 text-xs font-medium text-muted-foreground">
          <Link href="/" className="cursor-pointer transition hover:text-foreground">
            Home
          </Link>
          <span aria-hidden>/</span>
          <span className="text-foreground">Contact</span>
        </nav>

        {/* Hero */}
        <div className="mb-12 max-w-3xl">
          <div className="mb-3 inline-flex items-center gap-2 rounded-full border border-[var(--accent-cyan-text)]/30 bg-[var(--accent-cyan-text)]/10 px-3 py-1 text-xs font-semibold text-[var(--accent-cyan-text)]">
            <Sparkles className="h-3.5 w-3.5" />
            Get in touch
          </div>
          <h1 className="font-display text-4xl font-extrabold tracking-tight text-foreground sm:text-5xl lg:text-6xl">
            Contact <span className="text-gradient-brand">Quto AI</span>
          </h1>
          <p className="mt-5 text-lg leading-relaxed text-muted-foreground sm:text-xl">
            Quto AI builds multilingual voice agents for inbound and outbound calls, chat, and
            WhatsApp. Reach out and our team will get back to you.
          </p>
        </div>

        <div className="grid grid-cols-1 gap-12 lg:grid-cols-12 lg:gap-14">
          {/* Form — appears first on mobile (§40) */}
          <div className="order-1 lg:order-2 lg:col-span-6">
            <div className="rounded-3xl border border-border/80 bg-card p-6 shadow-sm sm:p-8">
              <div className="mb-2 text-xs font-bold uppercase tracking-wider text-[var(--accent-cyan-text)]">
                Send a message
              </div>
              <h2 className="font-display text-2xl font-bold tracking-tight text-foreground">
                Connect directly with our team
              </h2>
              <p className="mt-1 text-xs text-muted-foreground sm:text-sm">
                Pick a topic and we&apos;ll route your message to the right specialists.
              </p>

              {/* Department selector */}
              <div className="mt-6">
                <span className="block text-xs font-bold uppercase tracking-wider text-muted-foreground">
                  Inquiry department
                </span>
                <div className="mt-2 flex flex-wrap gap-2" role="group" aria-label="Inquiry department">
                  {DEPARTMENTS.map((dept) => {
                    const selected = department === dept;
                    return (
                      <button
                        key={dept}
                        type="button"
                        aria-pressed={selected}
                        onClick={() => setValue("department", dept)}
                        className={cn(
                          "cursor-pointer rounded-xl px-3 py-1.5 text-xs font-semibold transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-card",
                          selected
                            ? "bg-gradient-brand text-white font-bold shadow-xs glow-brand"
                            : "border border-border bg-muted/40 text-muted-foreground hover:bg-muted hover:text-foreground",
                        )}
                      >
                        {dept}
                      </button>
                    );
                  })}
                </div>
              </div>

              <form onSubmit={handleSubmit(onSubmit)} className="mt-6 space-y-4" noValidate>
                {/* Honeypot */}
                <div aria-hidden className="pointer-events-none absolute left-[-9999px] h-0 w-0 overflow-hidden">
                  <label htmlFor="c-website">Company website</label>
                  <input id="c-website" type="text" tabIndex={-1} autoComplete="off" {...register("website")} />
                </div>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                  <FloatingInput
                    id="c-name"
                    label="Full name"
                    autoComplete="name"
                    error={errors.name?.message}
                    {...register("name")}
                  />
                  <FloatingInput
                    id="c-email"
                    label="Work email"
                    type="email"
                    autoComplete="email"
                    error={errors.email?.message}
                    {...register("email")}
                  />
                </div>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                  <FloatingInput
                    id="c-company"
                    label="Company"
                    autoComplete="organization"
                    error={errors.company?.message}
                    {...register("company")}
                  />
                  <Controller
                    name="phone"
                    control={control}
                    render={({ field }) => (
                      <PhoneField
                        id="c-phone"
                        label="Phone (optional)"
                        country={phoneCountry}
                        onCountryChange={(code) => {
                          const currentPhone = watch("phone");
                          const adaptedPhone = switchCountryValue(
                            currentPhone,
                            phoneCountry,
                            code,
                          );
                          setValue("phoneCountry", code);
                          setValue("phone", adaptedPhone, { shouldValidate: true });
                        }}
                        value={field.value}
                        onChange={field.onChange}
                        onBlur={field.onBlur}
                        name={field.name}
                        ref={field.ref}
                        error={errors.phone?.message}
                      />
                    )}
                  />
                </div>

                <FloatingTextarea
                  id="c-message"
                  label="How can our team help?"
                  rows={4}
                  error={errors.message?.message}
                  {...register("message")}
                />

                {serverError && (
                  <div
                    role="alert"
                    className="flex items-start gap-2.5 rounded-xl border border-destructive/40 bg-destructive/10 p-3 text-xs font-medium text-destructive motion-safe:animate-in motion-safe:fade-in"
                  >
                    <AlertTriangle className="mt-px size-4 shrink-0" />
                    <span>{serverError}</span>
                  </div>
                )}

                <div className="pt-1">
                  <Button
                    type="submit"
                    variant="accent"
                    size="pill"
                    loading={isSubmitting}
                    className="w-full"
                  >
                    {isSubmitting ? (
                      "Sending…"
                    ) : (
                      <span className="inline-flex items-center gap-2">
                        <Send className="size-4" />
                        Send message
                      </span>
                    )}
                  </Button>
                </div>

                <p className="text-center text-xs text-muted-foreground">
                  Under zero-retention privacy, your inquiry data is never shared or sold.
                </p>
              </form>
            </div>
          </div>

          {/* Contact directory — second on mobile */}
          <div className="order-2 space-y-6 lg:order-1 lg:col-span-6">
            <div className="overflow-hidden rounded-3xl border border-border/80 bg-card shadow-sm">
              <div className="flex items-center justify-between border-b border-border/80 bg-muted/30 px-6 py-4">
                <div className="flex items-center gap-2.5">
                  <Building2 className="h-4 w-4 text-[#4FDAF1]" />
                  <span className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
                    Direct Contact Directory
                  </span>
                </div>
                <span className="flex items-center gap-1.5 text-xs font-semibold text-foreground">
                  <span className="h-2 w-2 rounded-full bg-[#4FDAF1] shadow-[0_0_8px_rgba(79,218,241,0.8)] motion-safe:animate-pulse" />
                  Available now
                </span>
              </div>

              <div className="divide-y divide-border/60">
                {[
                  { label: "General Inquiries", email: "quto.official@gmail.com" },
                  { label: "Sales & Enterprise", email: "quto.official@gmail.com", note: "Direct Inquiry" },
                  { label: "Client Support", email: "quto.official@gmail.com", note: "Dedicated Team" },
                ].map((row) => (
                  <div key={row.label} className="p-6 transition-colors hover:bg-muted/20">
                     <div className="flex items-center justify-between">
                      <div className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
                        {row.label}
                      </div>
                      {row.note && (
                        <span className="text-[11px] font-medium text-muted-foreground">{row.note}</span>
                      )}
                    </div>
                    <div className="mt-1">
                      <a
                        href={`mailto:${row.email}`}
                        className="cursor-pointer text-base font-semibold text-foreground underline-offset-4 hover:underline"
                      >
                        {row.email}
                      </a>
                    </div>
                  </div>
                ))}

                <div className="p-6 transition-colors hover:bg-muted/20">
                  <div className="text-xs font-bold uppercase tracking-wider text-muted-foreground">Phone</div>
                  <div className="mt-1">
                    <a
                      href="tel:+919680621321"
                      className="cursor-pointer text-base font-semibold text-foreground underline-offset-4 hover:underline"
                    >
                      +91 96806 21321
                    </a>
                  </div>
                </div>

                <div className="p-6 transition-colors hover:bg-muted/20">
                  <div className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
                    Social profiles
                  </div>
                  <div className="mt-3 flex flex-wrap gap-2">
                    {[
                      { name: "Instagram", href: "https://www.instagram.com/qutoai" },
                      { name: "Facebook", href: "https://www.facebook.com/qutoai" },
                      { name: "LinkedIn", href: "https://www.linkedin.com/company/qutoai" },
                    ].map((p) => (
                      <a
                        key={p.name}
                        href={p.href}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="inline-flex cursor-pointer items-center gap-1.5 rounded-lg border border-border bg-background px-3 py-1.5 text-xs font-medium text-foreground transition hover:border-foreground hover:bg-muted"
                      >
                        <span>{p.name}</span>
                        <ExternalLink className="h-3 w-3 opacity-50" />
                      </a>
                    ))}
                  </div>
                </div>
              </div>
            </div>

          </div>
        </div>
      </Container>
    </div>
  );
}
