import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { z } from "zod";
import { useServerFn } from "@tanstack/react-start";
import { SiteLayout, PageHero } from "@/components/site/SiteLayout";
import { Mail, MapPin, Send, CheckCircle2, Loader2 } from "lucide-react";
import { submitContact } from "@/lib/contact.functions";

export const Route = createFileRoute("/contact")({
  head: () => ({
    meta: [
      { title: "Contact — Casino API Provider" },
      {
        name: "description",
        content:
          "Request API access, talk to our sales team, or get support. We respond on Telegram, email or live chat.",
      },
      { property: "og:url", content: "/contact" },
    ],
    links: [{ rel: "canonical", href: "/contact" }],
  }),
  component: ContactPage,
});

const schema = z.object({
  name: z.string().trim().min(1).max(120),
  email: z.string().trim().email().max(200),
  company: z.string().trim().max(120).optional(),
  telegram: z.string().trim().max(60).optional(),
  message: z.string().trim().min(10).max(4000),
});

function ContactPage() {
  const submit = useServerFn(submitContact);
  const [sent, setSent] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState(false);

  const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    const parsed = schema.safeParse(Object.fromEntries(fd));
    if (!parsed.success) {
      const out: Record<string, string> = {};
      for (const i of parsed.error.issues) out[String(i.path[0])] = i.message;
      setErrors(out);
      return;
    }
    setErrors({});
    setLoading(true);
    try {
      await submit({ data: { ...parsed.data, source: "api_request" } });
      setSent(true);
    } catch (err: any) {
      setErrors({ message: err?.message ?? "Failed to send" });
    } finally {
      setLoading(false);
    }
  };

  return (
    <SiteLayout>
      <PageHero
        eyebrow="Get API Access"
        title={
          <>
            Talk to our <span className="text-gradient">integration team</span>.
          </>
        }
        description="Request an API key, demo, or pricing for your operation. We typically respond within 1 business hour via Telegram or email."
      />

      <section className="container-page py-16 grid gap-10 lg:grid-cols-[1fr_1.3fr]">
        <div className="space-y-5">
          {[
            { icon: Send, t: "Telegram (fastest)", b: "@casinoapi_support" },
            { icon: Mail, t: "Sales", b: "sales@casino-api.com" },
            { icon: Mail, t: "Support", b: "support@casino-api.com" },
            { icon: MapPin, t: "Coverage", b: "Global · 24/7" },
          ].map(({ icon: Icon, t, b }) => (
            <div key={t} className="surface-card p-5 flex gap-4">
              <div
                className="h-10 w-10 rounded-lg grid place-items-center"
                style={{ background: "var(--gradient-gold)" }}
              >
                <Icon className="h-4 w-4" style={{ color: "oklch(0.13 0.018 280)" }} />
              </div>
              <div>
                <p className="text-xs uppercase tracking-wider text-muted-foreground">{t}</p>
                <p className="mt-0.5 text-sm font-medium">{b}</p>
              </div>
            </div>
          ))}
        </div>

        <form onSubmit={onSubmit} className="surface-card-gold p-6 sm:p-8">
          {sent ? (
            <div className="text-center py-10">
              <CheckCircle2 className="h-10 w-10 text-success mx-auto" />
              <h3 className="mt-4 font-display text-xl font-bold">Request received</h3>
              <p className="mt-2 text-sm text-muted-foreground">
                Our team will reach out shortly via Telegram or email.
              </p>
            </div>
          ) : (
            <>
              <h3 className="font-display text-xl font-bold">Request API Access</h3>
              <div className="mt-6 grid gap-4 sm:grid-cols-2">
                <Field name="name" label="Full name" error={errors.name} />
                <Field name="email" label="Work email" type="email" error={errors.email} />
                <Field name="company" label="Company / Brand" />
                <Field name="telegram" label="Telegram handle" placeholder="@username" />
                <div className="sm:col-span-2">
                  <label className="text-xs uppercase tracking-wider text-muted-foreground">
                    Tell us about your project
                  </label>
                  <textarea
                    name="message"
                    rows={5}
                    placeholder="Markets, expected volume, providers you need…"
                    className="mt-1.5 w-full bg-background/60 border border-border-strong rounded-md px-3 py-2.5 text-sm outline-none focus:border-primary"
                  />
                  {errors.message && <p className="mt-1 text-xs text-destructive">{errors.message}</p>}
                </div>
              </div>
              <button type="submit" disabled={loading} className="mt-6 btn-hero">
                {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : "Request API Access"}
              </button>
            </>
          )}
        </form>
      </section>
    </SiteLayout>
  );
}

function Field({
  name,
  label,
  type = "text",
  error,
  placeholder,
  className = "",
}: {
  name: string;
  label: string;
  type?: string;
  error?: string;
  placeholder?: string;
  className?: string;
}) {
  return (
    <div className={className}>
      <label className="text-xs uppercase tracking-wider text-muted-foreground">{label}</label>
      <input
        name={name}
        type={type}
        placeholder={placeholder}
        className="mt-1.5 w-full bg-background/60 border border-border-strong rounded-md px-3 py-2.5 text-sm outline-none focus:border-primary"
      />
      {error && <p className="mt-1 text-xs text-destructive">{error}</p>}
    </div>
  );
}
