import { createFileRoute, Link } from '@tanstack/react-router';
import Breadcrumbs from "@/components/Breadcrumbs";
import { useState } from 'react';
import { useServerFn } from '@tanstack/react-start';
import { Mail, Send, MessageCircle, Facebook, Instagram, AlertCircle, ArrowRight, CheckCircle2, Loader2 } from 'lucide-react';
import { motion } from 'framer-motion';
import RelatedLinks from '@/components/RelatedLinks';
import { getRelatedLinks } from '@/lib/relatedLinks';
import { Turnstile, resetTurnstile } from '@/components/Turnstile';
import { submitContactForm } from '@/lib/contact.functions';
import heroContact from '@/assets/hero-contact.jpg';
import { useT, useLang, headLang, localizePath, SITE_URL } from '@/lib/i18n';

export const Route = createFileRoute('/contact-us')({
  head: (ctx) => {
    const lang = headLang(ctx);
    const path = localizePath('/contact-us', lang);
    const title = lang === 'en' ? 'Contact — Peptidewinkel | WhatsApp & email support' : 'Contact — Peptidewinkel | WhatsApp & e-mail support';
    const description = lang === 'en'
      ? 'Get in touch with Peptidewinkel via WhatsApp, email or the contact form. Questions about peptides, lab reports or an order? We are happy to help.'
      : 'Neem contact op met Peptidewinkel via WhatsApp, e-mail of het contactformulier. Vragen over peptides, labrapporten of een bestelling? Wij helpen je verder.';
    const ogTitle = lang === 'en' ? 'Contact — Peptidewinkel' : 'Contact — Peptidewinkel';
    return {
      meta: [
        { title },
        { name: 'description', content: description },
        { property: 'og:title', content: ogTitle },
        { property: 'og:description', content: 'WhatsApp: +3197010283889 · Email: info@peptidewinkel.com' },
        { property: 'og:url', content: `${SITE_URL}${path}` },
      ],
      links: [{ rel: 'canonical', href: `${SITE_URL}${path}` }],
    };
  },
  component: ContactPage,
});

const TelegramIcon = ({ className }: { className?: string }) => (
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className={className}>
    <path d="M11.944 0A12 12 0 000 12a12 12 0 0012 12 12 12 0 0012-12A12 12 0 0012 0 12 12 0 0011.944 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 01.171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.479.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z" />
  </svg>
);

const fadeUp = { initial: { opacity: 0, y: 30 }, whileInView: { opacity: 1, y: 0 }, viewport: { once: true, margin: '-50px' } };

function ContactPage() {
  const t = useT();
  const lang = useLang();

  const contactItems = [
    { Icon: MessageCircle, label: t('WhatsApp', 'WhatsApp'), value: '+31 970 102 838 89', sub: t('Snelste manier om ons te bereiken', 'Fastest way to reach us'), href: 'https://wa.me/3197010283889', badge: t('Snelst', 'Fastest') as string | undefined },
    { Icon: Mail, label: t('E-mail, orders & aftersales', 'Email, orders & aftersales'), value: 'info@peptidewinkel.com', sub: t('Reactie binnen 1–3 werkdagen', 'Response within 1–3 working days'), href: 'mailto:info@peptidewinkel.com', badge: undefined as string | undefined },
    { Icon: TelegramIcon, label: t('Telegram-kanaal', 'Telegram channel'), value: t('Volg ons op Telegram', 'Follow us on Telegram'), sub: t('Updates en nieuws — geen DM-support', 'Updates and news — no DM support'), href: 'https://t.me/+Flllg3K_W9NhZjk0', badge: undefined as string | undefined },
  ];

  const socialItems = [
    { Icon: Facebook, label: 'Facebook', value: 'PeptideWinkel', href: 'https://www.facebook.com/PeptideWinkel' },
    { Icon: Instagram, label: 'Instagram', value: '@peptide_winkel', href: 'https://www.instagram.com/peptide_winkel' },
  ];

  const [form, setForm] = useState({ name: '', email: '', message: '' });
  const [token, setToken] = useState<string>('');
  const [submitting, setSubmitting] = useState(false);
  const [done, setDone] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const submit = useServerFn(submitContactForm);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    if (!form.name.trim() || !form.email.trim() || form.message.trim().length < 5) {
      setError(t('Vul alle verplichte velden in (bericht min. 5 tekens).', 'Please fill in all required fields (message min. 5 characters).'));
      return;
    }
    if (!token) {
      setError(t('Bevestig eerst de captcha.', 'Please confirm the captcha first.'));
      return;
    }
    setSubmitting(true);
    try {
      const res = await submit({ data: { ...form, turnstile_token: token } });
      if (res.ok) {
        setDone(true);
        setForm({ name: '', email: '', message: '' });
      } else {
        setError(res.error ?? t('Verzenden mislukt', 'Sending failed'));
        resetTurnstile();
        setToken('');
      }
    } catch (err) {
      console.error(err);
      setError(t('Er ging iets mis. Probeer het opnieuw.', 'Something went wrong. Please try again.'));
      resetTurnstile();
      setToken('');
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="overflow-hidden">
      <Breadcrumbs items={[{ label: t('Contact', 'Contact') }]} />
      <section className="relative min-h-[360px] md:min-h-[440px] overflow-hidden">
        <img src={heroContact} alt={t('Contact opnemen met Peptidewinkel klantenservice — Nederlandstalige support voor research peptiden', 'Contacting Peptidewinkel customer service — Dutch-language support for research peptides')} width={1920} height={1080} loading="eager" decoding="async" className="absolute inset-0 w-full h-full object-cover" />
        <div className="absolute inset-0 bg-gradient-to-r from-black/85 via-black/70 to-black/40" />
        <div className="absolute inset-0 bg-molecule-grid opacity-40" />
        <div className="container relative z-10 text-center py-20 md:py-24">
          <motion.p {...fadeUp} transition={{ duration: 0.5 }} className="lab-label inline-block mb-4 border-white/30 text-white bg-white/5">CONTACT</motion.p>
          <motion.h1 {...fadeUp} transition={{ duration: 0.6, delay: 0.1 }} className="text-4xl md:text-6xl font-display font-extrabold text-white mb-5 tracking-tight">
            {t('Neem contact op met', 'Get in touch with')} <span className="text-gradient-primary">Peptidewinkel</span>
          </motion.h1>
          <motion.p {...fadeUp} transition={{ duration: 0.6, delay: 0.2 }} className="text-white/75 max-w-xl mx-auto text-lg leading-relaxed">
            {t('Vragen over een peptide, een labrapport of je bestelling? Stuur ons een bericht — wij reageren snel en discreet.', 'Questions about a peptide, a lab report or your order? Send us a message — we respond quickly and discreetly.')}
          </motion.p>
        </div>
      </section>

      <section className="container py-16">
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4 mb-12">
          {contactItems.map((item, i) => (
            <motion.a key={item.label} {...fadeUp} transition={{ duration: 0.5, delay: i * 0.05 }} href={item.href} target={item.href.startsWith('http') ? '_blank' : undefined} rel="noopener noreferrer" className="glass-card-premium p-6 flex items-start gap-4">
              <div className="w-12 h-12 rounded-md gradient-primary flex items-center justify-center shrink-0 shadow-glow-soft">
                <item.Icon className="w-5 h-5 text-white" />
              </div>
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2 mb-1">
                  <h3 className="font-display font-bold text-sm">{item.label}</h3>
                  {item.badge && <span className="lab-label !py-0">{item.badge}</span>}
                </div>
                <p className="text-sm text-foreground font-medium truncate">{item.value}</p>
                <p className="text-xs text-muted-foreground mt-1">{item.sub}</p>
              </div>
            </motion.a>
          ))}
        </div>

        <div className="flex flex-wrap justify-center gap-3 -mt-6 mb-12">
          {socialItems.map((s) => (
            <a key={s.label} href={s.href} target="_blank" rel="noopener noreferrer" aria-label={t(`Peptidewinkel op ${s.label}`, `Peptidewinkel on ${s.label}`)} className="inline-flex items-center gap-2 px-4 py-2 rounded-full border border-border bg-card text-sm font-medium hover:border-primary/50 hover:text-primary transition-colors">
              <s.Icon className="w-4 h-4" /> {s.label} <span className="text-muted-foreground">{s.value}</span>
            </a>
          ))}
        </div>

        <div className="max-w-2xl mx-auto">
          <motion.div {...fadeUp} transition={{ duration: 0.6 }} className="glass-card-premium p-8 md:p-10">
            <p className="lab-label inline-block mb-3">{t('CONTACTFORMULIER', 'CONTACT FORM')}</p>
            <h2 className="text-display text-2xl md:text-3xl mb-2">{t('Stuur ons een bericht', 'Send us a message')}</h2>
            <p className="text-sm text-muted-foreground mb-6">{t('Vul het formulier in, dan ontvang je binnen 1–3 werkdagen een reactie per e-mail. Sneller antwoord nodig? App ons via WhatsApp. Liever direct mailen? Dat kan via', 'Fill in the form and you will receive a reply by email within 1–3 working days. Need a faster answer? Message us on WhatsApp. Prefer to email directly? You can reach us at')} <span className="font-mono text-foreground">info@peptidewinkel.com</span>.</p>

            {done ? (
              <div className="text-center py-8">
                <CheckCircle2 className="w-12 h-12 text-success mx-auto mb-3" />
                <h3 className="font-display font-bold text-lg mb-2">{t('Bericht verzonden', 'Message sent')}</h3>
                <p className="text-sm text-muted-foreground">{t('We nemen zo snel mogelijk contact met je op.', 'We will get back to you as soon as possible.')}</p>
              </div>
            ) : (
              <form onSubmit={handleSubmit} className="space-y-4">
                <div className="grid sm:grid-cols-2 gap-4">
                  <div>
                    <label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground mb-1.5 block">{t('Naam', 'Name')}</label>
                    <input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} className="w-full px-3 py-2.5 rounded-md bg-background text-foreground border border-border text-sm focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none" required />
                  </div>
                  <div>
                    <label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground mb-1.5 block">{t('E-mail', 'Email')}</label>
                    <input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} className="w-full px-3 py-2.5 rounded-md bg-background text-foreground border border-border text-sm focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none" required />
                  </div>
                </div>
                <div>
                  <label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground mb-1.5 block">{t('Bericht', 'Message')}</label>
                  <textarea value={form.message} onChange={(e) => setForm({ ...form, message: e.target.value })} rows={5} className="w-full px-3 py-2.5 rounded-md bg-background text-foreground border border-border text-sm focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none resize-none" required />
                </div>
                <Turnstile action="contact" onVerify={setToken} />
                {error && (
                  <div className="flex items-start gap-2 text-sm text-destructive bg-destructive/10 p-3 rounded-md">
                    <AlertCircle className="w-4 h-4 shrink-0 mt-0.5" />
                    <span>{error}</span>
                  </div>
                )}
                <button type="submit" disabled={submitting} className="w-full gradient-primary text-white font-bold py-3 rounded-md hover:shadow-gold transition-all text-sm uppercase tracking-wide flex items-center justify-center gap-2 disabled:opacity-60">
                  {submitting ? <><Loader2 className="w-4 h-4 animate-spin" /> {t('Verzenden...', 'Sending...')}</> : <><Send className="w-4 h-4" /> {t('Verstuur bericht', 'Send message')}</>}
                </button>
              </form>
            )}
          </motion.div>

          <div className="mt-8 text-center">
            <Link to="/veelgestelde-vragen" className="inline-flex items-center gap-2 text-sm text-primary font-semibold hover:underline">
              {t('Bekijk eerst onze FAQ', 'Check our FAQ first')} <ArrowRight className="w-4 h-4" />
            </Link>
          </div>
        </div>
      </section>

      <RelatedLinks title={t('Mogelijk ook nuttig', 'Also useful')} subtitle={t('Snel een antwoord op je vraag of meer over onze service.', 'Quick answers to your questions or more about our service.')} links={getRelatedLinks('contact', lang)} />
    </div>
  );
}
